2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
23 #include "cl_dyntexture.h"
31 mempool_t *r_main_mempool;
32 rtexturepool_t *r_main_texturepool;
34 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
36 static qboolean r_loadnormalmap;
37 static qboolean r_loadgloss;
39 static qboolean r_loaddds;
40 static qboolean r_savedds;
47 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
48 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
49 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
50 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
51 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)"};
52 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
53 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
54 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
56 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
57 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"};
58 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
59 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)"};
60 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
62 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"};
63 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
64 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
65 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
66 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
67 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
68 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)"};
69 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
70 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
71 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"};
72 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"};
73 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
74 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"};
75 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"};
76 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"};
77 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
78 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
79 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
80 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
81 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
82 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
83 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)"};
84 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)"};
85 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
86 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
87 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
88 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
89 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
90 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
91 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
92 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."};
93 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
94 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
95 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
96 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."};
97 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
98 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
99 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
100 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
101 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"};
102 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"};
103 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
104 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
105 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
106 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
107 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"};
109 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
110 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
111 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
112 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
113 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
114 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
115 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
116 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
118 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)"};
119 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"};
121 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
122 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
123 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
124 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
125 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
127 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
128 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
129 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
131 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)"};
132 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
133 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
134 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
135 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
136 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)"};
137 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)"};
138 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)"};
139 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)"};
141 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)"};
142 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
143 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"};
144 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
145 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
147 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
148 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
149 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
150 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
152 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
153 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
154 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
155 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
156 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
157 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
158 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
160 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
161 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
162 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
163 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)"};
165 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"};
167 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"};
169 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
171 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
172 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"};
173 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
174 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
175 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
176 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
177 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)"};
179 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
181 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)"};
183 extern cvar_t v_glslgamma;
185 extern qboolean v_flipped_state;
187 static struct r_bloomstate_s
192 int bloomwidth, bloomheight;
194 int screentexturewidth, screentextureheight;
195 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
197 int bloomtexturewidth, bloomtextureheight;
198 rtexture_t *texture_bloom;
200 // arrays for rendering the screen passes
201 float screentexcoord2f[8];
202 float bloomtexcoord2f[8];
203 float offsettexcoord2f[8];
205 r_viewport_t viewport;
209 r_waterstate_t r_waterstate;
211 /// shadow volume bsp struct with automatically growing nodes buffer
214 rtexture_t *r_texture_blanknormalmap;
215 rtexture_t *r_texture_white;
216 rtexture_t *r_texture_grey128;
217 rtexture_t *r_texture_black;
218 rtexture_t *r_texture_notexture;
219 rtexture_t *r_texture_whitecube;
220 rtexture_t *r_texture_normalizationcube;
221 rtexture_t *r_texture_fogattenuation;
222 rtexture_t *r_texture_fogheighttexture;
223 rtexture_t *r_texture_gammaramps;
224 unsigned int r_texture_gammaramps_serial;
225 //rtexture_t *r_texture_fogintensity;
226 rtexture_t *r_texture_reflectcube;
228 // TODO: hash lookups?
229 typedef struct cubemapinfo_s
236 int r_texture_numcubemaps;
237 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
239 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
240 unsigned int r_numqueries;
241 unsigned int r_maxqueries;
243 typedef struct r_qwskincache_s
245 char name[MAX_QPATH];
246 skinframe_t *skinframe;
250 static r_qwskincache_t *r_qwskincache;
251 static int r_qwskincache_size;
253 /// vertex coordinates for a quad that covers the screen exactly
254 const float r_screenvertex3f[12] =
262 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
265 for (i = 0;i < verts;i++)
276 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
279 for (i = 0;i < verts;i++)
289 // FIXME: move this to client?
292 if (gamemode == GAME_NEHAHRA)
294 Cvar_Set("gl_fogenable", "0");
295 Cvar_Set("gl_fogdensity", "0.2");
296 Cvar_Set("gl_fogred", "0.3");
297 Cvar_Set("gl_foggreen", "0.3");
298 Cvar_Set("gl_fogblue", "0.3");
300 r_refdef.fog_density = 0;
301 r_refdef.fog_red = 0;
302 r_refdef.fog_green = 0;
303 r_refdef.fog_blue = 0;
304 r_refdef.fog_alpha = 1;
305 r_refdef.fog_start = 0;
306 r_refdef.fog_end = 16384;
307 r_refdef.fog_height = 1<<30;
308 r_refdef.fog_fadedepth = 128;
309 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
312 static void R_BuildBlankTextures(void)
314 unsigned char data[4];
315 data[2] = 128; // normal X
316 data[1] = 128; // normal Y
317 data[0] = 255; // normal Z
318 data[3] = 128; // height
319 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
324 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
329 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
334 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
337 static void R_BuildNoTexture(void)
340 unsigned char pix[16][16][4];
341 // this makes a light grey/dark grey checkerboard texture
342 for (y = 0;y < 16;y++)
344 for (x = 0;x < 16;x++)
346 if ((y < 8) ^ (x < 8))
362 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
365 static void R_BuildWhiteCube(void)
367 unsigned char data[6*1*1*4];
368 memset(data, 255, sizeof(data));
369 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
372 static void R_BuildNormalizationCube(void)
376 vec_t s, t, intensity;
379 data = Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
380 for (side = 0;side < 6;side++)
382 for (y = 0;y < NORMSIZE;y++)
384 for (x = 0;x < NORMSIZE;x++)
386 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
387 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
422 intensity = 127.0f / sqrt(DotProduct(v, v));
423 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
424 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
425 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
426 data[((side*64+y)*64+x)*4+3] = 255;
430 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
434 static void R_BuildFogTexture(void)
438 unsigned char data1[FOGWIDTH][4];
439 //unsigned char data2[FOGWIDTH][4];
442 r_refdef.fogmasktable_start = r_refdef.fog_start;
443 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
444 r_refdef.fogmasktable_range = r_refdef.fogrange;
445 r_refdef.fogmasktable_density = r_refdef.fog_density;
447 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
448 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
450 d = (x * r - r_refdef.fogmasktable_start);
451 if(developer_extra.integer)
452 Con_DPrintf("%f ", d);
454 if (r_fog_exp2.integer)
455 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
457 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
458 if(developer_extra.integer)
459 Con_DPrintf(" : %f ", alpha);
460 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
461 if(developer_extra.integer)
462 Con_DPrintf(" = %f\n", alpha);
463 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
466 for (x = 0;x < FOGWIDTH;x++)
468 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
473 //data2[x][0] = 255 - b;
474 //data2[x][1] = 255 - b;
475 //data2[x][2] = 255 - b;
478 if (r_texture_fogattenuation)
480 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
481 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
485 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);
486 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALLOWUPDATES, NULL);
490 static void R_BuildFogHeightTexture(void)
492 unsigned char *inpixels;
500 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
501 if (r_refdef.fogheighttexturename[0])
502 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false);
505 r_refdef.fog_height_tablesize = 0;
506 if (r_texture_fogheighttexture)
507 R_FreeTexture(r_texture_fogheighttexture);
508 r_texture_fogheighttexture = NULL;
509 if (r_refdef.fog_height_table2d)
510 Mem_Free(r_refdef.fog_height_table2d);
511 r_refdef.fog_height_table2d = NULL;
512 if (r_refdef.fog_height_table1d)
513 Mem_Free(r_refdef.fog_height_table1d);
514 r_refdef.fog_height_table1d = NULL;
518 r_refdef.fog_height_tablesize = size;
519 r_refdef.fog_height_table1d = Mem_Alloc(r_main_mempool, size * 4);
520 r_refdef.fog_height_table2d = Mem_Alloc(r_main_mempool, size * size * 4);
521 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
523 // LordHavoc: now the magic - what is that table2d for? it is a cooked
524 // average fog color table accounting for every fog layer between a point
525 // and the camera. (Note: attenuation is handled separately!)
526 for (y = 0;y < size;y++)
528 for (x = 0;x < size;x++)
534 for (j = x;j <= y;j++)
536 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
542 for (j = x;j >= y;j--)
544 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
549 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
550 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
551 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
552 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
555 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, NULL);
558 //=======================================================================================================================================================
560 static const char *builtinshaderstring =
561 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
562 "// written by Forest 'LordHavoc' Hale\n"
563 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
565 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
568 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
569 "#define USELIGHTMAP\n"
571 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
572 "#define USEEYEVECTOR\n"
575 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
576 "# extension GL_ARB_texture_rectangle : enable\n"
579 "#ifdef USESHADOWMAP2D\n"
580 "# ifdef GL_EXT_gpu_shader4\n"
581 "# extension GL_EXT_gpu_shader4 : enable\n"
583 "# ifdef GL_ARB_texture_gather\n"
584 "# extension GL_ARB_texture_gather : enable\n"
586 "# ifdef GL_AMD_texture_texture4\n"
587 "# extension GL_AMD_texture_texture4 : enable\n"
592 "#ifdef USESHADOWMAPCUBE\n"
593 "# extension GL_EXT_gpu_shader4 : enable\n"
596 "//#ifdef USESHADOWSAMPLER\n"
597 "//# extension GL_ARB_shadow : enable\n"
600 "//#ifdef __GLSL_CG_DATA_TYPES\n"
601 "//# define myhalf half\n"
602 "//# define myhalf2 half2\n"
603 "//# define myhalf3 half3\n"
604 "//# define myhalf4 half4\n"
606 "# define myhalf float\n"
607 "# define myhalf2 vec2\n"
608 "# define myhalf3 vec3\n"
609 "# define myhalf4 vec4\n"
612 "#ifdef VERTEX_SHADER\n"
613 "uniform mat4 ModelViewProjectionMatrix;\n"
616 "#ifdef MODE_DEPTH_OR_SHADOW\n"
617 "#ifdef VERTEX_SHADER\n"
620 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
623 "#else // !MODE_DEPTH_ORSHADOW\n"
628 "#ifdef MODE_SHOWDEPTH\n"
629 "#ifdef VERTEX_SHADER\n"
632 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
633 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
637 "#ifdef FRAGMENT_SHADER\n"
640 " gl_FragColor = gl_Color;\n"
643 "#else // !MODE_SHOWDEPTH\n"
648 "#ifdef MODE_POSTPROCESS\n"
649 "varying vec2 TexCoord1;\n"
650 "varying vec2 TexCoord2;\n"
652 "#ifdef VERTEX_SHADER\n"
655 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
656 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
658 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
663 "#ifdef FRAGMENT_SHADER\n"
664 "uniform sampler2D Texture_First;\n"
666 "uniform sampler2D Texture_Second;\n"
668 "#ifdef USEGAMMARAMPS\n"
669 "uniform sampler2D Texture_GammaRamps;\n"
671 "#ifdef USESATURATION\n"
672 "uniform float Saturation;\n"
674 "#ifdef USEVIEWTINT\n"
675 "uniform vec4 ViewTintColor;\n"
677 "//uncomment these if you want to use them:\n"
678 "uniform vec4 UserVec1;\n"
679 "uniform vec4 UserVec2;\n"
680 "// uniform vec4 UserVec3;\n"
681 "// uniform vec4 UserVec4;\n"
682 "// uniform float ClientTime;\n"
683 "uniform vec2 PixelSize;\n"
686 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
688 " gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
690 "#ifdef USEVIEWTINT\n"
691 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
694 "#ifdef USEPOSTPROCESSING\n"
695 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
696 "// 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"
697 " float sobel = 1.0;\n"
698 " // vec2 ts = textureSize(Texture_First, 0);\n"
699 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
700 " vec2 px = PixelSize;\n"
701 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
702 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
703 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
704 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
705 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
706 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
707 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
708 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
709 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
710 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
711 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
712 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
713 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
714 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
715 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
716 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
717 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
718 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
719 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
720 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
721 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
722 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
723 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
724 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
725 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
726 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
727 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
728 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
729 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
730 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
731 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
732 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
735 "#ifdef USESATURATION\n"
736 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
737 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
738 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
739 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
742 "#ifdef USEGAMMARAMPS\n"
743 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
744 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
745 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
749 "#else // !MODE_POSTPROCESS\n"
754 "#ifdef MODE_GENERIC\n"
755 "#ifdef USEDIFFUSE\n"
756 "varying vec2 TexCoord1;\n"
758 "#ifdef USESPECULAR\n"
759 "varying vec2 TexCoord2;\n"
761 "#ifdef VERTEX_SHADER\n"
764 " gl_FrontColor = gl_Color;\n"
765 "#ifdef USEDIFFUSE\n"
766 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
768 "#ifdef USESPECULAR\n"
769 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
771 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
775 "#ifdef FRAGMENT_SHADER\n"
776 "#ifdef USEDIFFUSE\n"
777 "uniform sampler2D Texture_First;\n"
779 "#ifdef USESPECULAR\n"
780 "uniform sampler2D Texture_Second;\n"
785 " gl_FragColor = gl_Color;\n"
786 "#ifdef USEDIFFUSE\n"
787 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
790 "#ifdef USESPECULAR\n"
791 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
792 "# ifdef USECOLORMAPPING\n"
793 " gl_FragColor *= tex2;\n"
796 " gl_FragColor += tex2;\n"
798 "# ifdef USEVERTEXTEXTUREBLEND\n"
799 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
804 "#else // !MODE_GENERIC\n"
809 "#ifdef MODE_BLOOMBLUR\n"
810 "varying TexCoord;\n"
811 "#ifdef VERTEX_SHADER\n"
814 " gl_FrontColor = gl_Color;\n"
815 " TexCoord = gl_MultiTexCoord0.xy;\n"
816 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
820 "#ifdef FRAGMENT_SHADER\n"
821 "uniform sampler2D Texture_First;\n"
822 "uniform vec4 BloomBlur_Parameters;\n"
827 " vec2 tc = TexCoord;\n"
828 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
829 " tc += BloomBlur_Parameters.xy;\n"
830 " for (i = 1;i < SAMPLES;i++)\n"
832 " color += texture2D(Texture_First, tc).rgb;\n"
833 " tc += BloomBlur_Parameters.xy;\n"
835 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
838 "#else // !MODE_BLOOMBLUR\n"
839 "#ifdef MODE_REFRACTION\n"
840 "varying vec2 TexCoord;\n"
841 "varying vec4 ModelViewProjectionPosition;\n"
842 "uniform mat4 TexMatrix;\n"
843 "#ifdef VERTEX_SHADER\n"
847 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
848 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
849 " ModelViewProjectionPosition = gl_Position;\n"
853 "#ifdef FRAGMENT_SHADER\n"
854 "uniform sampler2D Texture_Normal;\n"
855 "uniform sampler2D Texture_Refraction;\n"
856 "uniform sampler2D Texture_Reflection;\n"
858 "uniform vec4 DistortScaleRefractReflect;\n"
859 "uniform vec4 ScreenScaleRefractReflect;\n"
860 "uniform vec4 ScreenCenterRefractReflect;\n"
861 "uniform vec4 RefractColor;\n"
862 "uniform vec4 ReflectColor;\n"
863 "uniform float ReflectFactor;\n"
864 "uniform float ReflectOffset;\n"
868 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
869 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
870 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
871 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
872 " // FIXME temporary hack to detect the case that the reflection\n"
873 " // gets blackened at edges due to leaving the area that contains actual\n"
875 " // Remove this 'ack once we have a better way to stop this thing from\n"
877 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
878 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
879 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
880 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
881 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
882 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
885 "#else // !MODE_REFRACTION\n"
890 "#ifdef MODE_WATER\n"
891 "varying vec2 TexCoord;\n"
892 "varying vec3 EyeVector;\n"
893 "varying vec4 ModelViewProjectionPosition;\n"
894 "#ifdef VERTEX_SHADER\n"
895 "uniform vec3 EyePosition;\n"
896 "uniform mat4 TexMatrix;\n"
900 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
901 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
902 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
903 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
904 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
905 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
906 " ModelViewProjectionPosition = gl_Position;\n"
910 "#ifdef FRAGMENT_SHADER\n"
911 "uniform sampler2D Texture_Normal;\n"
912 "uniform sampler2D Texture_Refraction;\n"
913 "uniform sampler2D Texture_Reflection;\n"
915 "uniform vec4 DistortScaleRefractReflect;\n"
916 "uniform vec4 ScreenScaleRefractReflect;\n"
917 "uniform vec4 ScreenCenterRefractReflect;\n"
918 "uniform vec4 RefractColor;\n"
919 "uniform vec4 ReflectColor;\n"
920 "uniform float ReflectFactor;\n"
921 "uniform float ReflectOffset;\n"
925 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
926 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
927 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
928 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
929 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
930 " // FIXME temporary hack to detect the case that the reflection\n"
931 " // gets blackened at edges due to leaving the area that contains actual\n"
933 " // Remove this 'ack once we have a better way to stop this thing from\n"
935 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
936 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
937 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
938 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
939 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
940 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
941 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
942 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
943 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
944 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
945 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
946 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
949 "#else // !MODE_WATER\n"
954 "// common definitions between vertex shader and fragment shader:\n"
956 "varying vec2 TexCoord;\n"
957 "#ifdef USEVERTEXTEXTUREBLEND\n"
958 "varying vec2 TexCoord2;\n"
960 "#ifdef USELIGHTMAP\n"
961 "varying vec2 TexCoordLightmap;\n"
964 "#ifdef MODE_LIGHTSOURCE\n"
965 "varying vec3 CubeVector;\n"
968 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
969 "varying vec3 LightVector;\n"
972 "#ifdef USEEYEVECTOR\n"
973 "varying vec3 EyeVector;\n"
976 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
979 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
980 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
981 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
982 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
985 "#ifdef USEREFLECTION\n"
986 "varying vec4 ModelViewProjectionPosition;\n"
988 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
989 "uniform vec3 LightPosition;\n"
990 "varying vec4 ModelViewPosition;\n"
993 "#ifdef MODE_LIGHTSOURCE\n"
994 "uniform vec3 LightPosition;\n"
996 "uniform vec3 EyePosition;\n"
997 "#ifdef MODE_LIGHTDIRECTION\n"
998 "uniform vec3 LightDir;\n"
1000 "uniform vec4 FogPlane;\n"
1002 "#ifdef USESHADOWMAPORTHO\n"
1003 "varying vec3 ShadowMapTC;\n"
1010 "// 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"
1012 "// fragment shader specific:\n"
1013 "#ifdef FRAGMENT_SHADER\n"
1015 "uniform sampler2D Texture_Normal;\n"
1016 "uniform sampler2D Texture_Color;\n"
1017 "uniform sampler2D Texture_Gloss;\n"
1019 "uniform sampler2D Texture_Glow;\n"
1021 "#ifdef USEVERTEXTEXTUREBLEND\n"
1022 "uniform sampler2D Texture_SecondaryNormal;\n"
1023 "uniform sampler2D Texture_SecondaryColor;\n"
1024 "uniform sampler2D Texture_SecondaryGloss;\n"
1026 "uniform sampler2D Texture_SecondaryGlow;\n"
1029 "#ifdef USECOLORMAPPING\n"
1030 "uniform sampler2D Texture_Pants;\n"
1031 "uniform sampler2D Texture_Shirt;\n"
1034 "#ifdef USEFOGHEIGHTTEXTURE\n"
1035 "uniform sampler2D Texture_FogHeightTexture;\n"
1037 "uniform sampler2D Texture_FogMask;\n"
1039 "#ifdef USELIGHTMAP\n"
1040 "uniform sampler2D Texture_Lightmap;\n"
1042 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1043 "uniform sampler2D Texture_Deluxemap;\n"
1045 "#ifdef USEREFLECTION\n"
1046 "uniform sampler2D Texture_Reflection;\n"
1049 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1050 "uniform sampler2D Texture_ScreenDepth;\n"
1051 "uniform sampler2D Texture_ScreenNormalMap;\n"
1053 "#ifdef USEDEFERREDLIGHTMAP\n"
1054 "uniform sampler2D Texture_ScreenDiffuse;\n"
1055 "uniform sampler2D Texture_ScreenSpecular;\n"
1058 "uniform myhalf3 Color_Pants;\n"
1059 "uniform myhalf3 Color_Shirt;\n"
1060 "uniform myhalf3 FogColor;\n"
1063 "uniform float FogRangeRecip;\n"
1064 "uniform float FogPlaneViewDist;\n"
1065 "uniform float FogHeightFade;\n"
1066 "vec3 FogVertex(vec3 surfacecolor)\n"
1068 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1069 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1071 "#ifdef USEFOGHEIGHTTEXTURE\n"
1072 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1073 " fogfrac = fogheightpixel.a;\n"
1074 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1076 "# ifdef USEFOGOUTSIDE\n"
1077 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1079 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1081 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1086 "#ifdef USEOFFSETMAPPING\n"
1087 "uniform float OffsetMapping_Scale;\n"
1088 "vec2 OffsetMapping(vec2 TexCoord)\n"
1090 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1091 " // 14 sample relief mapping: linear search and then binary search\n"
1092 " // this basically steps forward a small amount repeatedly until it finds\n"
1093 " // itself inside solid, then jitters forward and back using decreasing\n"
1094 " // amounts to find the impact\n"
1095 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1096 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1097 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1098 " vec3 RT = vec3(TexCoord, 1);\n"
1099 " OffsetVector *= 0.1;\n"
1100 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1101 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1102 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1103 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1104 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1105 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1106 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1107 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1108 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1109 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1110 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1111 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1112 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1113 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1116 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1117 " // this basically moves forward the full distance, and then backs up based\n"
1118 " // on height of samples\n"
1119 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1120 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1121 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1122 " TexCoord += OffsetVector;\n"
1123 " OffsetVector *= 0.333;\n"
1124 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1125 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1126 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1127 " return TexCoord;\n"
1130 "#endif // USEOFFSETMAPPING\n"
1132 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1133 "uniform sampler2D Texture_Attenuation;\n"
1134 "uniform samplerCube Texture_Cube;\n"
1137 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1139 "#ifdef USESHADOWMAPRECT\n"
1140 "# ifdef USESHADOWSAMPLER\n"
1141 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1143 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1147 "#ifdef USESHADOWMAP2D\n"
1148 "# ifdef USESHADOWSAMPLER\n"
1149 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1151 "uniform sampler2D Texture_ShadowMap2D;\n"
1155 "#ifdef USESHADOWMAPVSDCT\n"
1156 "uniform samplerCube Texture_CubeProjection;\n"
1159 "#ifdef USESHADOWMAPCUBE\n"
1160 "# ifdef USESHADOWSAMPLER\n"
1161 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1163 "uniform samplerCube Texture_ShadowMapCube;\n"
1167 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1168 "uniform vec2 ShadowMap_TextureScale;\n"
1169 "uniform vec4 ShadowMap_Parameters;\n"
1172 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1173 "# ifdef USESHADOWMAPORTHO\n"
1174 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1176 "# ifdef USESHADOWMAPVSDCT\n"
1177 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1179 " vec3 adir = abs(dir);\n"
1180 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1181 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1182 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1185 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1187 " vec3 adir = abs(dir);\n"
1188 " float ma = adir.z;\n"
1189 " vec4 proj = vec4(dir, 2.5);\n"
1190 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1191 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1192 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1193 " return vec3(proj.xy * aparams.x + vec2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1197 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1199 "#ifdef USESHADOWMAPCUBE\n"
1200 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1202 " vec3 adir = abs(dir);\n"
1203 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1207 "# ifdef USESHADOWMAPRECT\n"
1208 "float ShadowMapCompare(vec3 dir)\n"
1210 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1212 "# ifdef USESHADOWSAMPLER\n"
1214 "# ifdef USESHADOWMAPPCF\n"
1215 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1216 " 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"
1218 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1223 "# ifdef USESHADOWMAPPCF\n"
1224 "# if USESHADOWMAPPCF > 1\n"
1225 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1226 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1227 " 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"
1228 " 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"
1229 " 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"
1230 " 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"
1231 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1232 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1234 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1235 " vec2 offset = fract(shadowmaptc.xy);\n"
1236 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1237 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1238 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1239 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1240 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1243 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1247 "# ifdef USESHADOWMAPORTHO\n"
1248 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1255 "# ifdef USESHADOWMAP2D\n"
1256 "float ShadowMapCompare(vec3 dir)\n"
1258 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1261 "# ifdef USESHADOWSAMPLER\n"
1262 "# ifdef USESHADOWMAPPCF\n"
1263 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1264 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1265 " 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"
1267 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1270 "# ifdef USESHADOWMAPPCF\n"
1271 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1272 "# ifdef GL_ARB_texture_gather\n"
1273 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1275 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1277 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1278 "# if USESHADOWMAPPCF > 1\n"
1279 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1280 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1281 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1282 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1283 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1284 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1285 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1286 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1287 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1288 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1289 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1290 " locols.yz += group2.ab;\n"
1291 " hicols.yz += group8.rg;\n"
1292 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1293 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1294 " mix(locols, hicols, offset.y);\n"
1295 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1296 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1297 " f = dot(cols, vec4(1.0/25.0));\n"
1299 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1300 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1301 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1302 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1303 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1304 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1305 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1308 "# ifdef GL_EXT_gpu_shader4\n"
1309 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1311 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1313 "# if USESHADOWMAPPCF > 1\n"
1314 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1315 " center *= ShadowMap_TextureScale;\n"
1316 " 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"
1317 " 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"
1318 " 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"
1319 " 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"
1320 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1321 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1323 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1324 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1325 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1326 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1327 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1328 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1332 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1335 "# ifdef USESHADOWMAPORTHO\n"
1336 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1343 "# ifdef USESHADOWMAPCUBE\n"
1344 "float ShadowMapCompare(vec3 dir)\n"
1346 " // apply depth texture cubemap as light filter\n"
1347 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1349 "# ifdef USESHADOWSAMPLER\n"
1350 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1352 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1357 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1358 "#endif // FRAGMENT_SHADER\n"
1363 "#ifdef MODE_DEFERREDGEOMETRY\n"
1364 "#ifdef VERTEX_SHADER\n"
1365 "uniform mat4 TexMatrix;\n"
1366 "#ifdef USEVERTEXTEXTUREBLEND\n"
1367 "uniform mat4 BackgroundTexMatrix;\n"
1369 "uniform mat4 ModelViewMatrix;\n"
1372 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1373 "#ifdef USEVERTEXTEXTUREBLEND\n"
1374 " gl_FrontColor = gl_Color;\n"
1375 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1378 " // transform unnormalized eye direction into tangent space\n"
1379 "#ifdef USEOFFSETMAPPING\n"
1380 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1381 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1382 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1383 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1386 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1387 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1388 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1389 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1391 "#endif // VERTEX_SHADER\n"
1393 "#ifdef FRAGMENT_SHADER\n"
1396 "#ifdef USEOFFSETMAPPING\n"
1397 " // apply offsetmapping\n"
1398 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1399 "#define TexCoord TexCoordOffset\n"
1402 "#ifdef USEALPHAKILL\n"
1403 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1407 "#ifdef USEVERTEXTEXTUREBLEND\n"
1408 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1409 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1410 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1411 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1414 "#ifdef USEVERTEXTEXTUREBLEND\n"
1415 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1416 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1418 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1419 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1422 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1424 "#endif // FRAGMENT_SHADER\n"
1425 "#else // !MODE_DEFERREDGEOMETRY\n"
1430 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1431 "#ifdef VERTEX_SHADER\n"
1432 "uniform mat4 ModelViewMatrix;\n"
1435 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1436 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1438 "#endif // VERTEX_SHADER\n"
1440 "#ifdef FRAGMENT_SHADER\n"
1441 "uniform mat4 ViewToLight;\n"
1442 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1443 "uniform vec2 ScreenToDepth;\n"
1444 "uniform myhalf3 DeferredColor_Ambient;\n"
1445 "uniform myhalf3 DeferredColor_Diffuse;\n"
1446 "#ifdef USESPECULAR\n"
1447 "uniform myhalf3 DeferredColor_Specular;\n"
1448 "uniform myhalf SpecularPower;\n"
1450 "uniform myhalf2 PixelToScreenTexCoord;\n"
1453 " // calculate viewspace pixel position\n"
1454 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1456 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1457 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1458 " // decode viewspace pixel normal\n"
1459 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1460 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1461 " // surfacenormal = pixel normal in viewspace\n"
1462 " // LightVector = pixel to light in viewspace\n"
1463 " // CubeVector = position in lightspace\n"
1464 " // eyevector = pixel to view in viewspace\n"
1465 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1466 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1467 "#ifdef USEDIFFUSE\n"
1468 " // calculate diffuse shading\n"
1469 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1470 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1472 "#ifdef USESPECULAR\n"
1473 " // calculate directional shading\n"
1474 " vec3 eyevector = position * -1.0;\n"
1475 "# ifdef USEEXACTSPECULARMATH\n"
1476 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1478 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1479 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1483 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1484 " fade *= ShadowMapCompare(CubeVector);\n"
1487 "#ifdef USEDIFFUSE\n"
1488 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1490 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1492 "#ifdef USESPECULAR\n"
1493 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1495 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1498 "# ifdef USECUBEFILTER\n"
1499 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1500 " gl_FragData[0].rgb *= cubecolor;\n"
1501 " gl_FragData[1].rgb *= cubecolor;\n"
1504 "#endif // FRAGMENT_SHADER\n"
1505 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1510 "#ifdef VERTEX_SHADER\n"
1511 "uniform mat4 TexMatrix;\n"
1512 "#ifdef USEVERTEXTEXTUREBLEND\n"
1513 "uniform mat4 BackgroundTexMatrix;\n"
1515 "#ifdef MODE_LIGHTSOURCE\n"
1516 "uniform mat4 ModelToLight;\n"
1518 "#ifdef USESHADOWMAPORTHO\n"
1519 "uniform mat4 ShadowMapMatrix;\n"
1523 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1524 " gl_FrontColor = gl_Color;\n"
1526 " // copy the surface texcoord\n"
1527 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1528 "#ifdef USEVERTEXTEXTUREBLEND\n"
1529 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1531 "#ifdef USELIGHTMAP\n"
1532 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1535 "#ifdef MODE_LIGHTSOURCE\n"
1536 " // transform vertex position into light attenuation/cubemap space\n"
1537 " // (-1 to +1 across the light box)\n"
1538 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1540 "# ifdef USEDIFFUSE\n"
1541 " // transform unnormalized light direction into tangent space\n"
1542 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1543 " // normalize it per pixel)\n"
1544 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1545 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1546 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1547 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1551 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1552 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1553 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1554 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1557 " // transform unnormalized eye direction into tangent space\n"
1558 "#ifdef USEEYEVECTOR\n"
1559 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1560 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1561 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1562 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1566 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1567 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1570 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1571 " VectorS = gl_MultiTexCoord1.xyz;\n"
1572 " VectorT = gl_MultiTexCoord2.xyz;\n"
1573 " VectorR = gl_MultiTexCoord3.xyz;\n"
1576 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1577 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1579 "#ifdef USESHADOWMAPORTHO\n"
1580 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1583 "#ifdef USEREFLECTION\n"
1584 " ModelViewProjectionPosition = gl_Position;\n"
1587 "#endif // VERTEX_SHADER\n"
1592 "#ifdef FRAGMENT_SHADER\n"
1593 "#ifdef USEDEFERREDLIGHTMAP\n"
1594 "uniform myhalf2 PixelToScreenTexCoord;\n"
1595 "uniform myhalf3 DeferredMod_Diffuse;\n"
1596 "uniform myhalf3 DeferredMod_Specular;\n"
1598 "uniform myhalf3 Color_Ambient;\n"
1599 "uniform myhalf3 Color_Diffuse;\n"
1600 "uniform myhalf3 Color_Specular;\n"
1601 "uniform myhalf SpecularPower;\n"
1603 "uniform myhalf3 Color_Glow;\n"
1605 "uniform myhalf Alpha;\n"
1606 "#ifdef USEREFLECTION\n"
1607 "uniform vec4 DistortScaleRefractReflect;\n"
1608 "uniform vec4 ScreenScaleRefractReflect;\n"
1609 "uniform vec4 ScreenCenterRefractReflect;\n"
1610 "uniform myhalf4 ReflectColor;\n"
1612 "#ifdef USEREFLECTCUBE\n"
1613 "uniform mat4 ModelToReflectCube;\n"
1614 "uniform sampler2D Texture_ReflectMask;\n"
1615 "uniform samplerCube Texture_ReflectCube;\n"
1617 "#ifdef MODE_LIGHTDIRECTION\n"
1618 "uniform myhalf3 LightColor;\n"
1620 "#ifdef MODE_LIGHTSOURCE\n"
1621 "uniform myhalf3 LightColor;\n"
1625 "#ifdef USEOFFSETMAPPING\n"
1626 " // apply offsetmapping\n"
1627 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1628 "#define TexCoord TexCoordOffset\n"
1631 " // combine the diffuse textures (base, pants, shirt)\n"
1632 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1633 "#ifdef USEALPHAKILL\n"
1634 " if (color.a < 0.5)\n"
1637 " color.a *= Alpha;\n"
1638 "#ifdef USECOLORMAPPING\n"
1639 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1641 "#ifdef USEVERTEXTEXTUREBLEND\n"
1642 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1643 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1644 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1645 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1647 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1650 " // get the surface normal\n"
1651 "#ifdef USEVERTEXTEXTUREBLEND\n"
1652 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1654 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1657 " // get the material colors\n"
1658 " myhalf3 diffusetex = color.rgb;\n"
1659 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1660 "# ifdef USEVERTEXTEXTUREBLEND\n"
1661 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1663 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1667 "#ifdef USEREFLECTCUBE\n"
1668 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1669 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1670 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1671 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1677 "#ifdef MODE_LIGHTSOURCE\n"
1678 " // light source\n"
1679 "#ifdef USEDIFFUSE\n"
1680 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1681 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1682 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1683 "#ifdef USESPECULAR\n"
1684 "#ifdef USEEXACTSPECULARMATH\n"
1685 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1687 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1688 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1690 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1693 " color.rgb = diffusetex * Color_Ambient;\n"
1695 " color.rgb *= LightColor;\n"
1696 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1697 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1698 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1700 "# ifdef USECUBEFILTER\n"
1701 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1703 "#endif // MODE_LIGHTSOURCE\n"
1708 "#ifdef MODE_LIGHTDIRECTION\n"
1710 "#ifdef USEDIFFUSE\n"
1711 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1713 "#define lightcolor LightColor\n"
1714 "#endif // MODE_LIGHTDIRECTION\n"
1715 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1717 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1718 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1719 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1720 " // convert modelspace light vector to tangentspace\n"
1721 " myhalf3 lightnormal;\n"
1722 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1723 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1724 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1725 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1726 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1727 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1728 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1729 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1730 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1731 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1732 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1733 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1734 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1735 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1736 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1738 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1739 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1740 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1746 "#ifdef MODE_LIGHTMAP\n"
1747 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1748 "#endif // MODE_LIGHTMAP\n"
1749 "#ifdef MODE_VERTEXCOLOR\n"
1750 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1751 "#endif // MODE_VERTEXCOLOR\n"
1752 "#ifdef MODE_FLATCOLOR\n"
1753 " color.rgb = diffusetex * Color_Ambient;\n"
1754 "#endif // MODE_FLATCOLOR\n"
1760 "# ifdef USEDIFFUSE\n"
1761 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1762 "# ifdef USESPECULAR\n"
1763 "# ifdef USEEXACTSPECULARMATH\n"
1764 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1766 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1767 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1769 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1771 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1774 " color.rgb = diffusetex * Color_Ambient;\n"
1778 "#ifdef USESHADOWMAPORTHO\n"
1779 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1782 "#ifdef USEDEFERREDLIGHTMAP\n"
1783 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1784 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1785 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1789 "#ifdef USEVERTEXTEXTUREBLEND\n"
1790 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1792 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1797 " color.rgb = FogVertex(color.rgb);\n"
1800 " // 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"
1801 "#ifdef USEREFLECTION\n"
1802 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1803 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1804 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1805 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1806 " // FIXME temporary hack to detect the case that the reflection\n"
1807 " // gets blackened at edges due to leaving the area that contains actual\n"
1809 " // Remove this 'ack once we have a better way to stop this thing from\n"
1811 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1812 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1813 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1814 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1815 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1816 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1819 " gl_FragColor = vec4(color);\n"
1821 "#endif // FRAGMENT_SHADER\n"
1823 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1824 "#endif // !MODE_DEFERREDGEOMETRY\n"
1825 "#endif // !MODE_WATER\n"
1826 "#endif // !MODE_REFRACTION\n"
1827 "#endif // !MODE_BLOOMBLUR\n"
1828 "#endif // !MODE_GENERIC\n"
1829 "#endif // !MODE_POSTPROCESS\n"
1830 "#endif // !MODE_SHOWDEPTH\n"
1831 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1835 =========================================================================================================================================================
1839 =========================================================================================================================================================
1843 =========================================================================================================================================================
1847 =========================================================================================================================================================
1851 =========================================================================================================================================================
1855 =========================================================================================================================================================
1859 =========================================================================================================================================================
1862 const char *builtincgshaderstring =
1863 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1864 "// written by Forest 'LordHavoc' Hale\n"
1865 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1867 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1868 "#if defined(USEREFLECTION)\n"
1869 "#undef USESHADOWMAPORTHO\n"
1872 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1875 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1876 "#define USELIGHTMAP\n"
1878 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1879 "#define USEEYEVECTOR\n"
1882 "#ifdef FRAGMENT_SHADER\n"
1883 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1886 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1887 "#ifdef VERTEX_SHADER\n"
1890 "float4 gl_Vertex : POSITION,\n"
1891 "uniform float4x4 ModelViewProjectionMatrix,\n"
1892 "out float4 gl_Position : POSITION\n"
1895 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1898 "#else // !MODE_DEPTH_ORSHADOW\n"
1903 "#ifdef MODE_SHOWDEPTH\n"
1904 "#ifdef VERTEX_SHADER\n"
1907 "float4 gl_Vertex : POSITION,\n"
1908 "uniform float4x4 ModelViewProjectionMatrix,\n"
1909 "out float4 gl_Position : POSITION,\n"
1910 "out float4 gl_FrontColor : COLOR0\n"
1913 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1914 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1918 "#ifdef FRAGMENT_SHADER\n"
1921 "float4 gl_FrontColor : COLOR0,\n"
1922 "out float4 gl_FragColor : COLOR\n"
1925 " gl_FragColor = gl_FrontColor;\n"
1928 "#else // !MODE_SHOWDEPTH\n"
1933 "#ifdef MODE_POSTPROCESS\n"
1935 "#ifdef VERTEX_SHADER\n"
1938 "float4 gl_Vertex : POSITION,\n"
1939 "uniform float4x4 ModelViewProjectionMatrix,\n"
1940 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1941 "float4 gl_MultiTexCoord1 : TEXCOORD4,\n"
1942 "out float4 gl_Position : POSITION,\n"
1943 "out float2 TexCoord1 : TEXCOORD0,\n"
1944 "out float2 TexCoord2 : TEXCOORD1\n"
1947 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1948 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1950 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
1955 "#ifdef FRAGMENT_SHADER\n"
1958 "float2 TexCoord1 : TEXCOORD0,\n"
1959 "float2 TexCoord2 : TEXCOORD1,\n"
1960 "uniform sampler2D Texture_First,\n"
1962 "uniform sampler2D Texture_Second,\n"
1964 "#ifdef USEGAMMARAMPS\n"
1965 "uniform sampler2D Texture_GammaRamps,\n"
1967 "#ifdef USESATURATION\n"
1968 "uniform float Saturation,\n"
1970 "#ifdef USEVIEWTINT\n"
1971 "uniform float4 ViewTintColor,\n"
1973 "uniform float4 UserVec1,\n"
1974 "uniform float4 UserVec2,\n"
1975 "uniform float4 UserVec3,\n"
1976 "uniform float4 UserVec4,\n"
1977 "uniform float ClientTime,\n"
1978 "uniform float2 PixelSize,\n"
1979 "out float4 gl_FragColor : COLOR\n"
1982 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1984 " gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
1986 "#ifdef USEVIEWTINT\n"
1987 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1990 "#ifdef USEPOSTPROCESSING\n"
1991 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1992 "// 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"
1993 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1994 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1995 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1996 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
1997 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
1998 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2001 "#ifdef USESATURATION\n"
2002 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2003 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2004 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2005 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2008 "#ifdef USEGAMMARAMPS\n"
2009 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2010 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2011 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2015 "#else // !MODE_POSTPROCESS\n"
2020 "#ifdef MODE_GENERIC\n"
2021 "#ifdef VERTEX_SHADER\n"
2024 "float4 gl_Vertex : POSITION,\n"
2025 "uniform float4x4 ModelViewProjectionMatrix,\n"
2026 "float4 gl_Color : COLOR0,\n"
2027 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2028 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2029 "out float4 gl_Position : POSITION,\n"
2030 "out float4 gl_FrontColor : COLOR,\n"
2031 "out float2 TexCoord1 : TEXCOORD0,\n"
2032 "out float2 TexCoord2 : TEXCOORD1\n"
2035 " gl_FrontColor = gl_Color;\n"
2036 "#ifdef USEDIFFUSE\n"
2037 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2039 "#ifdef USESPECULAR\n"
2040 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2042 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2046 "#ifdef FRAGMENT_SHADER\n"
2050 "float4 gl_FrontColor : COLOR,\n"
2051 "float2 TexCoord1 : TEXCOORD0,\n"
2052 "float2 TexCoord2 : TEXCOORD1,\n"
2053 "#ifdef USEDIFFUSE\n"
2054 "uniform sampler2D Texture_First,\n"
2056 "#ifdef USESPECULAR\n"
2057 "uniform sampler2D Texture_Second,\n"
2059 "out float4 gl_FragColor : COLOR\n"
2062 " gl_FragColor = gl_FrontColor;\n"
2063 "#ifdef USEDIFFUSE\n"
2064 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2067 "#ifdef USESPECULAR\n"
2068 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2069 "# ifdef USECOLORMAPPING\n"
2070 " gl_FragColor *= tex2;\n"
2073 " gl_FragColor += tex2;\n"
2075 "# ifdef USEVERTEXTEXTUREBLEND\n"
2076 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2081 "#else // !MODE_GENERIC\n"
2086 "#ifdef MODE_BLOOMBLUR\n"
2087 "#ifdef VERTEX_SHADER\n"
2090 "float4 gl_Vertex : POSITION,\n"
2091 "uniform float4x4 ModelViewProjectionMatrix,\n"
2092 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2093 "out float4 gl_Position : POSITION,\n"
2094 "out float2 TexCoord : TEXCOORD0\n"
2097 " TexCoord = gl_MultiTexCoord0.xy;\n"
2098 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2102 "#ifdef FRAGMENT_SHADER\n"
2106 "float2 TexCoord : TEXCOORD0,\n"
2107 "uniform sampler2D Texture_First,\n"
2108 "uniform float4 BloomBlur_Parameters,\n"
2109 "out float4 gl_FragColor : COLOR\n"
2113 " float2 tc = TexCoord;\n"
2114 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2115 " tc += BloomBlur_Parameters.xy;\n"
2116 " for (i = 1;i < SAMPLES;i++)\n"
2118 " color += tex2D(Texture_First, tc).rgb;\n"
2119 " tc += BloomBlur_Parameters.xy;\n"
2121 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2124 "#else // !MODE_BLOOMBLUR\n"
2125 "#ifdef MODE_REFRACTION\n"
2126 "#ifdef VERTEX_SHADER\n"
2129 "float4 gl_Vertex : POSITION,\n"
2130 "uniform float4x4 ModelViewProjectionMatrix,\n"
2131 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2132 "uniform float4x4 TexMatrix,\n"
2133 "uniform float3 EyePosition,\n"
2134 "out float4 gl_Position : POSITION,\n"
2135 "out float2 TexCoord : TEXCOORD0,\n"
2136 "out float3 EyeVector : TEXCOORD1,\n"
2137 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2140 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2141 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2142 " ModelViewProjectionPosition = gl_Position;\n"
2146 "#ifdef FRAGMENT_SHADER\n"
2149 "float2 TexCoord : TEXCOORD0,\n"
2150 "float3 EyeVector : TEXCOORD1,\n"
2151 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2152 "uniform sampler2D Texture_Normal,\n"
2153 "uniform sampler2D Texture_Refraction,\n"
2154 "uniform sampler2D Texture_Reflection,\n"
2155 "uniform float4 DistortScaleRefractReflect,\n"
2156 "uniform float4 ScreenScaleRefractReflect,\n"
2157 "uniform float4 ScreenCenterRefractReflect,\n"
2158 "uniform float4 RefractColor,\n"
2159 "out float4 gl_FragColor : COLOR\n"
2162 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2163 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2164 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2165 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2166 " // FIXME temporary hack to detect the case that the reflection\n"
2167 " // gets blackened at edges due to leaving the area that contains actual\n"
2169 " // Remove this 'ack once we have a better way to stop this thing from\n"
2171 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2172 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2173 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2174 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2175 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2176 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2179 "#else // !MODE_REFRACTION\n"
2184 "#ifdef MODE_WATER\n"
2185 "#ifdef VERTEX_SHADER\n"
2189 "float4 gl_Vertex : POSITION,\n"
2190 "uniform float4x4 ModelViewProjectionMatrix,\n"
2191 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2192 "uniform float4x4 TexMatrix,\n"
2193 "uniform float3 EyePosition,\n"
2194 "out float4 gl_Position : POSITION,\n"
2195 "out float2 TexCoord : TEXCOORD0,\n"
2196 "out float3 EyeVector : TEXCOORD1,\n"
2197 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2200 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2201 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2202 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2203 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2204 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2205 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2206 " ModelViewProjectionPosition = gl_Position;\n"
2210 "#ifdef FRAGMENT_SHADER\n"
2213 "float2 TexCoord : TEXCOORD0,\n"
2214 "float3 EyeVector : TEXCOORD1,\n"
2215 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2216 "uniform sampler2D Texture_Normal,\n"
2217 "uniform sampler2D Texture_Refraction,\n"
2218 "uniform sampler2D Texture_Reflection,\n"
2219 "uniform float4 DistortScaleRefractReflect,\n"
2220 "uniform float4 ScreenScaleRefractReflect,\n"
2221 "uniform float4 ScreenCenterRefractReflect,\n"
2222 "uniform float4 RefractColor,\n"
2223 "uniform float4 ReflectColor,\n"
2224 "uniform float ReflectFactor,\n"
2225 "uniform float ReflectOffset,\n"
2226 "out float4 gl_FragColor : COLOR\n"
2229 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2230 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2231 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2232 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2233 " // FIXME temporary hack to detect the case that the reflection\n"
2234 " // gets blackened at edges due to leaving the area that contains actual\n"
2236 " // Remove this 'ack once we have a better way to stop this thing from\n"
2238 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2239 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2240 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2241 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2242 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2243 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2244 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2245 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2246 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2247 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2248 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2249 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2252 "#else // !MODE_WATER\n"
2257 "// 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"
2259 "// fragment shader specific:\n"
2260 "#ifdef FRAGMENT_SHADER\n"
2263 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2266 "#ifdef USEFOGHEIGHTTEXTURE\n"
2267 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2268 " fogfrac = fogheightpixel.a;\n"
2269 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2271 "# ifdef USEFOGOUTSIDE\n"
2272 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2274 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2276 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2281 "#ifdef USEOFFSETMAPPING\n"
2282 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2284 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2285 " // 14 sample relief mapping: linear search and then binary search\n"
2286 " // this basically steps forward a small amount repeatedly until it finds\n"
2287 " // itself inside solid, then jitters forward and back using decreasing\n"
2288 " // amounts to find the impact\n"
2289 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2290 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2291 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2292 " float3 RT = float3(TexCoord, 1);\n"
2293 " OffsetVector *= 0.1;\n"
2294 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2295 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2296 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2297 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2298 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2299 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2300 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2301 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2302 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2303 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2304 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2305 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2306 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2307 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2310 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2311 " // this basically moves forward the full distance, and then backs up based\n"
2312 " // on height of samples\n"
2313 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2314 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2315 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2316 " TexCoord += OffsetVector;\n"
2317 " OffsetVector *= 0.333;\n"
2318 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2319 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2320 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2321 " return TexCoord;\n"
2324 "#endif // USEOFFSETMAPPING\n"
2326 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2327 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2328 "# ifdef USESHADOWMAPORTHO\n"
2329 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2331 "# ifdef USESHADOWMAPVSDCT\n"
2332 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2334 " float3 adir = abs(dir);\n"
2335 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2336 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2337 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2340 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2342 " float3 adir = abs(dir);\n"
2343 " float ma = adir.z;\n"
2344 " float4 proj = float4(dir, 2.5);\n"
2345 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2346 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2347 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2348 " return float3(proj.xy * aparams.x + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2352 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2354 "#ifdef USESHADOWMAPCUBE\n"
2355 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2357 " float3 adir = abs(dir);\n"
2358 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2362 "# ifdef USESHADOWMAPRECT\n"
2363 "#ifdef USESHADOWMAPVSDCT\n"
2364 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2366 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2369 "#ifdef USESHADOWMAPVSDCT\n"
2370 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2372 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2375 "# ifdef USESHADOWSAMPLER\n"
2377 "# ifdef USESHADOWMAPPCF\n"
2378 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2379 " 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"
2381 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2386 "# ifdef USESHADOWMAPPCF\n"
2387 "# if USESHADOWMAPPCF > 1\n"
2388 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2389 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2390 " 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"
2391 " 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"
2392 " 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"
2393 " 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"
2394 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2395 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2397 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2398 " float2 offset = frac(shadowmaptc.xy);\n"
2399 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2400 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2401 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2402 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2403 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2406 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2410 "# ifdef USESHADOWMAPORTHO\n"
2411 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2418 "# ifdef USESHADOWMAP2D\n"
2419 "#ifdef USESHADOWMAPVSDCT\n"
2420 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2422 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2425 "#ifdef USESHADOWMAPVSDCT\n"
2426 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2428 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2432 "# ifdef USESHADOWSAMPLER\n"
2433 "# ifdef USESHADOWMAPPCF\n"
2434 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
2435 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2436 " 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"
2438 " f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2441 "# ifdef USESHADOWMAPPCF\n"
2442 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2443 "# ifdef GL_ARB_texture_gather\n"
2444 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2446 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2448 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2449 " center *= ShadowMap_TextureScale;\n"
2450 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2451 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2452 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2453 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2454 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2455 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2456 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2458 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale) \n"
2459 "# if USESHADOWMAPPCF > 1\n"
2460 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2461 " center *= ShadowMap_TextureScale;\n"
2462 " 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"
2463 " 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"
2464 " 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"
2465 " 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"
2466 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2467 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2469 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2470 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2471 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2472 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2473 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2474 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2478 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2481 "# ifdef USESHADOWMAPORTHO\n"
2482 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2489 "# ifdef USESHADOWMAPCUBE\n"
2490 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2492 " // apply depth texture cubemap as light filter\n"
2493 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2495 "# ifdef USESHADOWSAMPLER\n"
2496 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2498 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2503 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2504 "#endif // FRAGMENT_SHADER\n"
2509 "#ifdef MODE_DEFERREDGEOMETRY\n"
2510 "#ifdef VERTEX_SHADER\n"
2513 "float4 gl_Vertex : POSITION,\n"
2514 "uniform float4x4 ModelViewProjectionMatrix,\n"
2515 "#ifdef USEVERTEXTEXTUREBLEND\n"
2516 "float4 gl_Color : COLOR0,\n"
2518 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2519 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2520 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2521 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2522 "uniform float4x4 TexMatrix,\n"
2523 "#ifdef USEVERTEXTEXTUREBLEND\n"
2524 "uniform float4x4 BackgroundTexMatrix,\n"
2526 "uniform float4x4 ModelViewMatrix,\n"
2527 "#ifdef USEOFFSETMAPPING\n"
2528 "uniform float3 EyePosition,\n"
2530 "out float4 gl_Position : POSITION,\n"
2531 "out float4 gl_FrontColor : COLOR,\n"
2532 "out float4 TexCoordBoth : TEXCOORD0,\n"
2533 "#ifdef USEOFFSETMAPPING\n"
2534 "out float3 EyeVector : TEXCOORD2,\n"
2536 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2537 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2538 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2541 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2542 "#ifdef USEVERTEXTEXTUREBLEND\n"
2543 " gl_FrontColor = gl_Color;\n"
2544 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2547 " // transform unnormalized eye direction into tangent space\n"
2548 "#ifdef USEOFFSETMAPPING\n"
2549 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2550 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2551 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2552 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2555 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2556 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2557 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2558 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2560 "#endif // VERTEX_SHADER\n"
2562 "#ifdef FRAGMENT_SHADER\n"
2565 "float4 TexCoordBoth : TEXCOORD0,\n"
2566 "float3 EyeVector : TEXCOORD2,\n"
2567 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2568 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2569 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2570 "uniform sampler2D Texture_Normal,\n"
2571 "#ifdef USEALPHAKILL\n"
2572 "uniform sampler2D Texture_Color,\n"
2574 "uniform sampler2D Texture_Gloss,\n"
2575 "#ifdef USEVERTEXTEXTUREBLEND\n"
2576 "uniform sampler2D Texture_SecondaryNormal,\n"
2577 "uniform sampler2D Texture_SecondaryGloss,\n"
2579 "#ifdef USEOFFSETMAPPING\n"
2580 "uniform float OffsetMapping_Scale,\n"
2582 "uniform half SpecularPower,\n"
2583 "out float4 gl_FragColor : COLOR\n"
2586 " float2 TexCoord = TexCoordBoth.xy;\n"
2587 "#ifdef USEOFFSETMAPPING\n"
2588 " // apply offsetmapping\n"
2589 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2590 "#define TexCoord TexCoordOffset\n"
2593 "#ifdef USEALPHAKILL\n"
2594 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2598 "#ifdef USEVERTEXTEXTUREBLEND\n"
2599 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2600 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2601 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2602 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2605 "#ifdef USEVERTEXTEXTUREBLEND\n"
2606 " float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2607 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2609 " float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2610 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2613 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2615 "#endif // FRAGMENT_SHADER\n"
2616 "#else // !MODE_DEFERREDGEOMETRY\n"
2621 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2622 "#ifdef VERTEX_SHADER\n"
2625 "float4 gl_Vertex : POSITION,\n"
2626 "uniform float4x4 ModelViewProjectionMatrix,\n"
2627 "uniform float4x4 ModelViewMatrix,\n"
2628 "out float4 gl_Position : POSITION,\n"
2629 "out float4 ModelViewPosition : TEXCOORD0\n"
2632 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2633 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2635 "#endif // VERTEX_SHADER\n"
2637 "#ifdef FRAGMENT_SHADER\n"
2640 "float2 Pixel : WPOS,\n"
2641 "float4 ModelViewPosition : TEXCOORD0,\n"
2642 "uniform float4x4 ViewToLight,\n"
2643 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2644 "uniform float3 LightPosition,\n"
2645 "uniform half2 PixelToScreenTexCoord,\n"
2646 "uniform half3 DeferredColor_Ambient,\n"
2647 "uniform half3 DeferredColor_Diffuse,\n"
2648 "#ifdef USESPECULAR\n"
2649 "uniform half3 DeferredColor_Specular,\n"
2650 "uniform half SpecularPower,\n"
2652 "uniform sampler2D Texture_Attenuation,\n"
2653 "uniform sampler2D Texture_ScreenDepth,\n"
2654 "uniform sampler2D Texture_ScreenNormalMap,\n"
2656 "#ifdef USECUBEFILTER\n"
2657 "uniform samplerCUBE Texture_Cube,\n"
2660 "#ifdef USESHADOWMAPRECT\n"
2661 "# ifdef USESHADOWSAMPLER\n"
2662 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2664 "uniform samplerRECT Texture_ShadowMapRect,\n"
2668 "#ifdef USESHADOWMAP2D\n"
2669 "# ifdef USESHADOWSAMPLER\n"
2670 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2672 "uniform sampler2D Texture_ShadowMap2D,\n"
2676 "#ifdef USESHADOWMAPVSDCT\n"
2677 "uniform samplerCUBE Texture_CubeProjection,\n"
2680 "#ifdef USESHADOWMAPCUBE\n"
2681 "# ifdef USESHADOWSAMPLER\n"
2682 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2684 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2688 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2689 "uniform float2 ShadowMap_TextureScale,\n"
2690 "uniform float4 ShadowMap_Parameters,\n"
2693 "out float4 gl_FragData0 : COLOR0,\n"
2694 "out float4 gl_FragData1 : COLOR1\n"
2697 " // calculate viewspace pixel position\n"
2698 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2699 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2700 " float3 position;\n"
2701 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2702 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2703 " // decode viewspace pixel normal\n"
2704 " half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2705 " half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2706 " // surfacenormal = pixel normal in viewspace\n"
2707 " // LightVector = pixel to light in viewspace\n"
2708 " // CubeVector = position in lightspace\n"
2709 " // eyevector = pixel to view in viewspace\n"
2710 " float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2711 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2712 "#ifdef USEDIFFUSE\n"
2713 " // calculate diffuse shading\n"
2714 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2715 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2717 "#ifdef USESPECULAR\n"
2718 " // calculate directional shading\n"
2719 " float3 eyevector = position * -1.0;\n"
2720 "# ifdef USEEXACTSPECULARMATH\n"
2721 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2723 " half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2724 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2728 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2729 " fade *= ShadowMapCompare(CubeVector,\n"
2730 "# if defined(USESHADOWMAP2D)\n"
2731 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2733 "# if defined(USESHADOWMAPRECT)\n"
2734 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2736 "# if defined(USESHADOWMAPCUBE)\n"
2737 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2740 "#ifdef USESHADOWMAPVSDCT\n"
2741 ", Texture_CubeProjection\n"
2746 "#ifdef USEDIFFUSE\n"
2747 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2749 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2751 "#ifdef USESPECULAR\n"
2752 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2754 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2757 "# ifdef USECUBEFILTER\n"
2758 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2759 " gl_FragData0.rgb *= cubecolor;\n"
2760 " gl_FragData1.rgb *= cubecolor;\n"
2763 "#endif // FRAGMENT_SHADER\n"
2764 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2769 "#ifdef VERTEX_SHADER\n"
2772 "float4 gl_Vertex : POSITION,\n"
2773 "uniform float4x4 ModelViewProjectionMatrix,\n"
2774 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2775 "float4 gl_Color : COLOR0,\n"
2777 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2778 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2779 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2780 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2781 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2783 "uniform float3 EyePosition,\n"
2784 "uniform float4x4 TexMatrix,\n"
2785 "#ifdef USEVERTEXTEXTUREBLEND\n"
2786 "uniform float4x4 BackgroundTexMatrix,\n"
2788 "#ifdef MODE_LIGHTSOURCE\n"
2789 "uniform float4x4 ModelToLight,\n"
2791 "#ifdef MODE_LIGHTSOURCE\n"
2792 "uniform float3 LightPosition,\n"
2794 "#ifdef MODE_LIGHTDIRECTION\n"
2795 "uniform float3 LightDir,\n"
2797 "uniform float4 FogPlane,\n"
2798 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2799 "uniform float3 LightPosition,\n"
2801 "#ifdef USESHADOWMAPORTHO\n"
2802 "uniform float4x4 ShadowMapMatrix,\n"
2805 "out float4 gl_FrontColor : COLOR,\n"
2806 "out float4 TexCoordBoth : TEXCOORD0,\n"
2807 "#ifdef USELIGHTMAP\n"
2808 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2810 "#ifdef USEEYEVECTOR\n"
2811 "out float3 EyeVector : TEXCOORD2,\n"
2813 "#ifdef USEREFLECTION\n"
2814 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2817 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2819 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2820 "out float3 LightVector : TEXCOORD1,\n"
2822 "#ifdef MODE_LIGHTSOURCE\n"
2823 "out float3 CubeVector : TEXCOORD3,\n"
2825 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2826 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2827 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2828 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2830 "#ifdef USESHADOWMAPORTHO\n"
2831 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2833 "out float4 gl_Position : POSITION\n"
2836 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2837 " gl_FrontColor = gl_Color;\n"
2839 " // copy the surface texcoord\n"
2840 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2841 "#ifdef USEVERTEXTEXTUREBLEND\n"
2842 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2844 "#ifdef USELIGHTMAP\n"
2845 " TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2848 "#ifdef MODE_LIGHTSOURCE\n"
2849 " // transform vertex position into light attenuation/cubemap space\n"
2850 " // (-1 to +1 across the light box)\n"
2851 " CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2853 "# ifdef USEDIFFUSE\n"
2854 " // transform unnormalized light direction into tangent space\n"
2855 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2856 " // normalize it per pixel)\n"
2857 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2858 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2859 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2860 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2864 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2865 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2866 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2867 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2870 " // transform unnormalized eye direction into tangent space\n"
2871 "#ifdef USEEYEVECTOR\n"
2872 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2873 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2874 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2875 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2879 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2880 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2883 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2884 " VectorS = gl_MultiTexCoord1.xyz;\n"
2885 " VectorT = gl_MultiTexCoord2.xyz;\n"
2886 " VectorR = gl_MultiTexCoord3.xyz;\n"
2889 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2890 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2892 "#ifdef USESHADOWMAPORTHO\n"
2893 " ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2896 "#ifdef USEREFLECTION\n"
2897 " ModelViewProjectionPosition = gl_Position;\n"
2900 "#endif // VERTEX_SHADER\n"
2905 "#ifdef FRAGMENT_SHADER\n"
2908 "#ifdef USEDEFERREDLIGHTMAP\n"
2909 "float2 Pixel : WPOS,\n"
2911 "float4 gl_FrontColor : COLOR,\n"
2912 "float4 TexCoordBoth : TEXCOORD0,\n"
2913 "#ifdef USELIGHTMAP\n"
2914 "float2 TexCoordLightmap : TEXCOORD1,\n"
2916 "#ifdef USEEYEVECTOR\n"
2917 "float3 EyeVector : TEXCOORD2,\n"
2919 "#ifdef USEREFLECTION\n"
2920 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2923 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2925 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2926 "float3 LightVector : TEXCOORD1,\n"
2928 "#ifdef MODE_LIGHTSOURCE\n"
2929 "float3 CubeVector : TEXCOORD3,\n"
2931 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2932 "float4 ModelViewPosition : TEXCOORD0,\n"
2934 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2935 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2936 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2937 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2939 "#ifdef USESHADOWMAPORTHO\n"
2940 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2943 "uniform sampler2D Texture_Normal,\n"
2944 "uniform sampler2D Texture_Color,\n"
2945 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2946 "uniform sampler2D Texture_Gloss,\n"
2949 "uniform sampler2D Texture_Glow,\n"
2951 "#ifdef USEVERTEXTEXTUREBLEND\n"
2952 "uniform sampler2D Texture_SecondaryNormal,\n"
2953 "uniform sampler2D Texture_SecondaryColor,\n"
2954 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2955 "uniform sampler2D Texture_SecondaryGloss,\n"
2958 "uniform sampler2D Texture_SecondaryGlow,\n"
2961 "#ifdef USECOLORMAPPING\n"
2962 "uniform sampler2D Texture_Pants,\n"
2963 "uniform sampler2D Texture_Shirt,\n"
2966 "uniform sampler2D Texture_FogHeightTexture,\n"
2967 "uniform sampler2D Texture_FogMask,\n"
2969 "#ifdef USELIGHTMAP\n"
2970 "uniform sampler2D Texture_Lightmap,\n"
2972 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2973 "uniform sampler2D Texture_Deluxemap,\n"
2975 "#ifdef USEREFLECTION\n"
2976 "uniform sampler2D Texture_Reflection,\n"
2979 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2980 "uniform sampler2D Texture_ScreenDepth,\n"
2981 "uniform sampler2D Texture_ScreenNormalMap,\n"
2983 "#ifdef USEDEFERREDLIGHTMAP\n"
2984 "uniform sampler2D Texture_ScreenDiffuse,\n"
2985 "uniform sampler2D Texture_ScreenSpecular,\n"
2988 "#ifdef USECOLORMAPPING\n"
2989 "uniform half3 Color_Pants,\n"
2990 "uniform half3 Color_Shirt,\n"
2993 "uniform float3 FogColor,\n"
2994 "uniform float FogRangeRecip,\n"
2995 "uniform float FogPlaneViewDist,\n"
2996 "uniform float FogHeightFade,\n"
2999 "#ifdef USEOFFSETMAPPING\n"
3000 "uniform float OffsetMapping_Scale,\n"
3003 "#ifdef USEDEFERREDLIGHTMAP\n"
3004 "uniform half2 PixelToScreenTexCoord,\n"
3005 "uniform half3 DeferredMod_Diffuse,\n"
3006 "uniform half3 DeferredMod_Specular,\n"
3008 "uniform half3 Color_Ambient,\n"
3009 "uniform half3 Color_Diffuse,\n"
3010 "uniform half3 Color_Specular,\n"
3011 "uniform half SpecularPower,\n"
3013 "uniform half3 Color_Glow,\n"
3015 "uniform half Alpha,\n"
3016 "#ifdef USEREFLECTION\n"
3017 "uniform float4 DistortScaleRefractReflect,\n"
3018 "uniform float4 ScreenScaleRefractReflect,\n"
3019 "uniform float4 ScreenCenterRefractReflect,\n"
3020 "uniform half4 ReflectColor,\n"
3022 "#ifdef USEREFLECTCUBE\n"
3023 "uniform float4x4 ModelToReflectCube,\n"
3024 "uniform sampler2D Texture_ReflectMask,\n"
3025 "uniform samplerCUBE Texture_ReflectCube,\n"
3027 "#ifdef MODE_LIGHTDIRECTION\n"
3028 "uniform half3 LightColor,\n"
3030 "#ifdef MODE_LIGHTSOURCE\n"
3031 "uniform half3 LightColor,\n"
3034 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3035 "uniform sampler2D Texture_Attenuation,\n"
3036 "uniform samplerCUBE Texture_Cube,\n"
3039 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3041 "#ifdef USESHADOWMAPRECT\n"
3042 "# ifdef USESHADOWSAMPLER\n"
3043 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3045 "uniform samplerRECT Texture_ShadowMapRect,\n"
3049 "#ifdef USESHADOWMAP2D\n"
3050 "# ifdef USESHADOWSAMPLER\n"
3051 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3053 "uniform sampler2D Texture_ShadowMap2D,\n"
3057 "#ifdef USESHADOWMAPVSDCT\n"
3058 "uniform samplerCUBE Texture_CubeProjection,\n"
3061 "#ifdef USESHADOWMAPCUBE\n"
3062 "# ifdef USESHADOWSAMPLER\n"
3063 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3065 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3069 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3070 "uniform float2 ShadowMap_TextureScale,\n"
3071 "uniform float4 ShadowMap_Parameters,\n"
3073 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3075 "out float4 gl_FragColor : COLOR\n"
3078 " float2 TexCoord = TexCoordBoth.xy;\n"
3079 "#ifdef USEVERTEXTEXTUREBLEND\n"
3080 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3082 "#ifdef USEOFFSETMAPPING\n"
3083 " // apply offsetmapping\n"
3084 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3085 "#define TexCoord TexCoordOffset\n"
3088 " // combine the diffuse textures (base, pants, shirt)\n"
3089 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3090 "#ifdef USEALPHAKILL\n"
3091 " if (color.a < 0.5)\n"
3094 " color.a *= Alpha;\n"
3095 "#ifdef USECOLORMAPPING\n"
3096 " color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3098 "#ifdef USEVERTEXTEXTUREBLEND\n"
3099 " float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3100 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3101 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3102 " color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3104 " //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3107 " // get the surface normal\n"
3108 "#ifdef USEVERTEXTEXTUREBLEND\n"
3109 " half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3111 " half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3114 " // get the material colors\n"
3115 " half3 diffusetex = color.rgb;\n"
3116 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3117 "# ifdef USEVERTEXTEXTUREBLEND\n"
3118 " half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3120 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3124 "#ifdef USEREFLECTCUBE\n"
3125 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3126 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3127 " float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3128 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3134 "#ifdef MODE_LIGHTSOURCE\n"
3135 " // light source\n"
3136 "#ifdef USEDIFFUSE\n"
3137 " half3 lightnormal = half3(normalize(LightVector));\n"
3138 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3139 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3140 "#ifdef USESPECULAR\n"
3141 "#ifdef USEEXACTSPECULARMATH\n"
3142 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3144 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3145 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3147 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3150 " color.rgb = diffusetex * Color_Ambient;\n"
3152 " color.rgb *= LightColor;\n"
3153 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3154 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3155 " color.rgb *= ShadowMapCompare(CubeVector,\n"
3156 "# if defined(USESHADOWMAP2D)\n"
3157 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3159 "# if defined(USESHADOWMAPRECT)\n"
3160 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3162 "# if defined(USESHADOWMAPCUBE)\n"
3163 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3166 "#ifdef USESHADOWMAPVSDCT\n"
3167 ", Texture_CubeProjection\n"
3172 "# ifdef USECUBEFILTER\n"
3173 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3175 "#endif // MODE_LIGHTSOURCE\n"
3180 "#ifdef MODE_LIGHTDIRECTION\n"
3182 "#ifdef USEDIFFUSE\n"
3183 " half3 lightnormal = half3(normalize(LightVector));\n"
3185 "#define lightcolor LightColor\n"
3186 "#endif // MODE_LIGHTDIRECTION\n"
3187 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3189 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3190 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3191 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3192 " // convert modelspace light vector to tangentspace\n"
3193 " half3 lightnormal;\n"
3194 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3195 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3196 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3197 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3198 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3199 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3200 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3201 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3202 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3203 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3204 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3205 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3206 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3207 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3208 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3210 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3211 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3212 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3218 "#ifdef MODE_LIGHTMAP\n"
3219 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3220 "#endif // MODE_LIGHTMAP\n"
3221 "#ifdef MODE_VERTEXCOLOR\n"
3222 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3223 "#endif // MODE_VERTEXCOLOR\n"
3224 "#ifdef MODE_FLATCOLOR\n"
3225 " color.rgb = diffusetex * Color_Ambient;\n"
3226 "#endif // MODE_FLATCOLOR\n"
3232 "# ifdef USEDIFFUSE\n"
3233 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3234 "# ifdef USESPECULAR\n"
3235 "# ifdef USEEXACTSPECULARMATH\n"
3236 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3238 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3239 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3241 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3243 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3246 " color.rgb = diffusetex * Color_Ambient;\n"
3250 "#ifdef USESHADOWMAPORTHO\n"
3251 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3252 "# if defined(USESHADOWMAP2D)\n"
3253 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3255 "# if defined(USESHADOWMAPRECT)\n"
3256 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3261 "#ifdef USEDEFERREDLIGHTMAP\n"
3262 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3263 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3264 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3268 "#ifdef USEVERTEXTEXTUREBLEND\n"
3269 " color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3271 " color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3276 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3279 " // 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"
3280 "#ifdef USEREFLECTION\n"
3281 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3282 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3283 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3284 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3285 " // FIXME temporary hack to detect the case that the reflection\n"
3286 " // gets blackened at edges due to leaving the area that contains actual\n"
3288 " // Remove this 'ack once we have a better way to stop this thing from\n"
3290 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3291 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3292 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3293 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3294 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3295 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3298 " gl_FragColor = float4(color);\n"
3300 "#endif // FRAGMENT_SHADER\n"
3302 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3303 "#endif // !MODE_DEFERREDGEOMETRY\n"
3304 "#endif // !MODE_WATER\n"
3305 "#endif // !MODE_REFRACTION\n"
3306 "#endif // !MODE_BLOOMBLUR\n"
3307 "#endif // !MODE_GENERIC\n"
3308 "#endif // !MODE_POSTPROCESS\n"
3309 "#endif // !MODE_SHOWDEPTH\n"
3310 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3313 char *glslshaderstring = NULL;
3314 char *cgshaderstring = NULL;
3316 //=======================================================================================================================================================
3318 typedef struct shaderpermutationinfo_s
3320 const char *pretext;
3323 shaderpermutationinfo_t;
3325 typedef struct shadermodeinfo_s
3327 const char *vertexfilename;
3328 const char *geometryfilename;
3329 const char *fragmentfilename;
3330 const char *pretext;
3335 typedef enum shaderpermutation_e
3337 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3338 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3339 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3340 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3341 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3342 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3343 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3344 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3345 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3346 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3347 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3348 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3349 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3350 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3351 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3352 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3353 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3354 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3355 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3356 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3357 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3358 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3359 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3360 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3361 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3362 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3363 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3364 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3365 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3366 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3367 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3369 shaderpermutation_t;
3371 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3372 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3374 {"#define USEDIFFUSE\n", " diffuse"},
3375 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3376 {"#define USEVIEWTINT\n", " viewtint"},
3377 {"#define USECOLORMAPPING\n", " colormapping"},
3378 {"#define USESATURATION\n", " saturation"},
3379 {"#define USEFOGINSIDE\n", " foginside"},
3380 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3381 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3382 {"#define USEGAMMARAMPS\n", " gammaramps"},
3383 {"#define USECUBEFILTER\n", " cubefilter"},
3384 {"#define USEGLOW\n", " glow"},
3385 {"#define USEBLOOM\n", " bloom"},
3386 {"#define USESPECULAR\n", " specular"},
3387 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3388 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3389 {"#define USEREFLECTION\n", " reflection"},
3390 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3391 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3392 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3393 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3394 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3395 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3396 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3397 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3398 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3399 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3400 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3401 {"#define USEALPHAKILL\n", " alphakill"},
3402 {"#define USEREFLECTCUBE\n", " reflectcube"},
3405 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3406 typedef enum shadermode_e
3408 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3409 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3410 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3411 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3412 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3413 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3414 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3415 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3416 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3417 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3418 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3419 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3420 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3421 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3422 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3427 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3428 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3430 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3431 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3432 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3433 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3434 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3435 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3436 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3437 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3438 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3439 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3440 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3441 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3442 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3443 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3444 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3448 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3450 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3451 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3452 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3453 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3454 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3455 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3456 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3457 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3458 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3459 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3460 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3461 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3462 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3463 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3464 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3468 struct r_glsl_permutation_s;
3469 typedef struct r_glsl_permutation_s
3471 /// hash lookup data
3472 struct r_glsl_permutation_s *hashnext;
3474 unsigned int permutation;
3476 /// indicates if we have tried compiling this permutation already
3478 /// 0 if compilation failed
3480 /// locations of detected uniforms in program object, or -1 if not found
3481 int loc_Texture_First;
3482 int loc_Texture_Second;
3483 int loc_Texture_GammaRamps;
3484 int loc_Texture_Normal;
3485 int loc_Texture_Color;
3486 int loc_Texture_Gloss;
3487 int loc_Texture_Glow;
3488 int loc_Texture_SecondaryNormal;
3489 int loc_Texture_SecondaryColor;
3490 int loc_Texture_SecondaryGloss;
3491 int loc_Texture_SecondaryGlow;
3492 int loc_Texture_Pants;
3493 int loc_Texture_Shirt;
3494 int loc_Texture_FogHeightTexture;
3495 int loc_Texture_FogMask;
3496 int loc_Texture_Lightmap;
3497 int loc_Texture_Deluxemap;
3498 int loc_Texture_Attenuation;
3499 int loc_Texture_Cube;
3500 int loc_Texture_Refraction;
3501 int loc_Texture_Reflection;
3502 int loc_Texture_ShadowMapRect;
3503 int loc_Texture_ShadowMapCube;
3504 int loc_Texture_ShadowMap2D;
3505 int loc_Texture_CubeProjection;
3506 int loc_Texture_ScreenDepth;
3507 int loc_Texture_ScreenNormalMap;
3508 int loc_Texture_ScreenDiffuse;
3509 int loc_Texture_ScreenSpecular;
3510 int loc_Texture_ReflectMask;
3511 int loc_Texture_ReflectCube;
3513 int loc_BloomBlur_Parameters;
3515 int loc_Color_Ambient;
3516 int loc_Color_Diffuse;
3517 int loc_Color_Specular;
3519 int loc_Color_Pants;
3520 int loc_Color_Shirt;
3521 int loc_DeferredColor_Ambient;
3522 int loc_DeferredColor_Diffuse;
3523 int loc_DeferredColor_Specular;
3524 int loc_DeferredMod_Diffuse;
3525 int loc_DeferredMod_Specular;
3526 int loc_DistortScaleRefractReflect;
3527 int loc_EyePosition;
3529 int loc_FogHeightFade;
3531 int loc_FogPlaneViewDist;
3532 int loc_FogRangeRecip;
3535 int loc_LightPosition;
3536 int loc_OffsetMapping_Scale;
3538 int loc_ReflectColor;
3539 int loc_ReflectFactor;
3540 int loc_ReflectOffset;
3541 int loc_RefractColor;
3543 int loc_ScreenCenterRefractReflect;
3544 int loc_ScreenScaleRefractReflect;
3545 int loc_ScreenToDepth;
3546 int loc_ShadowMap_Parameters;
3547 int loc_ShadowMap_TextureScale;
3548 int loc_SpecularPower;
3553 int loc_ViewTintColor;
3554 int loc_ViewToLight;
3555 int loc_ModelToLight;
3557 int loc_BackgroundTexMatrix;
3558 int loc_ModelViewProjectionMatrix;
3559 int loc_ModelViewMatrix;
3560 int loc_PixelToScreenTexCoord;
3561 int loc_ModelToReflectCube;
3562 int loc_ShadowMapMatrix;
3564 r_glsl_permutation_t;
3566 #define SHADERPERMUTATION_HASHSIZE 256
3568 /// information about each possible shader permutation
3569 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3570 /// currently selected permutation
3571 r_glsl_permutation_t *r_glsl_permutation;
3572 /// storage for permutations linked in the hash table
3573 memexpandablearray_t r_glsl_permutationarray;
3575 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3577 //unsigned int hashdepth = 0;
3578 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3579 r_glsl_permutation_t *p;
3580 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3582 if (p->mode == mode && p->permutation == permutation)
3584 //if (hashdepth > 10)
3585 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3590 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3592 p->permutation = permutation;
3593 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3594 r_glsl_permutationhash[mode][hashindex] = p;
3595 //if (hashdepth > 10)
3596 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3600 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3603 if (!filename || !filename[0])
3605 if (!strcmp(filename, "glsl/default.glsl"))
3607 if (!glslshaderstring)
3609 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3610 if (glslshaderstring)
3611 Con_DPrintf("Loading shaders from file %s...\n", filename);
3613 glslshaderstring = (char *)builtinshaderstring;
3615 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3616 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3617 return shaderstring;
3619 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3622 if (printfromdisknotice)
3623 Con_DPrintf("from disk %s... ", filename);
3624 return shaderstring;
3626 return shaderstring;
3629 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3632 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3633 int vertstrings_count = 0;
3634 int geomstrings_count = 0;
3635 int fragstrings_count = 0;
3636 char *vertexstring, *geometrystring, *fragmentstring;
3637 const char *vertstrings_list[32+3];
3638 const char *geomstrings_list[32+3];
3639 const char *fragstrings_list[32+3];
3640 char permutationname[256];
3647 permutationname[0] = 0;
3648 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3649 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3650 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3652 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3654 // the first pretext is which type of shader to compile as
3655 // (later these will all be bound together as a program object)
3656 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3657 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3658 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3660 // the second pretext is the mode (for example a light source)
3661 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3662 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3663 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3664 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3666 // now add all the permutation pretexts
3667 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3669 if (permutation & (1<<i))
3671 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3672 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3673 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3674 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3678 // keep line numbers correct
3679 vertstrings_list[vertstrings_count++] = "\n";
3680 geomstrings_list[geomstrings_count++] = "\n";
3681 fragstrings_list[fragstrings_count++] = "\n";
3685 // now append the shader text itself
3686 vertstrings_list[vertstrings_count++] = vertexstring;
3687 geomstrings_list[geomstrings_count++] = geometrystring;
3688 fragstrings_list[fragstrings_count++] = fragmentstring;
3690 // if any sources were NULL, clear the respective list
3692 vertstrings_count = 0;
3693 if (!geometrystring)
3694 geomstrings_count = 0;
3695 if (!fragmentstring)
3696 fragstrings_count = 0;
3698 // compile the shader program
3699 if (vertstrings_count + geomstrings_count + fragstrings_count)
3700 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3704 qglUseProgramObjectARB(p->program);CHECKGLERROR
3705 // look up all the uniform variable names we care about, so we don't
3706 // have to look them up every time we set them
3708 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3709 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3710 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3711 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3712 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3713 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3714 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3715 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3716 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3717 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3718 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3719 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3720 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3721 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3722 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3723 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3724 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3725 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3726 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3727 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3728 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3729 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3730 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3731 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3732 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3733 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3734 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3735 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3736 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3737 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3738 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3739 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3740 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3741 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3742 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3743 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3744 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3745 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3746 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3747 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3748 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3749 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3750 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3751 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3752 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3753 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3754 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3755 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3756 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3757 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3758 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3759 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3760 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3761 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3762 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3763 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3764 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3765 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3766 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3767 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3768 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3769 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3770 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3771 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3772 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3773 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3774 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3775 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3776 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3777 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3778 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3779 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3780 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3781 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3782 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3783 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3784 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3785 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3786 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3787 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3788 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3789 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3790 // initialize the samplers to refer to the texture units we use
3791 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3792 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3793 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3794 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3795 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3796 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3797 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3798 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3799 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3800 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3801 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3802 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3803 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3804 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3805 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3806 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3807 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3808 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3809 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3810 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3811 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3812 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3813 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3814 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3815 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3816 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3817 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3818 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3819 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3820 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3821 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3823 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3826 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3830 Mem_Free(vertexstring);
3832 Mem_Free(geometrystring);
3834 Mem_Free(fragmentstring);
3837 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3839 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3840 if (r_glsl_permutation != perm)
3842 r_glsl_permutation = perm;
3843 if (!r_glsl_permutation->program)
3845 if (!r_glsl_permutation->compiled)
3846 R_GLSL_CompilePermutation(perm, mode, permutation);
3847 if (!r_glsl_permutation->program)
3849 // remove features until we find a valid permutation
3851 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3853 // reduce i more quickly whenever it would not remove any bits
3854 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3855 if (!(permutation & j))
3858 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3859 if (!r_glsl_permutation->compiled)
3860 R_GLSL_CompilePermutation(perm, mode, permutation);
3861 if (r_glsl_permutation->program)
3864 if (i >= SHADERPERMUTATION_COUNT)
3866 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3867 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3868 qglUseProgramObjectARB(0);CHECKGLERROR
3869 return; // no bit left to clear, entire mode is broken
3874 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3876 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3877 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3878 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3882 #include <Cg/cgGL.h>
3883 struct r_cg_permutation_s;
3884 typedef struct r_cg_permutation_s
3886 /// hash lookup data
3887 struct r_cg_permutation_s *hashnext;
3889 unsigned int permutation;
3891 /// indicates if we have tried compiling this permutation already
3893 /// 0 if compilation failed
3896 /// locations of detected parameters in programs, or NULL if not found
3897 CGparameter vp_EyePosition;
3898 CGparameter vp_FogPlane;
3899 CGparameter vp_LightDir;
3900 CGparameter vp_LightPosition;
3901 CGparameter vp_ModelToLight;
3902 CGparameter vp_TexMatrix;
3903 CGparameter vp_BackgroundTexMatrix;
3904 CGparameter vp_ModelViewProjectionMatrix;
3905 CGparameter vp_ModelViewMatrix;
3906 CGparameter vp_ShadowMapMatrix;
3908 CGparameter fp_Texture_First;
3909 CGparameter fp_Texture_Second;
3910 CGparameter fp_Texture_GammaRamps;
3911 CGparameter fp_Texture_Normal;
3912 CGparameter fp_Texture_Color;
3913 CGparameter fp_Texture_Gloss;
3914 CGparameter fp_Texture_Glow;
3915 CGparameter fp_Texture_SecondaryNormal;
3916 CGparameter fp_Texture_SecondaryColor;
3917 CGparameter fp_Texture_SecondaryGloss;
3918 CGparameter fp_Texture_SecondaryGlow;
3919 CGparameter fp_Texture_Pants;
3920 CGparameter fp_Texture_Shirt;
3921 CGparameter fp_Texture_FogHeightTexture;
3922 CGparameter fp_Texture_FogMask;
3923 CGparameter fp_Texture_Lightmap;
3924 CGparameter fp_Texture_Deluxemap;
3925 CGparameter fp_Texture_Attenuation;
3926 CGparameter fp_Texture_Cube;
3927 CGparameter fp_Texture_Refraction;
3928 CGparameter fp_Texture_Reflection;
3929 CGparameter fp_Texture_ShadowMapRect;
3930 CGparameter fp_Texture_ShadowMapCube;
3931 CGparameter fp_Texture_ShadowMap2D;
3932 CGparameter fp_Texture_CubeProjection;
3933 CGparameter fp_Texture_ScreenDepth;
3934 CGparameter fp_Texture_ScreenNormalMap;
3935 CGparameter fp_Texture_ScreenDiffuse;
3936 CGparameter fp_Texture_ScreenSpecular;
3937 CGparameter fp_Texture_ReflectMask;
3938 CGparameter fp_Texture_ReflectCube;
3939 CGparameter fp_Alpha;
3940 CGparameter fp_BloomBlur_Parameters;
3941 CGparameter fp_ClientTime;
3942 CGparameter fp_Color_Ambient;
3943 CGparameter fp_Color_Diffuse;
3944 CGparameter fp_Color_Specular;
3945 CGparameter fp_Color_Glow;
3946 CGparameter fp_Color_Pants;
3947 CGparameter fp_Color_Shirt;
3948 CGparameter fp_DeferredColor_Ambient;
3949 CGparameter fp_DeferredColor_Diffuse;
3950 CGparameter fp_DeferredColor_Specular;
3951 CGparameter fp_DeferredMod_Diffuse;
3952 CGparameter fp_DeferredMod_Specular;
3953 CGparameter fp_DistortScaleRefractReflect;
3954 CGparameter fp_EyePosition;
3955 CGparameter fp_FogColor;
3956 CGparameter fp_FogHeightFade;
3957 CGparameter fp_FogPlane;
3958 CGparameter fp_FogPlaneViewDist;
3959 CGparameter fp_FogRangeRecip;
3960 CGparameter fp_LightColor;
3961 CGparameter fp_LightDir;
3962 CGparameter fp_LightPosition;
3963 CGparameter fp_OffsetMapping_Scale;
3964 CGparameter fp_PixelSize;
3965 CGparameter fp_ReflectColor;
3966 CGparameter fp_ReflectFactor;
3967 CGparameter fp_ReflectOffset;
3968 CGparameter fp_RefractColor;
3969 CGparameter fp_Saturation;
3970 CGparameter fp_ScreenCenterRefractReflect;
3971 CGparameter fp_ScreenScaleRefractReflect;
3972 CGparameter fp_ScreenToDepth;
3973 CGparameter fp_ShadowMap_Parameters;
3974 CGparameter fp_ShadowMap_TextureScale;
3975 CGparameter fp_SpecularPower;
3976 CGparameter fp_UserVec1;
3977 CGparameter fp_UserVec2;
3978 CGparameter fp_UserVec3;
3979 CGparameter fp_UserVec4;
3980 CGparameter fp_ViewTintColor;
3981 CGparameter fp_ViewToLight;
3982 CGparameter fp_PixelToScreenTexCoord;
3983 CGparameter fp_ModelToReflectCube;
3987 /// information about each possible shader permutation
3988 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3989 /// currently selected permutation
3990 r_cg_permutation_t *r_cg_permutation;
3991 /// storage for permutations linked in the hash table
3992 memexpandablearray_t r_cg_permutationarray;
3994 #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));}}
3996 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
3998 //unsigned int hashdepth = 0;
3999 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4000 r_cg_permutation_t *p;
4001 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4003 if (p->mode == mode && p->permutation == permutation)
4005 //if (hashdepth > 10)
4006 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4011 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4013 p->permutation = permutation;
4014 p->hashnext = r_cg_permutationhash[mode][hashindex];
4015 r_cg_permutationhash[mode][hashindex] = p;
4016 //if (hashdepth > 10)
4017 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4021 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4024 if (!filename || !filename[0])
4026 if (!strcmp(filename, "cg/default.cg"))
4028 if (!cgshaderstring)
4030 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4032 Con_DPrintf("Loading shaders from file %s...\n", filename);
4034 cgshaderstring = (char *)builtincgshaderstring;
4036 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4037 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4038 return shaderstring;
4040 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4043 if (printfromdisknotice)
4044 Con_DPrintf("from disk %s... ", filename);
4045 return shaderstring;
4047 return shaderstring;
4050 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4052 // TODO: load or create .fp and .vp shader files
4055 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4058 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4059 int vertstrings_count = 0, vertstring_length = 0;
4060 int geomstrings_count = 0, geomstring_length = 0;
4061 int fragstrings_count = 0, fragstring_length = 0;
4063 char *vertexstring, *geometrystring, *fragmentstring;
4064 char *vertstring, *geomstring, *fragstring;
4065 const char *vertstrings_list[32+3];
4066 const char *geomstrings_list[32+3];
4067 const char *fragstrings_list[32+3];
4068 char permutationname[256];
4069 char cachename[256];
4070 CGprofile vertexProfile;
4071 CGprofile fragmentProfile;
4079 permutationname[0] = 0;
4081 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4082 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4083 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4085 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4086 strlcat(cachename, "cg/", sizeof(cachename));
4088 // the first pretext is which type of shader to compile as
4089 // (later these will all be bound together as a program object)
4090 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4091 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4092 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4094 // the second pretext is the mode (for example a light source)
4095 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4096 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4097 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4098 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4099 strlcat(cachename, modeinfo->name, sizeof(cachename));
4101 // now add all the permutation pretexts
4102 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4104 if (permutation & (1<<i))
4106 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4107 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4108 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4109 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4110 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4114 // keep line numbers correct
4115 vertstrings_list[vertstrings_count++] = "\n";
4116 geomstrings_list[geomstrings_count++] = "\n";
4117 fragstrings_list[fragstrings_count++] = "\n";
4121 // replace spaces in the cachename with _ characters
4122 for (i = 0;cachename[i];i++)
4123 if (cachename[i] == ' ')
4126 // now append the shader text itself
4127 vertstrings_list[vertstrings_count++] = vertexstring;
4128 geomstrings_list[geomstrings_count++] = geometrystring;
4129 fragstrings_list[fragstrings_count++] = fragmentstring;
4131 // if any sources were NULL, clear the respective list
4133 vertstrings_count = 0;
4134 if (!geometrystring)
4135 geomstrings_count = 0;
4136 if (!fragmentstring)
4137 fragstrings_count = 0;
4139 vertstring_length = 0;
4140 for (i = 0;i < vertstrings_count;i++)
4141 vertstring_length += strlen(vertstrings_list[i]);
4142 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4143 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4144 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4146 geomstring_length = 0;
4147 for (i = 0;i < geomstrings_count;i++)
4148 geomstring_length += strlen(geomstrings_list[i]);
4149 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4150 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4151 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4153 fragstring_length = 0;
4154 for (i = 0;i < fragstrings_count;i++)
4155 fragstring_length += strlen(fragstrings_list[i]);
4156 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4157 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4158 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4162 //vertexProfile = CG_PROFILE_ARBVP1;
4163 //fragmentProfile = CG_PROFILE_ARBFP1;
4164 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4165 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4166 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4167 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4168 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4171 // try to load the cached shader, or generate one
4172 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4174 // if caching failed, do a dynamic compile for now
4176 if (vertstring[0] && !p->vprogram)
4177 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4179 if (fragstring[0] && !p->fprogram)
4180 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4183 // look up all the uniform variable names we care about, so we don't
4184 // have to look them up every time we set them
4188 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4189 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4190 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4191 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4192 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4193 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4194 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4195 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4196 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4197 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4198 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4199 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4205 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4206 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4207 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4208 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4209 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4210 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4211 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4212 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4213 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4214 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4215 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4216 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4217 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4218 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4219 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4220 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4221 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4222 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4223 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4224 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4225 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4226 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4227 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4228 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4229 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4230 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4231 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4232 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4233 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4234 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4235 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4236 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4237 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4238 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4239 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4240 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4241 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4242 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4243 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4244 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4245 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4246 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4247 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4248 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4249 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4250 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4251 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4252 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4253 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4254 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4255 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4256 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4257 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4258 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4259 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4260 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4261 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4262 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4263 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4264 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4265 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4266 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4267 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4268 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4269 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4270 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4271 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4272 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4273 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4274 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4275 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4276 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4277 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4278 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4279 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4280 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4281 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4282 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4286 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4287 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4289 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4293 Mem_Free(vertstring);
4295 Mem_Free(geomstring);
4297 Mem_Free(fragstring);
4299 Mem_Free(vertexstring);
4301 Mem_Free(geometrystring);
4303 Mem_Free(fragmentstring);
4306 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4308 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4311 if (r_cg_permutation != perm)
4313 r_cg_permutation = perm;
4314 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4316 if (!r_cg_permutation->compiled)
4317 R_CG_CompilePermutation(perm, mode, permutation);
4318 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4320 // remove features until we find a valid permutation
4322 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4324 // reduce i more quickly whenever it would not remove any bits
4325 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4326 if (!(permutation & j))
4329 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4330 if (!r_cg_permutation->compiled)
4331 R_CG_CompilePermutation(perm, mode, permutation);
4332 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4335 if (i >= SHADERPERMUTATION_COUNT)
4337 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4338 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4339 return; // no bit left to clear, entire mode is broken
4345 if (r_cg_permutation->vprogram)
4347 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4348 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4349 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4353 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4354 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4356 if (r_cg_permutation->fprogram)
4358 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4359 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4360 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4364 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4365 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4369 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4370 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4371 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4374 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4376 cgGLSetTextureParameter(param, R_GetTexture(tex));
4377 cgGLEnableTextureParameter(param);
4381 void R_GLSL_Restart_f(void)
4383 unsigned int i, limit;
4384 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4385 Mem_Free(glslshaderstring);
4386 glslshaderstring = NULL;
4387 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4388 Mem_Free(cgshaderstring);
4389 cgshaderstring = NULL;
4390 switch(vid.renderpath)
4392 case RENDERPATH_GL20:
4394 r_glsl_permutation_t *p;
4395 r_glsl_permutation = NULL;
4396 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4397 for (i = 0;i < limit;i++)
4399 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4401 GL_Backend_FreeProgram(p->program);
4402 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4405 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4408 case RENDERPATH_CGGL:
4411 r_cg_permutation_t *p;
4412 r_cg_permutation = NULL;
4413 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4414 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4415 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4416 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4417 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4418 for (i = 0;i < limit;i++)
4420 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4423 cgDestroyProgram(p->vprogram);
4425 cgDestroyProgram(p->fprogram);
4426 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4429 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4433 case RENDERPATH_GL13:
4434 case RENDERPATH_GL11:
4439 void R_GLSL_DumpShader_f(void)
4444 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4447 FS_Print(file, "/* The engine may define the following macros:\n");
4448 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4449 for (i = 0;i < SHADERMODE_COUNT;i++)
4450 FS_Print(file, glslshadermodeinfo[i].pretext);
4451 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4452 FS_Print(file, shaderpermutationinfo[i].pretext);
4453 FS_Print(file, "*/\n");
4454 FS_Print(file, builtinshaderstring);
4456 Con_Printf("glsl/default.glsl written\n");
4459 Con_Printf("failed to write to glsl/default.glsl\n");
4462 file = FS_OpenRealFile("cg/default.cg", "w", false);
4465 FS_Print(file, "/* The engine may define the following macros:\n");
4466 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4467 for (i = 0;i < SHADERMODE_COUNT;i++)
4468 FS_Print(file, cgshadermodeinfo[i].pretext);
4469 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4470 FS_Print(file, shaderpermutationinfo[i].pretext);
4471 FS_Print(file, "*/\n");
4472 FS_Print(file, builtincgshaderstring);
4474 Con_Printf("cg/default.cg written\n");
4477 Con_Printf("failed to write to cg/default.cg\n");
4481 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4484 texturemode = GL_MODULATE;
4485 switch (vid.renderpath)
4487 case RENDERPATH_GL20:
4488 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4489 if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
4490 if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
4492 case RENDERPATH_CGGL:
4495 R_SetupShader_SetPermutationCG(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4496 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
4497 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
4500 case RENDERPATH_GL13:
4501 R_Mesh_TexBind(0, first );
4502 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4503 R_Mesh_TexBind(1, second);
4505 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4507 case RENDERPATH_GL11:
4508 R_Mesh_TexBind(0, first );
4513 void R_SetupShader_DepthOrShadow(void)
4515 switch (vid.renderpath)
4517 case RENDERPATH_GL20:
4518 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4520 case RENDERPATH_CGGL:
4522 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
4525 case RENDERPATH_GL13:
4526 R_Mesh_TexBind(0, 0);
4527 R_Mesh_TexBind(1, 0);
4529 case RENDERPATH_GL11:
4530 R_Mesh_TexBind(0, 0);
4535 void R_SetupShader_ShowDepth(void)
4537 switch (vid.renderpath)
4539 case RENDERPATH_GL20:
4540 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4542 case RENDERPATH_CGGL:
4544 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
4547 case RENDERPATH_GL13:
4549 case RENDERPATH_GL11:
4554 extern qboolean r_shadow_usingdeferredprepass;
4555 extern cvar_t r_shadow_deferred_8bitrange;
4556 extern rtexture_t *r_shadow_attenuationgradienttexture;
4557 extern rtexture_t *r_shadow_attenuation2dtexture;
4558 extern rtexture_t *r_shadow_attenuation3dtexture;
4559 extern qboolean r_shadow_usingshadowmaprect;
4560 extern qboolean r_shadow_usingshadowmapcube;
4561 extern qboolean r_shadow_usingshadowmap2d;
4562 extern qboolean r_shadow_usingshadowmaportho;
4563 extern float r_shadow_shadowmap_texturescale[2];
4564 extern float r_shadow_shadowmap_parameters[4];
4565 extern qboolean r_shadow_shadowmapvsdct;
4566 extern qboolean r_shadow_shadowmapsampler;
4567 extern int r_shadow_shadowmappcf;
4568 extern rtexture_t *r_shadow_shadowmaprectangletexture;
4569 extern rtexture_t *r_shadow_shadowmap2dtexture;
4570 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
4571 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4572 extern matrix4x4_t r_shadow_shadowmapmatrix;
4573 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4574 extern int r_shadow_prepass_width;
4575 extern int r_shadow_prepass_height;
4576 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4577 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4578 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4579 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4580 extern cvar_t gl_mesh_separatearrays;
4581 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist)
4583 // select a permutation of the lighting shader appropriate to this
4584 // combination of texture, entity, light source, and fogging, only use the
4585 // minimum features necessary to avoid wasting rendering time in the
4586 // fragment shader on features that are not being used
4587 unsigned int permutation = 0;
4588 unsigned int mode = 0;
4590 if (rsurfacepass == RSURFPASS_BACKGROUND)
4592 // distorted background
4593 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4594 mode = SHADERMODE_WATER;
4595 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4596 mode = SHADERMODE_REFRACTION;
4599 mode = SHADERMODE_GENERIC;
4600 permutation |= SHADERPERMUTATION_DIFFUSE;
4602 GL_AlphaTest(false);
4603 GL_BlendFunc(GL_ONE, GL_ZERO);
4605 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4607 if (r_glsl_offsetmapping.integer)
4609 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4610 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4611 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4612 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4613 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4615 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4616 if (r_glsl_offsetmapping_reliefmapping.integer)
4617 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4620 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4621 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4622 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4623 permutation |= SHADERPERMUTATION_ALPHAKILL;
4624 // normalmap (deferred prepass), may use alpha test on diffuse
4625 mode = SHADERMODE_DEFERREDGEOMETRY;
4626 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4627 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4628 GL_AlphaTest(false);
4629 GL_BlendFunc(GL_ONE, GL_ZERO);
4631 else if (rsurfacepass == RSURFPASS_RTLIGHT)
4633 if (r_glsl_offsetmapping.integer)
4635 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4636 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4637 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4638 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4639 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4641 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4642 if (r_glsl_offsetmapping_reliefmapping.integer)
4643 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4646 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4647 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4649 mode = SHADERMODE_LIGHTSOURCE;
4650 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4651 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4652 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4653 permutation |= SHADERPERMUTATION_CUBEFILTER;
4654 if (diffusescale > 0)
4655 permutation |= SHADERPERMUTATION_DIFFUSE;
4656 if (specularscale > 0)
4658 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4659 if (r_shadow_glossexact.integer)
4660 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4662 if (r_refdef.fogenabled)
4663 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4664 if (rsurface.texture->colormapping)
4665 permutation |= SHADERPERMUTATION_COLORMAPPING;
4666 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
4668 if (r_shadow_usingshadowmaprect)
4669 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4670 if (r_shadow_usingshadowmap2d)
4671 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4672 if (r_shadow_usingshadowmapcube)
4673 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
4674 else if(r_shadow_shadowmapvsdct)
4675 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
4677 if (r_shadow_shadowmapsampler)
4678 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4679 if (r_shadow_shadowmappcf > 1)
4680 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4681 else if (r_shadow_shadowmappcf)
4682 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4684 if (rsurface.texture->reflectmasktexture)
4685 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4686 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4687 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4689 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4691 if (r_glsl_offsetmapping.integer)
4693 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4694 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4695 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4696 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4697 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4699 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4700 if (r_glsl_offsetmapping_reliefmapping.integer)
4701 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4704 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4705 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4706 // unshaded geometry (fullbright or ambient model lighting)
4707 mode = SHADERMODE_FLATCOLOR;
4708 ambientscale = diffusescale = specularscale = 0;
4709 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4710 permutation |= SHADERPERMUTATION_GLOW;
4711 if (r_refdef.fogenabled)
4712 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4713 if (rsurface.texture->colormapping)
4714 permutation |= SHADERPERMUTATION_COLORMAPPING;
4715 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4717 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4718 if (r_shadow_usingshadowmaprect)
4719 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4720 if (r_shadow_usingshadowmap2d)
4721 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4723 if (r_shadow_shadowmapsampler)
4724 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4725 if (r_shadow_shadowmappcf > 1)
4726 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4727 else if (r_shadow_shadowmappcf)
4728 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4730 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4731 permutation |= SHADERPERMUTATION_REFLECTION;
4732 if (rsurface.texture->reflectmasktexture)
4733 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4734 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4735 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4737 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
4739 if (r_glsl_offsetmapping.integer)
4741 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4742 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4743 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4744 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4745 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4747 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4748 if (r_glsl_offsetmapping_reliefmapping.integer)
4749 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4752 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4753 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4754 // directional model lighting
4755 mode = SHADERMODE_LIGHTDIRECTION;
4756 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4757 permutation |= SHADERPERMUTATION_GLOW;
4758 permutation |= SHADERPERMUTATION_DIFFUSE;
4759 if (specularscale > 0)
4761 permutation |= SHADERPERMUTATION_SPECULAR;
4762 if (r_shadow_glossexact.integer)
4763 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4765 if (r_refdef.fogenabled)
4766 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4767 if (rsurface.texture->colormapping)
4768 permutation |= SHADERPERMUTATION_COLORMAPPING;
4769 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4771 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4772 if (r_shadow_usingshadowmaprect)
4773 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4774 if (r_shadow_usingshadowmap2d)
4775 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4777 if (r_shadow_shadowmapsampler)
4778 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4779 if (r_shadow_shadowmappcf > 1)
4780 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4781 else if (r_shadow_shadowmappcf)
4782 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4784 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4785 permutation |= SHADERPERMUTATION_REFLECTION;
4786 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4787 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4788 if (rsurface.texture->reflectmasktexture)
4789 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4790 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4791 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4793 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
4795 if (r_glsl_offsetmapping.integer)
4797 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4798 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4799 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4800 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4801 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4803 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4804 if (r_glsl_offsetmapping_reliefmapping.integer)
4805 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4808 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4809 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4810 // ambient model lighting
4811 mode = SHADERMODE_LIGHTDIRECTION;
4812 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4813 permutation |= SHADERPERMUTATION_GLOW;
4814 if (r_refdef.fogenabled)
4815 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4816 if (rsurface.texture->colormapping)
4817 permutation |= SHADERPERMUTATION_COLORMAPPING;
4818 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4820 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4821 if (r_shadow_usingshadowmaprect)
4822 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4823 if (r_shadow_usingshadowmap2d)
4824 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4826 if (r_shadow_shadowmapsampler)
4827 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4828 if (r_shadow_shadowmappcf > 1)
4829 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4830 else if (r_shadow_shadowmappcf)
4831 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4833 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4834 permutation |= SHADERPERMUTATION_REFLECTION;
4835 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4836 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4837 if (rsurface.texture->reflectmasktexture)
4838 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4839 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4840 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4844 if (r_glsl_offsetmapping.integer)
4846 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4847 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4848 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4849 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4850 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4852 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4853 if (r_glsl_offsetmapping_reliefmapping.integer)
4854 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4857 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4858 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4860 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4861 permutation |= SHADERPERMUTATION_GLOW;
4862 if (r_refdef.fogenabled)
4863 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4864 if (rsurface.texture->colormapping)
4865 permutation |= SHADERPERMUTATION_COLORMAPPING;
4866 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4868 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4869 if (r_shadow_usingshadowmaprect)
4870 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4871 if (r_shadow_usingshadowmap2d)
4872 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4874 if (r_shadow_shadowmapsampler)
4875 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4876 if (r_shadow_shadowmappcf > 1)
4877 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4878 else if (r_shadow_shadowmappcf)
4879 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4881 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4882 permutation |= SHADERPERMUTATION_REFLECTION;
4883 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4884 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4885 if (rsurface.texture->reflectmasktexture)
4886 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4887 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
4889 // deluxemapping (light direction texture)
4890 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
4891 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
4893 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
4894 permutation |= SHADERPERMUTATION_DIFFUSE;
4895 if (specularscale > 0)
4897 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4898 if (r_shadow_glossexact.integer)
4899 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4902 else if (r_glsl_deluxemapping.integer >= 2)
4904 // fake deluxemapping (uniform light direction in tangentspace)
4905 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
4906 permutation |= SHADERPERMUTATION_DIFFUSE;
4907 if (specularscale > 0)
4909 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4910 if (r_shadow_glossexact.integer)
4911 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4914 else if (rsurface.uselightmaptexture)
4916 // ordinary lightmapping (q1bsp, q3bsp)
4917 mode = SHADERMODE_LIGHTMAP;
4921 // ordinary vertex coloring (q3bsp)
4922 mode = SHADERMODE_VERTEXCOLOR;
4924 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4925 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4927 switch(vid.renderpath)
4929 case RENDERPATH_GL20:
4930 if (gl_mesh_separatearrays.integer)
4932 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
4933 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
4934 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
4935 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
4936 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
4937 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
4938 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
4939 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
4943 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
4944 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
4946 R_SetupShader_SetPermutationGLSL(mode, permutation);
4947 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
4948 if (mode == SHADERMODE_LIGHTSOURCE)
4950 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
4951 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
4952 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
4953 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
4954 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
4955 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
4957 // additive passes are only darkened by fog, not tinted
4958 if (r_glsl_permutation->loc_FogColor >= 0)
4959 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
4960 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
4964 if (mode == SHADERMODE_FLATCOLOR)
4966 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
4968 else if (mode == SHADERMODE_LIGHTDIRECTION)
4970 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);
4971 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
4972 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
4973 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);
4974 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
4975 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
4976 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
4980 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
4981 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
4982 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
4983 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
4984 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
4986 // additive passes are only darkened by fog, not tinted
4987 if (r_glsl_permutation->loc_FogColor >= 0)
4989 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
4990 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
4992 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
4994 if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
4995 if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
4996 if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
4997 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
4998 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
4999 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5000 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5001 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5003 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5004 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5005 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5006 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5007 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5009 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5010 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5011 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5012 if (r_glsl_permutation->loc_Color_Pants >= 0)
5014 if (rsurface.texture->pantstexture)
5015 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5017 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5019 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5021 if (rsurface.texture->shirttexture)
5022 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5024 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5026 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4fARB(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5027 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5028 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5029 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5030 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5031 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5032 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5034 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5035 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5036 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5037 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5038 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5039 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5040 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5041 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5042 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5043 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5044 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5045 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5046 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5047 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5048 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5049 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5050 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5051 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_white );
5052 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_blanknormalmap );
5053 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5054 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION , r_texture_white );
5055 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION , r_texture_white );
5056 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5057 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5058 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5059 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5060 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5062 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5063 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5064 if (rsurface.rtlight)
5066 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5067 if (r_shadow_usingshadowmapcube)
5068 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5069 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5074 case RENDERPATH_CGGL:
5076 if (gl_mesh_separatearrays.integer)
5078 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5079 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5080 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5081 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5082 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5083 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5084 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5085 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5089 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5090 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5092 R_SetupShader_SetPermutationCG(mode, permutation);
5093 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5094 if (mode == SHADERMODE_LIGHTSOURCE)
5096 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5097 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5101 if (mode == SHADERMODE_LIGHTDIRECTION)
5103 if (r_cg_permutation->vp_LightDir) cgGLSetParameter3f(r_cg_permutation->vp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5106 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5107 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5108 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5109 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5110 if (r_cg_permutation->vp_FogPlane) cgGLSetParameter4f(r_cg_permutation->vp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5113 if (mode == SHADERMODE_LIGHTSOURCE)
5115 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5116 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5117 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);CHECKCGERROR
5118 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);CHECKCGERROR
5119 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);CHECKCGERROR
5121 // additive passes are only darkened by fog, not tinted
5122 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5123 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5127 if (mode == SHADERMODE_FLATCOLOR)
5129 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);CHECKCGERROR
5131 else if (mode == SHADERMODE_LIGHTDIRECTION)
5133 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);CHECKCGERROR
5134 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);CHECKCGERROR
5135 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5136 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5137 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5138 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);CHECKCGERROR
5139 if (r_cg_permutation->fp_LightDir) cgGLSetParameter3f(r_cg_permutation->fp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5143 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);CHECKCGERROR
5144 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);CHECKCGERROR
5145 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5146 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5147 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5149 // additive passes are only darkened by fog, not tinted
5150 if (r_cg_permutation->fp_FogColor)
5152 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5153 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5155 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5158 if (r_cg_permutation->fp_DistortScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);CHECKCGERROR
5159 if (r_cg_permutation->fp_ScreenScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);CHECKCGERROR
5160 if (r_cg_permutation->fp_ScreenCenterRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);CHECKCGERROR
5161 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5162 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5163 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5164 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5165 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5167 if (r_cg_permutation->fp_ShadowMap_TextureScale) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5168 if (r_cg_permutation->fp_ShadowMap_Parameters) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5169 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5170 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5171 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5172 if (r_cg_permutation->fp_Color_Pants)
5174 if (rsurface.texture->pantstexture)
5175 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5177 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5180 if (r_cg_permutation->fp_Color_Shirt)
5182 if (rsurface.texture->shirttexture)
5183 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5185 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5188 if (r_cg_permutation->fp_FogPlane) cgGLSetParameter4f(r_cg_permutation->fp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5189 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5190 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5191 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5192 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5193 if (r_cg_permutation->fp_ScreenToDepth) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5194 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5196 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
5197 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
5198 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
5199 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
5200 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
5201 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
5202 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
5203 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
5204 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
5205 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
5206 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
5207 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
5208 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
5209 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
5210 if (r_cg_permutation->fp_Texture_ReflectCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectCube , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);CHECKCGERROR
5211 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
5212 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
5213 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , r_texture_white );CHECKCGERROR
5214 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , r_texture_blanknormalmap );CHECKCGERROR
5215 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5216 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , r_texture_white );CHECKCGERROR
5217 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , r_texture_white );CHECKCGERROR
5218 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5219 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5220 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
5221 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
5222 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5224 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5225 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5226 if (rsurface.rtlight)
5228 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5229 if (r_shadow_usingshadowmapcube)
5230 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5231 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5238 case RENDERPATH_GL13:
5239 case RENDERPATH_GL11:
5244 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5246 // select a permutation of the lighting shader appropriate to this
5247 // combination of texture, entity, light source, and fogging, only use the
5248 // minimum features necessary to avoid wasting rendering time in the
5249 // fragment shader on features that are not being used
5250 unsigned int permutation = 0;
5251 unsigned int mode = 0;
5252 const float *lightcolorbase = rtlight->currentcolor;
5253 float ambientscale = rtlight->ambientscale;
5254 float diffusescale = rtlight->diffusescale;
5255 float specularscale = rtlight->specularscale;
5256 // this is the location of the light in view space
5257 vec3_t viewlightorigin;
5258 // this transforms from view space (camera) to light space (cubemap)
5259 matrix4x4_t viewtolight;
5260 matrix4x4_t lighttoview;
5261 float viewtolight16f[16];
5262 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5264 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5265 if (rtlight->currentcubemap != r_texture_whitecube)
5266 permutation |= SHADERPERMUTATION_CUBEFILTER;
5267 if (diffusescale > 0)
5268 permutation |= SHADERPERMUTATION_DIFFUSE;
5269 if (specularscale > 0)
5271 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5272 if (r_shadow_glossexact.integer)
5273 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5275 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5277 if (r_shadow_usingshadowmaprect)
5278 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5279 if (r_shadow_usingshadowmap2d)
5280 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5281 if (r_shadow_usingshadowmapcube)
5282 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5283 else if(r_shadow_shadowmapvsdct)
5284 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5286 if (r_shadow_shadowmapsampler)
5287 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5288 if (r_shadow_shadowmappcf > 1)
5289 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5290 else if (r_shadow_shadowmappcf)
5291 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5293 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5294 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5295 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5296 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5297 switch(vid.renderpath)
5299 case RENDERPATH_GL20:
5300 R_SetupShader_SetPermutationGLSL(mode, permutation);
5301 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5302 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
5303 if (r_glsl_permutation->loc_DeferredColor_Ambient >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
5304 if (r_glsl_permutation->loc_DeferredColor_Diffuse >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
5305 if (r_glsl_permutation->loc_DeferredColor_Specular >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Specular , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5306 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB( r_glsl_permutation->loc_ShadowMap_TextureScale , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5307 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB( r_glsl_permutation->loc_ShadowMap_Parameters , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5308 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB( r_glsl_permutation->loc_SpecularPower , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5309 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB( r_glsl_permutation->loc_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5310 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5312 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5313 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5314 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5315 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5316 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
5317 if (r_shadow_usingshadowmapcube)
5318 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5319 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
5320 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5322 case RENDERPATH_CGGL:
5324 R_SetupShader_SetPermutationCG(mode, permutation);
5325 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
5326 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
5327 if (r_cg_permutation->fp_DeferredColor_Ambient ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);CHECKCGERROR
5328 if (r_cg_permutation->fp_DeferredColor_Diffuse ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);CHECKCGERROR
5329 if (r_cg_permutation->fp_DeferredColor_Specular ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);CHECKCGERROR
5330 if (r_cg_permutation->fp_ShadowMap_TextureScale ) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5331 if (r_cg_permutation->fp_ShadowMap_Parameters ) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5332 if (r_cg_permutation->fp_SpecularPower ) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5333 if (r_cg_permutation->fp_ScreenToDepth ) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5334 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5336 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5337 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5338 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5339 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5340 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5341 if (r_shadow_usingshadowmapcube)
5342 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5343 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5344 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5347 case RENDERPATH_GL13:
5348 case RENDERPATH_GL11:
5353 #define SKINFRAME_HASH 1024
5357 int loadsequence; // incremented each level change
5358 memexpandablearray_t array;
5359 skinframe_t *hash[SKINFRAME_HASH];
5362 r_skinframe_t r_skinframe;
5364 void R_SkinFrame_PrepareForPurge(void)
5366 r_skinframe.loadsequence++;
5367 // wrap it without hitting zero
5368 if (r_skinframe.loadsequence >= 200)
5369 r_skinframe.loadsequence = 1;
5372 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5376 // mark the skinframe as used for the purging code
5377 skinframe->loadsequence = r_skinframe.loadsequence;
5380 void R_SkinFrame_Purge(void)
5384 for (i = 0;i < SKINFRAME_HASH;i++)
5386 for (s = r_skinframe.hash[i];s;s = s->next)
5388 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5390 if (s->merged == s->base)
5392 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5393 R_PurgeTexture(s->stain );s->stain = NULL;
5394 R_PurgeTexture(s->merged);s->merged = NULL;
5395 R_PurgeTexture(s->base );s->base = NULL;
5396 R_PurgeTexture(s->pants );s->pants = NULL;
5397 R_PurgeTexture(s->shirt );s->shirt = NULL;
5398 R_PurgeTexture(s->nmap );s->nmap = NULL;
5399 R_PurgeTexture(s->gloss );s->gloss = NULL;
5400 R_PurgeTexture(s->glow );s->glow = NULL;
5401 R_PurgeTexture(s->fog );s->fog = NULL;
5402 R_PurgeTexture(s->reflect);s->reflect = NULL;
5403 s->loadsequence = 0;
5409 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5411 char basename[MAX_QPATH];
5413 Image_StripImageExtension(name, basename, sizeof(basename));
5415 if( last == NULL ) {
5417 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5418 item = r_skinframe.hash[hashindex];
5423 // linearly search through the hash bucket
5424 for( ; item ; item = item->next ) {
5425 if( !strcmp( item->basename, basename ) ) {
5432 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5436 char basename[MAX_QPATH];
5438 Image_StripImageExtension(name, basename, sizeof(basename));
5440 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5441 for (item = r_skinframe.hash[hashindex];item;item = item->next)
5442 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5446 rtexture_t *dyntexture;
5447 // check whether its a dynamic texture
5448 dyntexture = CL_GetDynTexture( basename );
5449 if (!add && !dyntexture)
5451 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5452 memset(item, 0, sizeof(*item));
5453 strlcpy(item->basename, basename, sizeof(item->basename));
5454 item->base = dyntexture; // either NULL or dyntexture handle
5455 item->textureflags = textureflags;
5456 item->comparewidth = comparewidth;
5457 item->compareheight = compareheight;
5458 item->comparecrc = comparecrc;
5459 item->next = r_skinframe.hash[hashindex];
5460 r_skinframe.hash[hashindex] = item;
5462 else if( item->base == NULL )
5464 rtexture_t *dyntexture;
5465 // check whether its a dynamic texture
5466 // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
5467 dyntexture = CL_GetDynTexture( basename );
5468 item->base = dyntexture; // either NULL or dyntexture handle
5471 R_SkinFrame_MarkUsed(item);
5475 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5477 unsigned long long avgcolor[5], wsum; \
5485 for(pix = 0; pix < cnt; ++pix) \
5488 for(comp = 0; comp < 3; ++comp) \
5490 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5493 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5495 for(comp = 0; comp < 3; ++comp) \
5496 avgcolor[comp] += getpixel * w; \
5499 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5500 avgcolor[4] += getpixel; \
5502 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
5504 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
5505 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
5506 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
5507 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
5510 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
5513 unsigned char *pixels;
5514 unsigned char *bumppixels;
5515 unsigned char *basepixels = NULL;
5516 int basepixels_width = 0;
5517 int basepixels_height = 0;
5518 skinframe_t *skinframe;
5519 rtexture_t *ddsbase = NULL;
5520 qboolean ddshasalpha = false;
5521 float ddsavgcolor[4];
5522 char basename[MAX_QPATH];
5524 if (cls.state == ca_dedicated)
5527 // return an existing skinframe if already loaded
5528 // if loading of the first image fails, don't make a new skinframe as it
5529 // would cause all future lookups of this to be missing
5530 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
5531 if (skinframe && skinframe->base)
5534 Image_StripImageExtension(name, basename, sizeof(basename));
5536 // check for DDS texture file first
5537 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor)))
5539 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer);
5540 if (basepixels == NULL)
5544 if (developer_loading.integer)
5545 Con_Printf("loading skin \"%s\"\n", name);
5547 // we've got some pixels to store, so really allocate this new texture now
5549 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
5550 skinframe->stain = NULL;
5551 skinframe->merged = NULL;
5552 skinframe->base = NULL;
5553 skinframe->pants = NULL;
5554 skinframe->shirt = NULL;
5555 skinframe->nmap = NULL;
5556 skinframe->gloss = NULL;
5557 skinframe->glow = NULL;
5558 skinframe->fog = NULL;
5559 skinframe->reflect = NULL;
5560 skinframe->hasalpha = false;
5564 skinframe->base = ddsbase;
5565 skinframe->hasalpha = ddshasalpha;
5566 VectorCopy(ddsavgcolor, skinframe->avgcolor);
5567 if (r_loadfog && skinframe->hasalpha)
5568 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL);
5569 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5573 basepixels_width = image_width;
5574 basepixels_height = image_height;
5575 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5576 if (textureflags & TEXF_ALPHA)
5578 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
5580 if (basepixels[j] < 255)
5582 skinframe->hasalpha = true;
5586 if (r_loadfog && skinframe->hasalpha)
5588 // has transparent pixels
5589 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5590 for (j = 0;j < image_width * image_height * 4;j += 4)
5595 pixels[j+3] = basepixels[j+3];
5597 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5601 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
5602 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5603 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
5604 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true);
5605 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
5606 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true);
5611 if (r_loadnormalmap)
5612 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL);
5613 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL);
5615 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL);
5616 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL);
5617 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL);
5618 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL);
5621 // _norm is the name used by tenebrae and has been adopted as standard
5622 if (r_loadnormalmap && skinframe->nmap == NULL)
5624 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false)) != NULL)
5626 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5630 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false)) != NULL)
5632 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5633 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
5634 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5636 Mem_Free(bumppixels);
5638 else if (r_shadow_bumpscale_basetexture.value > 0)
5640 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
5641 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
5642 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5645 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
5646 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true);
5649 // _luma is supported only for tenebrae compatibility
5650 // _glow is the preferred name
5651 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer))))
5653 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5654 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
5655 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true);
5656 Mem_Free(pixels);pixels = NULL;
5659 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5661 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5662 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
5663 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true);
5668 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5670 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5671 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
5672 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true);
5677 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5679 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5680 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
5681 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true);
5686 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5688 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5689 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
5690 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true);
5696 Mem_Free(basepixels);
5701 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
5702 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
5705 unsigned char *temp1, *temp2;
5706 skinframe_t *skinframe;
5708 if (cls.state == ca_dedicated)
5711 // if already loaded just return it, otherwise make a new skinframe
5712 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
5713 if (skinframe && skinframe->base)
5716 skinframe->stain = NULL;
5717 skinframe->merged = NULL;
5718 skinframe->base = NULL;
5719 skinframe->pants = NULL;
5720 skinframe->shirt = NULL;
5721 skinframe->nmap = NULL;
5722 skinframe->gloss = NULL;
5723 skinframe->glow = NULL;
5724 skinframe->fog = NULL;
5725 skinframe->reflect = NULL;
5726 skinframe->hasalpha = false;
5728 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5732 if (developer_loading.integer)
5733 Con_Printf("loading 32bit skin \"%s\"\n", name);
5735 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
5737 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5738 temp2 = temp1 + width * height * 4;
5739 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5740 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
5743 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
5744 if (textureflags & TEXF_ALPHA)
5746 for (i = 3;i < width * height * 4;i += 4)
5748 if (skindata[i] < 255)
5750 skinframe->hasalpha = true;
5754 if (r_loadfog && skinframe->hasalpha)
5756 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
5757 memcpy(fogpixels, skindata, width * height * 4);
5758 for (i = 0;i < width * height * 4;i += 4)
5759 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
5760 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
5761 Mem_Free(fogpixels);
5765 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
5766 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5771 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
5775 skinframe_t *skinframe;
5777 if (cls.state == ca_dedicated)
5780 // if already loaded just return it, otherwise make a new skinframe
5781 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5782 if (skinframe && skinframe->base)
5785 skinframe->stain = NULL;
5786 skinframe->merged = NULL;
5787 skinframe->base = NULL;
5788 skinframe->pants = NULL;
5789 skinframe->shirt = NULL;
5790 skinframe->nmap = NULL;
5791 skinframe->gloss = NULL;
5792 skinframe->glow = NULL;
5793 skinframe->fog = NULL;
5794 skinframe->reflect = NULL;
5795 skinframe->hasalpha = false;
5797 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5801 if (developer_loading.integer)
5802 Con_Printf("loading quake skin \"%s\"\n", name);
5804 // we actually don't upload anything until the first use, because mdl skins frequently go unused, and are almost never used in both modes (colormapped and non-colormapped)
5805 skinframe->qpixels = Mem_Alloc(r_main_mempool, width*height);
5806 memcpy(skinframe->qpixels, skindata, width*height);
5807 skinframe->qwidth = width;
5808 skinframe->qheight = height;
5811 for (i = 0;i < width * height;i++)
5812 featuresmask |= palette_featureflags[skindata[i]];
5814 skinframe->hasalpha = false;
5815 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
5816 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
5817 skinframe->qgeneratemerged = true;
5818 skinframe->qgeneratebase = skinframe->qhascolormapping;
5819 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
5821 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
5822 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5827 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
5831 unsigned char *skindata;
5833 if (!skinframe->qpixels)
5836 if (!skinframe->qhascolormapping)
5837 colormapped = false;
5841 if (!skinframe->qgeneratebase)
5846 if (!skinframe->qgeneratemerged)
5850 width = skinframe->qwidth;
5851 height = skinframe->qheight;
5852 skindata = skinframe->qpixels;
5854 if (skinframe->qgeneratenmap)
5856 unsigned char *temp1, *temp2;
5857 skinframe->qgeneratenmap = false;
5858 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5859 temp2 = temp1 + width * height * 4;
5860 // use either a custom palette or the quake palette
5861 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
5862 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5863 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
5867 if (skinframe->qgenerateglow)
5869 skinframe->qgenerateglow = false;
5870 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_onlyfullbrights); // glow
5875 skinframe->qgeneratebase = false;
5876 skinframe->base = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
5877 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_pantsaswhite);
5878 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_shirtaswhite);
5882 skinframe->qgeneratemerged = false;
5883 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
5886 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
5888 Mem_Free(skinframe->qpixels);
5889 skinframe->qpixels = NULL;
5893 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
5896 skinframe_t *skinframe;
5898 if (cls.state == ca_dedicated)
5901 // if already loaded just return it, otherwise make a new skinframe
5902 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5903 if (skinframe && skinframe->base)
5906 skinframe->stain = NULL;
5907 skinframe->merged = NULL;
5908 skinframe->base = NULL;
5909 skinframe->pants = NULL;
5910 skinframe->shirt = NULL;
5911 skinframe->nmap = NULL;
5912 skinframe->gloss = NULL;
5913 skinframe->glow = NULL;
5914 skinframe->fog = NULL;
5915 skinframe->reflect = NULL;
5916 skinframe->hasalpha = false;
5918 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5922 if (developer_loading.integer)
5923 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
5925 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette);
5926 if (textureflags & TEXF_ALPHA)
5928 for (i = 0;i < width * height;i++)
5930 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
5932 skinframe->hasalpha = true;
5936 if (r_loadfog && skinframe->hasalpha)
5937 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, alphapalette);
5940 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
5941 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5946 skinframe_t *R_SkinFrame_LoadMissing(void)
5948 skinframe_t *skinframe;
5950 if (cls.state == ca_dedicated)
5953 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
5954 skinframe->stain = NULL;
5955 skinframe->merged = NULL;
5956 skinframe->base = NULL;
5957 skinframe->pants = NULL;
5958 skinframe->shirt = NULL;
5959 skinframe->nmap = NULL;
5960 skinframe->gloss = NULL;
5961 skinframe->glow = NULL;
5962 skinframe->fog = NULL;
5963 skinframe->reflect = NULL;
5964 skinframe->hasalpha = false;
5966 skinframe->avgcolor[0] = rand() / RAND_MAX;
5967 skinframe->avgcolor[1] = rand() / RAND_MAX;
5968 skinframe->avgcolor[2] = rand() / RAND_MAX;
5969 skinframe->avgcolor[3] = 1;
5974 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
5975 typedef struct suffixinfo_s
5978 qboolean flipx, flipy, flipdiagonal;
5981 static suffixinfo_t suffix[3][6] =
5984 {"px", false, false, false},
5985 {"nx", false, false, false},
5986 {"py", false, false, false},
5987 {"ny", false, false, false},
5988 {"pz", false, false, false},
5989 {"nz", false, false, false}
5992 {"posx", false, false, false},
5993 {"negx", false, false, false},
5994 {"posy", false, false, false},
5995 {"negy", false, false, false},
5996 {"posz", false, false, false},
5997 {"negz", false, false, false}
6000 {"rt", true, false, true},
6001 {"lf", false, true, true},
6002 {"ft", true, true, false},
6003 {"bk", false, false, false},
6004 {"up", true, false, true},
6005 {"dn", true, false, true}
6009 static int componentorder[4] = {0, 1, 2, 3};
6011 rtexture_t *R_LoadCubemap(const char *basename)
6013 int i, j, cubemapsize;
6014 unsigned char *cubemappixels, *image_buffer;
6015 rtexture_t *cubemaptexture;
6017 // must start 0 so the first loadimagepixels has no requested width/height
6019 cubemappixels = NULL;
6020 cubemaptexture = NULL;
6021 // keep trying different suffix groups (posx, px, rt) until one loads
6022 for (j = 0;j < 3 && !cubemappixels;j++)
6024 // load the 6 images in the suffix group
6025 for (i = 0;i < 6;i++)
6027 // generate an image name based on the base and and suffix
6028 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6030 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer)))
6032 // an image loaded, make sure width and height are equal
6033 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6035 // if this is the first image to load successfully, allocate the cubemap memory
6036 if (!cubemappixels && image_width >= 1)
6038 cubemapsize = image_width;
6039 // note this clears to black, so unavailable sides are black
6040 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6042 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6044 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
6047 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6049 Mem_Free(image_buffer);
6053 // if a cubemap loaded, upload it
6056 if (developer_loading.integer)
6057 Con_Printf("loading cubemap \"%s\"\n", basename);
6059 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR, NULL);
6060 Mem_Free(cubemappixels);
6064 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6065 if (developer_loading.integer)
6067 Con_Printf("(tried tried images ");
6068 for (j = 0;j < 3;j++)
6069 for (i = 0;i < 6;i++)
6070 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6071 Con_Print(" and was unable to find any of them).\n");
6074 return cubemaptexture;
6077 rtexture_t *R_GetCubemap(const char *basename)
6080 for (i = 0;i < r_texture_numcubemaps;i++)
6081 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6082 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6083 if (i >= MAX_CUBEMAPS)
6084 return r_texture_whitecube;
6085 r_texture_numcubemaps++;
6086 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6087 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6088 return r_texture_cubemaps[i].texture;
6091 void R_FreeCubemaps(void)
6094 for (i = 0;i < r_texture_numcubemaps;i++)
6096 if (developer_loading.integer)
6097 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6098 if (r_texture_cubemaps[i].texture)
6099 R_FreeTexture(r_texture_cubemaps[i].texture);
6101 r_texture_numcubemaps = 0;
6104 void R_Main_FreeViewCache(void)
6106 if (r_refdef.viewcache.entityvisible)
6107 Mem_Free(r_refdef.viewcache.entityvisible);
6108 if (r_refdef.viewcache.world_pvsbits)
6109 Mem_Free(r_refdef.viewcache.world_pvsbits);
6110 if (r_refdef.viewcache.world_leafvisible)
6111 Mem_Free(r_refdef.viewcache.world_leafvisible);
6112 if (r_refdef.viewcache.world_surfacevisible)
6113 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6114 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6117 void R_Main_ResizeViewCache(void)
6119 int numentities = r_refdef.scene.numentities;
6120 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6121 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6122 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6123 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6124 if (r_refdef.viewcache.maxentities < numentities)
6126 r_refdef.viewcache.maxentities = numentities;
6127 if (r_refdef.viewcache.entityvisible)
6128 Mem_Free(r_refdef.viewcache.entityvisible);
6129 r_refdef.viewcache.entityvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6131 if (r_refdef.viewcache.world_numclusters != numclusters)
6133 r_refdef.viewcache.world_numclusters = numclusters;
6134 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6135 if (r_refdef.viewcache.world_pvsbits)
6136 Mem_Free(r_refdef.viewcache.world_pvsbits);
6137 r_refdef.viewcache.world_pvsbits = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6139 if (r_refdef.viewcache.world_numleafs != numleafs)
6141 r_refdef.viewcache.world_numleafs = numleafs;
6142 if (r_refdef.viewcache.world_leafvisible)
6143 Mem_Free(r_refdef.viewcache.world_leafvisible);
6144 r_refdef.viewcache.world_leafvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6146 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6148 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6149 if (r_refdef.viewcache.world_surfacevisible)
6150 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6151 r_refdef.viewcache.world_surfacevisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6155 extern rtexture_t *loadingscreentexture;
6156 void gl_main_start(void)
6158 loadingscreentexture = NULL;
6159 r_texture_blanknormalmap = NULL;
6160 r_texture_white = NULL;
6161 r_texture_grey128 = NULL;
6162 r_texture_black = NULL;
6163 r_texture_whitecube = NULL;
6164 r_texture_normalizationcube = NULL;
6165 r_texture_fogattenuation = NULL;
6166 r_texture_fogheighttexture = NULL;
6167 r_texture_gammaramps = NULL;
6168 r_texture_numcubemaps = 0;
6170 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6171 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6173 switch(vid.renderpath)
6175 case RENDERPATH_GL20:
6176 case RENDERPATH_CGGL:
6177 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6178 Cvar_SetValueQuick(&gl_combine, 1);
6179 Cvar_SetValueQuick(&r_glsl, 1);
6180 r_loadnormalmap = true;
6184 case RENDERPATH_GL13:
6185 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6186 Cvar_SetValueQuick(&gl_combine, 1);
6187 Cvar_SetValueQuick(&r_glsl, 0);
6188 r_loadnormalmap = false;
6189 r_loadgloss = false;
6192 case RENDERPATH_GL11:
6193 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6194 Cvar_SetValueQuick(&gl_combine, 0);
6195 Cvar_SetValueQuick(&r_glsl, 0);
6196 r_loadnormalmap = false;
6197 r_loadgloss = false;
6203 R_FrameData_Reset();
6207 memset(r_queries, 0, sizeof(r_queries));
6209 r_qwskincache = NULL;
6210 r_qwskincache_size = 0;
6212 // set up r_skinframe loading system for textures
6213 memset(&r_skinframe, 0, sizeof(r_skinframe));
6214 r_skinframe.loadsequence = 1;
6215 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6217 r_main_texturepool = R_AllocTexturePool();
6218 R_BuildBlankTextures();
6220 if (vid.support.arb_texture_cube_map)
6223 R_BuildNormalizationCube();
6225 r_texture_fogattenuation = NULL;
6226 r_texture_fogheighttexture = NULL;
6227 r_texture_gammaramps = NULL;
6228 //r_texture_fogintensity = NULL;
6229 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6230 memset(&r_waterstate, 0, sizeof(r_waterstate));
6231 r_glsl_permutation = NULL;
6232 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6233 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6234 glslshaderstring = NULL;
6236 r_cg_permutation = NULL;
6237 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6238 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6239 cgshaderstring = NULL;
6241 memset(&r_svbsp, 0, sizeof (r_svbsp));
6243 r_refdef.fogmasktable_density = 0;
6246 void gl_main_shutdown(void)
6249 R_FrameData_Reset();
6251 R_Main_FreeViewCache();
6254 qglDeleteQueriesARB(r_maxqueries, r_queries);
6258 memset(r_queries, 0, sizeof(r_queries));
6260 r_qwskincache = NULL;
6261 r_qwskincache_size = 0;
6263 // clear out the r_skinframe state
6264 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6265 memset(&r_skinframe, 0, sizeof(r_skinframe));
6268 Mem_Free(r_svbsp.nodes);
6269 memset(&r_svbsp, 0, sizeof (r_svbsp));
6270 R_FreeTexturePool(&r_main_texturepool);
6271 loadingscreentexture = NULL;
6272 r_texture_blanknormalmap = NULL;
6273 r_texture_white = NULL;
6274 r_texture_grey128 = NULL;
6275 r_texture_black = NULL;
6276 r_texture_whitecube = NULL;
6277 r_texture_normalizationcube = NULL;
6278 r_texture_fogattenuation = NULL;
6279 r_texture_fogheighttexture = NULL;
6280 r_texture_gammaramps = NULL;
6281 r_texture_numcubemaps = 0;
6282 //r_texture_fogintensity = NULL;
6283 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6284 memset(&r_waterstate, 0, sizeof(r_waterstate));
6285 r_glsl_permutation = NULL;
6286 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6287 glslshaderstring = NULL;
6289 r_cg_permutation = NULL;
6290 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6291 cgshaderstring = NULL;
6296 extern void CL_ParseEntityLump(char *entitystring);
6297 void gl_main_newmap(void)
6299 // FIXME: move this code to client
6301 char *entities, entname[MAX_QPATH];
6303 Mem_Free(r_qwskincache);
6304 r_qwskincache = NULL;
6305 r_qwskincache_size = 0;
6308 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
6309 l = (int)strlen(entname) - 4;
6310 if (l >= 0 && !strcmp(entname + l, ".bsp"))
6312 memcpy(entname + l, ".ent", 5);
6313 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6315 CL_ParseEntityLump(entities);
6320 if (cl.worldmodel->brush.entities)
6321 CL_ParseEntityLump(cl.worldmodel->brush.entities);
6323 R_Main_FreeViewCache();
6325 R_FrameData_Reset();
6328 void GL_Main_Init(void)
6330 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6332 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6333 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6334 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6335 if (gamemode == GAME_NEHAHRA)
6337 Cvar_RegisterVariable (&gl_fogenable);
6338 Cvar_RegisterVariable (&gl_fogdensity);
6339 Cvar_RegisterVariable (&gl_fogred);
6340 Cvar_RegisterVariable (&gl_foggreen);
6341 Cvar_RegisterVariable (&gl_fogblue);
6342 Cvar_RegisterVariable (&gl_fogstart);
6343 Cvar_RegisterVariable (&gl_fogend);
6344 Cvar_RegisterVariable (&gl_skyclip);
6346 Cvar_RegisterVariable(&r_motionblur);
6347 Cvar_RegisterVariable(&r_motionblur_maxblur);
6348 Cvar_RegisterVariable(&r_motionblur_bmin);
6349 Cvar_RegisterVariable(&r_motionblur_vmin);
6350 Cvar_RegisterVariable(&r_motionblur_vmax);
6351 Cvar_RegisterVariable(&r_motionblur_vcoeff);
6352 Cvar_RegisterVariable(&r_motionblur_randomize);
6353 Cvar_RegisterVariable(&r_damageblur);
6354 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6355 Cvar_RegisterVariable(&r_equalize_entities_minambient);
6356 Cvar_RegisterVariable(&r_equalize_entities_by);
6357 Cvar_RegisterVariable(&r_equalize_entities_to);
6358 Cvar_RegisterVariable(&r_depthfirst);
6359 Cvar_RegisterVariable(&r_useinfinitefarclip);
6360 Cvar_RegisterVariable(&r_farclip_base);
6361 Cvar_RegisterVariable(&r_farclip_world);
6362 Cvar_RegisterVariable(&r_nearclip);
6363 Cvar_RegisterVariable(&r_showbboxes);
6364 Cvar_RegisterVariable(&r_showsurfaces);
6365 Cvar_RegisterVariable(&r_showtris);
6366 Cvar_RegisterVariable(&r_shownormals);
6367 Cvar_RegisterVariable(&r_showlighting);
6368 Cvar_RegisterVariable(&r_showshadowvolumes);
6369 Cvar_RegisterVariable(&r_showcollisionbrushes);
6370 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6371 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6372 Cvar_RegisterVariable(&r_showdisabledepthtest);
6373 Cvar_RegisterVariable(&r_drawportals);
6374 Cvar_RegisterVariable(&r_drawentities);
6375 Cvar_RegisterVariable(&r_drawworld);
6376 Cvar_RegisterVariable(&r_cullentities_trace);
6377 Cvar_RegisterVariable(&r_cullentities_trace_samples);
6378 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6379 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6380 Cvar_RegisterVariable(&r_cullentities_trace_delay);
6381 Cvar_RegisterVariable(&r_drawviewmodel);
6382 Cvar_RegisterVariable(&r_drawexteriormodel);
6383 Cvar_RegisterVariable(&r_speeds);
6384 Cvar_RegisterVariable(&r_fullbrights);
6385 Cvar_RegisterVariable(&r_wateralpha);
6386 Cvar_RegisterVariable(&r_dynamic);
6387 Cvar_RegisterVariable(&r_fullbright);
6388 Cvar_RegisterVariable(&r_shadows);
6389 Cvar_RegisterVariable(&r_shadows_darken);
6390 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6391 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6392 Cvar_RegisterVariable(&r_shadows_throwdistance);
6393 Cvar_RegisterVariable(&r_shadows_throwdirection);
6394 Cvar_RegisterVariable(&r_shadows_focus);
6395 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6396 Cvar_RegisterVariable(&r_q1bsp_skymasking);
6397 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6398 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6399 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6400 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6401 Cvar_RegisterVariable(&r_fog_exp2);
6402 Cvar_RegisterVariable(&r_drawfog);
6403 Cvar_RegisterVariable(&r_transparentdepthmasking);
6404 Cvar_RegisterVariable(&r_texture_dds_load);
6405 Cvar_RegisterVariable(&r_texture_dds_save);
6406 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6407 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6408 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6409 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6410 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6411 Cvar_RegisterVariable(&r_textureunits);
6412 Cvar_RegisterVariable(&gl_combine);
6413 Cvar_RegisterVariable(&r_glsl);
6414 Cvar_RegisterVariable(&r_glsl_deluxemapping);
6415 Cvar_RegisterVariable(&r_glsl_offsetmapping);
6416 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6417 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6418 Cvar_RegisterVariable(&r_glsl_postprocess);
6419 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6420 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6421 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6422 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6423 Cvar_RegisterVariable(&r_water);
6424 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6425 Cvar_RegisterVariable(&r_water_clippingplanebias);
6426 Cvar_RegisterVariable(&r_water_refractdistort);
6427 Cvar_RegisterVariable(&r_water_reflectdistort);
6428 Cvar_RegisterVariable(&r_lerpsprites);
6429 Cvar_RegisterVariable(&r_lerpmodels);
6430 Cvar_RegisterVariable(&r_lerplightstyles);
6431 Cvar_RegisterVariable(&r_waterscroll);
6432 Cvar_RegisterVariable(&r_bloom);
6433 Cvar_RegisterVariable(&r_bloom_colorscale);
6434 Cvar_RegisterVariable(&r_bloom_brighten);
6435 Cvar_RegisterVariable(&r_bloom_blur);
6436 Cvar_RegisterVariable(&r_bloom_resolution);
6437 Cvar_RegisterVariable(&r_bloom_colorexponent);
6438 Cvar_RegisterVariable(&r_bloom_colorsubtract);
6439 Cvar_RegisterVariable(&r_hdr);
6440 Cvar_RegisterVariable(&r_hdr_scenebrightness);
6441 Cvar_RegisterVariable(&r_hdr_glowintensity);
6442 Cvar_RegisterVariable(&r_hdr_range);
6443 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6444 Cvar_RegisterVariable(&developer_texturelogging);
6445 Cvar_RegisterVariable(&gl_lightmaps);
6446 Cvar_RegisterVariable(&r_test);
6447 Cvar_RegisterVariable(&r_glsl_saturation);
6448 Cvar_RegisterVariable(&r_framedatasize);
6449 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
6450 Cvar_SetValue("r_fullbrights", 0);
6451 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
6453 Cvar_RegisterVariable(&r_track_sprites);
6454 Cvar_RegisterVariable(&r_track_sprites_flags);
6455 Cvar_RegisterVariable(&r_track_sprites_scalew);
6456 Cvar_RegisterVariable(&r_track_sprites_scaleh);
6457 Cvar_RegisterVariable(&r_overheadsprites_perspective);
6458 Cvar_RegisterVariable(&r_overheadsprites_pushback);
6461 extern void R_Textures_Init(void);
6462 extern void GL_Draw_Init(void);
6463 extern void GL_Main_Init(void);
6464 extern void R_Shadow_Init(void);
6465 extern void R_Sky_Init(void);
6466 extern void GL_Surf_Init(void);
6467 extern void R_Particles_Init(void);
6468 extern void R_Explosion_Init(void);
6469 extern void gl_backend_init(void);
6470 extern void Sbar_Init(void);
6471 extern void R_LightningBeams_Init(void);
6472 extern void Mod_RenderInit(void);
6473 extern void Font_Init(void);
6475 void Render_Init(void)
6488 R_LightningBeams_Init();
6497 extern char *ENGINE_EXTENSIONS;
6500 gl_renderer = (const char *)qglGetString(GL_RENDERER);
6501 gl_vendor = (const char *)qglGetString(GL_VENDOR);
6502 gl_version = (const char *)qglGetString(GL_VERSION);
6503 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
6507 if (!gl_platformextensions)
6508 gl_platformextensions = "";
6510 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
6511 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
6512 Con_Printf("GL_VERSION: %s\n", gl_version);
6513 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
6514 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
6516 VID_CheckExtensions();
6518 // LordHavoc: report supported extensions
6519 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
6521 // clear to black (loading plaque will be seen over this)
6523 qglClearColor(0,0,0,1);CHECKGLERROR
6524 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
6527 int R_CullBox(const vec3_t mins, const vec3_t maxs)
6531 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
6533 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
6536 p = r_refdef.view.frustum + i;
6541 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6545 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6549 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6553 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6557 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6561 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6565 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6569 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6577 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
6581 for (i = 0;i < numplanes;i++)
6588 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6592 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6596 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6600 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6604 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6608 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6612 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6616 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6624 //==================================================================================
6626 // LordHavoc: this stores temporary data used within the same frame
6628 qboolean r_framedata_failed;
6629 static size_t r_framedata_size;
6630 static size_t r_framedata_current;
6631 static void *r_framedata_base;
6633 void R_FrameData_Reset(void)
6635 if (r_framedata_base)
6636 Mem_Free(r_framedata_base);
6637 r_framedata_base = NULL;
6638 r_framedata_size = 0;
6639 r_framedata_current = 0;
6640 r_framedata_failed = false;
6643 void R_FrameData_NewFrame(void)
6646 if (r_framedata_failed)
6647 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
6648 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
6649 wantedsize = bound(65536, wantedsize, 128*1024*1024);
6650 if (r_framedata_size != wantedsize)
6652 r_framedata_size = wantedsize;
6653 if (r_framedata_base)
6654 Mem_Free(r_framedata_base);
6655 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
6657 r_framedata_current = 0;
6658 r_framedata_failed = false;
6661 void *R_FrameData_Alloc(size_t size)
6665 // align to 16 byte boundary
6666 size = (size + 15) & ~15;
6667 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
6668 r_framedata_current += size;
6671 if (r_framedata_current > r_framedata_size)
6672 r_framedata_failed = true;
6674 // return NULL on everything after a failure
6675 if (r_framedata_failed)
6681 void *R_FrameData_Store(size_t size, void *data)
6683 void *d = R_FrameData_Alloc(size);
6685 memcpy(d, data, size);
6689 //==================================================================================
6691 // LordHavoc: animcache originally written by Echon, rewritten since then
6694 * Animation cache prevents re-generating mesh data for an animated model
6695 * multiple times in one frame for lighting, shadowing, reflections, etc.
6698 void R_AnimCache_Free(void)
6702 void R_AnimCache_ClearCache(void)
6705 entity_render_t *ent;
6707 for (i = 0;i < r_refdef.scene.numentities;i++)
6709 ent = r_refdef.scene.entities[i];
6710 ent->animcache_vertex3f = NULL;
6711 ent->animcache_normal3f = NULL;
6712 ent->animcache_svector3f = NULL;
6713 ent->animcache_tvector3f = NULL;
6714 ent->animcache_vertexposition = NULL;
6715 ent->animcache_vertexmesh = NULL;
6716 ent->animcache_vertexpositionbuffer = NULL;
6717 ent->animcache_vertexmeshbuffer = NULL;
6721 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
6724 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
6725 ent->animcache_vertexmesh = R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
6726 if (!ent->animcache_vertexposition)
6727 ent->animcache_vertexposition = R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
6728 if (ent->animcache_vertexposition)
6730 for (i = 0;i < numvertices;i++)
6731 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
6732 // TODO: upload vertex buffer?
6734 if (ent->animcache_vertexmesh)
6736 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
6737 for (i = 0;i < numvertices;i++)
6738 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
6739 if (ent->animcache_svector3f)
6740 for (i = 0;i < numvertices;i++)
6741 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
6742 if (ent->animcache_tvector3f)
6743 for (i = 0;i < numvertices;i++)
6744 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
6745 if (ent->animcache_normal3f)
6746 for (i = 0;i < numvertices;i++)
6747 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
6748 // TODO: upload vertex buffer?
6752 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
6754 dp_model_t *model = ent->model;
6756 // see if it's already cached this frame
6757 if (ent->animcache_vertex3f)
6759 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
6760 if (wantnormals || wanttangents)
6762 if (ent->animcache_normal3f)
6763 wantnormals = false;
6764 if (ent->animcache_svector3f)
6765 wanttangents = false;
6766 if (wantnormals || wanttangents)
6768 numvertices = model->surfmesh.num_vertices;
6770 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6773 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6774 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6776 if (!r_framedata_failed)
6778 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
6779 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6786 // see if this ent is worth caching
6787 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
6789 // get some memory for this entity and generate mesh data
6790 numvertices = model->surfmesh.num_vertices;
6791 ent->animcache_vertex3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6793 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6796 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6797 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6799 if (!r_framedata_failed)
6801 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
6802 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6805 return !r_framedata_failed;
6808 void R_AnimCache_CacheVisibleEntities(void)
6811 qboolean wantnormals = true;
6812 qboolean wanttangents = !r_showsurfaces.integer;
6814 switch(vid.renderpath)
6816 case RENDERPATH_GL20:
6817 case RENDERPATH_CGGL:
6819 case RENDERPATH_GL13:
6820 case RENDERPATH_GL11:
6821 wanttangents = false;
6825 if (r_shownormals.integer)
6826 wanttangents = wantnormals = true;
6828 // TODO: thread this
6829 // NOTE: R_PrepareRTLights() also caches entities
6831 for (i = 0;i < r_refdef.scene.numentities;i++)
6832 if (r_refdef.viewcache.entityvisible[i])
6833 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
6836 //==================================================================================
6838 static void R_View_UpdateEntityLighting (void)
6841 entity_render_t *ent;
6842 vec3_t tempdiffusenormal, avg;
6843 vec_t f, fa, fd, fdd;
6844 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
6846 for (i = 0;i < r_refdef.scene.numentities;i++)
6848 ent = r_refdef.scene.entities[i];
6850 // skip unseen models
6851 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
6855 if (ent->model && ent->model->brush.num_leafs)
6857 // TODO: use modellight for r_ambient settings on world?
6858 VectorSet(ent->modellight_ambient, 0, 0, 0);
6859 VectorSet(ent->modellight_diffuse, 0, 0, 0);
6860 VectorSet(ent->modellight_lightdir, 0, 0, 1);
6864 // fetch the lighting from the worldmodel data
6865 VectorClear(ent->modellight_ambient);
6866 VectorClear(ent->modellight_diffuse);
6867 VectorClear(tempdiffusenormal);
6868 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6871 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
6872 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
6873 if(ent->flags & RENDER_EQUALIZE)
6875 // first fix up ambient lighting...
6876 if(r_equalize_entities_minambient.value > 0)
6878 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
6881 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
6882 if(fa < r_equalize_entities_minambient.value * fd)
6885 // fa'/fd' = minambient
6886 // fa'+0.25*fd' = fa+0.25*fd
6888 // fa' = fd' * minambient
6889 // fd'*(0.25+minambient) = fa+0.25*fd
6891 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
6892 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
6894 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
6895 f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
6896 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
6897 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
6902 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
6904 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
6905 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
6908 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
6909 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
6910 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
6916 VectorSet(ent->modellight_ambient, 1, 1, 1);
6918 // move the light direction into modelspace coordinates for lighting code
6919 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
6920 if(VectorLength2(ent->modellight_lightdir) == 0)
6921 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
6922 VectorNormalize(ent->modellight_lightdir);
6926 #define MAX_LINEOFSIGHTTRACES 64
6928 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
6931 vec3_t boxmins, boxmaxs;
6934 dp_model_t *model = r_refdef.scene.worldmodel;
6936 if (!model || !model->brush.TraceLineOfSight)
6939 // expand the box a little
6940 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
6941 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
6942 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
6943 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
6944 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
6945 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
6947 // return true if eye is inside enlarged box
6948 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
6952 VectorCopy(eye, start);
6953 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
6954 if (model->brush.TraceLineOfSight(model, start, end))
6957 // try various random positions
6958 for (i = 0;i < numsamples;i++)
6960 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
6961 if (model->brush.TraceLineOfSight(model, start, end))
6969 static void R_View_UpdateEntityVisible (void)
6974 entity_render_t *ent;
6976 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
6977 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
6978 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
6979 : RENDER_EXTERIORMODEL;
6980 if (!r_drawviewmodel.integer)
6981 renderimask |= RENDER_VIEWMODEL;
6982 if (!r_drawexteriormodel.integer)
6983 renderimask |= RENDER_EXTERIORMODEL;
6984 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
6986 // worldmodel can check visibility
6987 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
6988 for (i = 0;i < r_refdef.scene.numentities;i++)
6990 ent = r_refdef.scene.entities[i];
6991 if (!(ent->flags & renderimask))
6992 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
6993 if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
6994 r_refdef.viewcache.entityvisible[i] = true;
6996 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
6997 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
6999 for (i = 0;i < r_refdef.scene.numentities;i++)
7001 ent = r_refdef.scene.entities[i];
7002 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7004 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7006 continue; // temp entities do pvs only
7007 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7008 ent->last_trace_visibility = realtime;
7009 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7010 r_refdef.viewcache.entityvisible[i] = 0;
7017 // no worldmodel or it can't check visibility
7018 for (i = 0;i < r_refdef.scene.numentities;i++)
7020 ent = r_refdef.scene.entities[i];
7021 r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
7026 /// only used if skyrendermasked, and normally returns false
7027 int R_DrawBrushModelsSky (void)
7030 entity_render_t *ent;
7033 for (i = 0;i < r_refdef.scene.numentities;i++)
7035 if (!r_refdef.viewcache.entityvisible[i])
7037 ent = r_refdef.scene.entities[i];
7038 if (!ent->model || !ent->model->DrawSky)
7040 ent->model->DrawSky(ent);
7046 static void R_DrawNoModel(entity_render_t *ent);
7047 static void R_DrawModels(void)
7050 entity_render_t *ent;
7052 for (i = 0;i < r_refdef.scene.numentities;i++)
7054 if (!r_refdef.viewcache.entityvisible[i])
7056 ent = r_refdef.scene.entities[i];
7057 r_refdef.stats.entities++;
7058 if (ent->model && ent->model->Draw != NULL)
7059 ent->model->Draw(ent);
7065 static void R_DrawModelsDepth(void)
7068 entity_render_t *ent;
7070 for (i = 0;i < r_refdef.scene.numentities;i++)
7072 if (!r_refdef.viewcache.entityvisible[i])
7074 ent = r_refdef.scene.entities[i];
7075 if (ent->model && ent->model->DrawDepth != NULL)
7076 ent->model->DrawDepth(ent);
7080 static void R_DrawModelsDebug(void)
7083 entity_render_t *ent;
7085 for (i = 0;i < r_refdef.scene.numentities;i++)
7087 if (!r_refdef.viewcache.entityvisible[i])
7089 ent = r_refdef.scene.entities[i];
7090 if (ent->model && ent->model->DrawDebug != NULL)
7091 ent->model->DrawDebug(ent);
7095 static void R_DrawModelsAddWaterPlanes(void)
7098 entity_render_t *ent;
7100 for (i = 0;i < r_refdef.scene.numentities;i++)
7102 if (!r_refdef.viewcache.entityvisible[i])
7104 ent = r_refdef.scene.entities[i];
7105 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7106 ent->model->DrawAddWaterPlanes(ent);
7110 static void R_View_SetFrustum(void)
7113 double slopex, slopey;
7114 vec3_t forward, left, up, origin;
7116 // we can't trust r_refdef.view.forward and friends in reflected scenes
7117 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7120 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7121 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7122 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7123 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7124 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7125 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7126 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7127 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7128 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7129 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7130 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7131 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7135 zNear = r_refdef.nearclip;
7136 nudge = 1.0 - 1.0 / (1<<23);
7137 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7138 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7139 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7140 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7141 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7142 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7143 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7144 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7150 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7151 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7152 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7153 r_refdef.view.frustum[0].dist = m[15] - m[12];
7155 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7156 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7157 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7158 r_refdef.view.frustum[1].dist = m[15] + m[12];
7160 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7161 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7162 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7163 r_refdef.view.frustum[2].dist = m[15] - m[13];
7165 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7166 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7167 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7168 r_refdef.view.frustum[3].dist = m[15] + m[13];
7170 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7171 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7172 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7173 r_refdef.view.frustum[4].dist = m[15] - m[14];
7175 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7176 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7177 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7178 r_refdef.view.frustum[5].dist = m[15] + m[14];
7181 if (r_refdef.view.useperspective)
7183 slopex = 1.0 / r_refdef.view.frustum_x;
7184 slopey = 1.0 / r_refdef.view.frustum_y;
7185 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
7186 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
7187 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
7188 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
7189 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7191 // Leaving those out was a mistake, those were in the old code, and they
7192 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7193 // I couldn't reproduce it after adding those normalizations. --blub
7194 VectorNormalize(r_refdef.view.frustum[0].normal);
7195 VectorNormalize(r_refdef.view.frustum[1].normal);
7196 VectorNormalize(r_refdef.view.frustum[2].normal);
7197 VectorNormalize(r_refdef.view.frustum[3].normal);
7199 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7200 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * r_refdef.view.frustum_x, left, -1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
7201 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, 1024 * r_refdef.view.frustum_x, left, -1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
7202 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * r_refdef.view.frustum_x, left, 1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
7203 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, 1024 * r_refdef.view.frustum_x, left, 1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
7205 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7206 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7207 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7208 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7209 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7213 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7214 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7215 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7216 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7217 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7218 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7219 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7220 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7221 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7222 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7224 r_refdef.view.numfrustumplanes = 5;
7226 if (r_refdef.view.useclipplane)
7228 r_refdef.view.numfrustumplanes = 6;
7229 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7232 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7233 PlaneClassify(r_refdef.view.frustum + i);
7235 // LordHavoc: note to all quake engine coders, Quake had a special case
7236 // for 90 degrees which assumed a square view (wrong), so I removed it,
7237 // Quake2 has it disabled as well.
7239 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7240 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7241 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7242 //PlaneClassify(&frustum[0]);
7244 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7245 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7246 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7247 //PlaneClassify(&frustum[1]);
7249 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7250 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7251 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7252 //PlaneClassify(&frustum[2]);
7254 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7255 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7256 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7257 //PlaneClassify(&frustum[3]);
7260 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7261 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7262 //PlaneClassify(&frustum[4]);
7265 void R_View_Update(void)
7267 R_Main_ResizeViewCache();
7268 R_View_SetFrustum();
7269 R_View_WorldVisibility(r_refdef.view.useclipplane);
7270 R_View_UpdateEntityVisible();
7271 R_View_UpdateEntityLighting();
7274 void R_SetupView(qboolean allowwaterclippingplane)
7276 const float *customclipplane = NULL;
7278 if (r_refdef.view.useclipplane && allowwaterclippingplane)
7280 // LordHavoc: couldn't figure out how to make this approach the
7281 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7282 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7283 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7284 dist = r_refdef.view.clipplane.dist;
7285 plane[0] = r_refdef.view.clipplane.normal[0];
7286 plane[1] = r_refdef.view.clipplane.normal[1];
7287 plane[2] = r_refdef.view.clipplane.normal[2];
7289 customclipplane = plane;
7292 if (!r_refdef.view.useperspective)
7293 R_Viewport_InitOrtho(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, -r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip, customclipplane);
7294 else if (vid.stencil && r_useinfinitefarclip.integer)
7295 R_Viewport_InitPerspectiveInfinite(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, customclipplane);
7297 R_Viewport_InitPerspective(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip, customclipplane);
7298 R_SetViewport(&r_refdef.view.viewport);
7301 void R_EntityMatrix(const matrix4x4_t *matrix)
7303 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7305 gl_modelmatrixchanged = false;
7306 gl_modelmatrix = *matrix;
7307 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7308 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7309 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7310 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7312 switch(vid.renderpath)
7314 case RENDERPATH_GL20:
7315 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7316 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7317 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7319 case RENDERPATH_CGGL:
7322 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7323 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7324 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7327 case RENDERPATH_GL13:
7328 case RENDERPATH_GL11:
7329 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7335 void R_ResetViewRendering2D(void)
7337 r_viewport_t viewport;
7340 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7341 R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, 0, 0, 1, 1, -10, 100, NULL);
7342 R_SetViewport(&viewport);
7343 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7344 GL_Color(1, 1, 1, 1);
7345 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7346 GL_BlendFunc(GL_ONE, GL_ZERO);
7347 GL_AlphaTest(false);
7348 GL_ScissorTest(false);
7349 GL_DepthMask(false);
7350 GL_DepthRange(0, 1);
7351 GL_DepthTest(false);
7352 R_EntityMatrix(&identitymatrix);
7353 R_Mesh_ResetTextureState();
7354 GL_PolygonOffset(0, 0);
7355 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7356 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7357 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7358 qglStencilMask(~0);CHECKGLERROR
7359 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7360 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7361 GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7364 void R_ResetViewRendering3D(void)
7369 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7370 GL_Color(1, 1, 1, 1);
7371 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7372 GL_BlendFunc(GL_ONE, GL_ZERO);
7373 GL_AlphaTest(false);
7374 GL_ScissorTest(true);
7376 GL_DepthRange(0, 1);
7378 R_EntityMatrix(&identitymatrix);
7379 R_Mesh_ResetTextureState();
7380 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7381 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7382 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7383 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7384 qglStencilMask(~0);CHECKGLERROR
7385 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7386 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7387 GL_CullFace(r_refdef.view.cullface_back);
7392 R_RenderView_UpdateViewVectors
7395 static void R_RenderView_UpdateViewVectors(void)
7397 // break apart the view matrix into vectors for various purposes
7398 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7399 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7400 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7401 VectorNegate(r_refdef.view.left, r_refdef.view.right);
7402 // make an inverted copy of the view matrix for tracking sprites
7403 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7406 void R_RenderScene(void);
7407 void R_RenderWaterPlanes(void);
7409 static void R_Water_StartFrame(void)
7412 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7413 r_waterstate_waterplane_t *p;
7415 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7418 switch(vid.renderpath)
7420 case RENDERPATH_GL20:
7421 case RENDERPATH_CGGL:
7423 case RENDERPATH_GL13:
7424 case RENDERPATH_GL11:
7428 // set waterwidth and waterheight to the water resolution that will be
7429 // used (often less than the screen resolution for faster rendering)
7430 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7431 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7433 // calculate desired texture sizes
7434 // can't use water if the card does not support the texture size
7435 if (!r_water.integer || r_showsurfaces.integer)
7436 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7437 else if (vid.support.arb_texture_non_power_of_two)
7439 texturewidth = waterwidth;
7440 textureheight = waterheight;
7441 camerawidth = waterwidth;
7442 cameraheight = waterheight;
7446 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
7447 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
7448 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
7449 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
7452 // allocate textures as needed
7453 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7455 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7456 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7458 if (p->texture_refraction)
7459 R_FreeTexture(p->texture_refraction);
7460 p->texture_refraction = NULL;
7461 if (p->texture_reflection)
7462 R_FreeTexture(p->texture_reflection);
7463 p->texture_reflection = NULL;
7464 if (p->texture_camera)
7465 R_FreeTexture(p->texture_camera);
7466 p->texture_camera = NULL;
7468 memset(&r_waterstate, 0, sizeof(r_waterstate));
7469 r_waterstate.texturewidth = texturewidth;
7470 r_waterstate.textureheight = textureheight;
7471 r_waterstate.camerawidth = camerawidth;
7472 r_waterstate.cameraheight = cameraheight;
7475 if (r_waterstate.texturewidth)
7477 r_waterstate.enabled = true;
7479 // when doing a reduced render (HDR) we want to use a smaller area
7480 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7481 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7483 // set up variables that will be used in shader setup
7484 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7485 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7486 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7487 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7490 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7491 r_waterstate.numwaterplanes = 0;
7494 void R_Water_AddWaterPlane(msurface_t *surface)
7496 int triangleindex, planeindex;
7503 r_waterstate_waterplane_t *p;
7504 texture_t *t = R_GetCurrentTexture(surface->texture);
7505 cam_ent = t->camera_entity;
7506 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7509 // just use the first triangle with a valid normal for any decisions
7510 VectorClear(normal);
7511 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7513 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7514 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7515 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7516 TriangleNormal(vert[0], vert[1], vert[2], normal);
7517 if (VectorLength2(normal) >= 0.001)
7521 VectorCopy(normal, plane.normal);
7522 VectorNormalize(plane.normal);
7523 plane.dist = DotProduct(vert[0], plane.normal);
7524 PlaneClassify(&plane);
7525 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7527 // skip backfaces (except if nocullface is set)
7528 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7530 VectorNegate(plane.normal, plane.normal);
7532 PlaneClassify(&plane);
7536 // find a matching plane if there is one
7537 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7538 if(p->camera_entity == t->camera_entity)
7539 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7541 if (planeindex >= r_waterstate.maxwaterplanes)
7542 return; // nothing we can do, out of planes
7544 // if this triangle does not fit any known plane rendered this frame, add one
7545 if (planeindex >= r_waterstate.numwaterplanes)
7547 // store the new plane
7548 r_waterstate.numwaterplanes++;
7550 // clear materialflags and pvs
7551 p->materialflags = 0;
7552 p->pvsvalid = false;
7553 p->camera_entity = t->camera_entity;
7555 // merge this surface's materialflags into the waterplane
7556 p->materialflags |= t->currentmaterialflags;
7557 if(!(p->materialflags & MATERIALFLAG_CAMERA))
7559 // merge this surface's PVS into the waterplane
7560 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7561 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7562 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7564 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7570 static void R_Water_ProcessPlanes(void)
7572 r_refdef_view_t originalview;
7573 r_refdef_view_t myview;
7575 r_waterstate_waterplane_t *p;
7578 originalview = r_refdef.view;
7580 // make sure enough textures are allocated
7581 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7583 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7585 if (!p->texture_refraction)
7586 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7587 if (!p->texture_refraction)
7590 else if (p->materialflags & MATERIALFLAG_CAMERA)
7592 if (!p->texture_camera)
7593 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, NULL);
7594 if (!p->texture_camera)
7598 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7600 if (!p->texture_reflection)
7601 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7602 if (!p->texture_reflection)
7608 r_refdef.view = originalview;
7609 r_refdef.view.showdebug = false;
7610 r_refdef.view.width = r_waterstate.waterwidth;
7611 r_refdef.view.height = r_waterstate.waterheight;
7612 r_refdef.view.useclipplane = true;
7613 myview = r_refdef.view;
7614 r_waterstate.renderingscene = true;
7615 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7617 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7619 r_refdef.view = myview;
7620 // render reflected scene and copy into texture
7621 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7622 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7623 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7624 r_refdef.view.clipplane = p->plane;
7625 // reverse the cullface settings for this render
7626 r_refdef.view.cullface_front = GL_FRONT;
7627 r_refdef.view.cullface_back = GL_BACK;
7628 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7630 r_refdef.view.usecustompvs = true;
7632 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7634 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7637 R_ResetViewRendering3D();
7638 R_ClearScreen(r_refdef.fogenabled);
7642 R_Mesh_CopyToTexture(p->texture_reflection, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7645 // render the normal view scene and copy into texture
7646 // (except that a clipping plane should be used to hide everything on one side of the water, and the viewer's weapon model should be omitted)
7647 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7649 r_waterstate.renderingrefraction = true;
7650 r_refdef.view = myview;
7652 r_refdef.view.clipplane = p->plane;
7653 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7654 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7656 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7658 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7659 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7660 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7661 R_RenderView_UpdateViewVectors();
7662 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
7665 PlaneClassify(&r_refdef.view.clipplane);
7667 R_ResetViewRendering3D();
7668 R_ClearScreen(r_refdef.fogenabled);
7672 R_Mesh_CopyToTexture(p->texture_refraction, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7673 r_waterstate.renderingrefraction = false;
7675 else if (p->materialflags & MATERIALFLAG_CAMERA)
7677 r_refdef.view = myview;
7679 r_refdef.view.clipplane = p->plane;
7680 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7681 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7683 r_refdef.view.width = r_waterstate.camerawidth;
7684 r_refdef.view.height = r_waterstate.cameraheight;
7685 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7686 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7688 if(p->camera_entity)
7690 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7691 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7694 // reverse the cullface settings for this render
7695 r_refdef.view.cullface_front = GL_FRONT;
7696 r_refdef.view.cullface_back = GL_BACK;
7697 // also reverse the view matrix
7698 Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, -1, 1);
7699 R_RenderView_UpdateViewVectors();
7700 if(p->camera_entity)
7701 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
7703 // camera needs no clipplane
7704 r_refdef.view.useclipplane = false;
7706 PlaneClassify(&r_refdef.view.clipplane);
7708 R_ResetViewRendering3D();
7709 R_ClearScreen(r_refdef.fogenabled);
7713 R_Mesh_CopyToTexture(p->texture_camera, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7714 r_waterstate.renderingrefraction = false;
7718 r_waterstate.renderingscene = false;
7719 r_refdef.view = originalview;
7720 R_ResetViewRendering3D();
7721 R_ClearScreen(r_refdef.fogenabled);
7725 r_refdef.view = originalview;
7726 r_waterstate.renderingscene = false;
7727 Cvar_SetValueQuick(&r_water, 0);
7728 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
7732 void R_Bloom_StartFrame(void)
7734 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
7736 switch(vid.renderpath)
7738 case RENDERPATH_GL20:
7739 case RENDERPATH_CGGL:
7741 case RENDERPATH_GL13:
7742 case RENDERPATH_GL11:
7746 // set bloomwidth and bloomheight to the bloom resolution that will be
7747 // used (often less than the screen resolution for faster rendering)
7748 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
7749 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
7750 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
7751 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
7752 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
7754 // calculate desired texture sizes
7755 if (vid.support.arb_texture_non_power_of_two)
7757 screentexturewidth = r_refdef.view.width;
7758 screentextureheight = r_refdef.view.height;
7759 bloomtexturewidth = r_bloomstate.bloomwidth;
7760 bloomtextureheight = r_bloomstate.bloomheight;
7764 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
7765 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
7766 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
7767 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
7770 if ((r_hdr.integer || r_bloom.integer || (!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))) && ((r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512) || r_refdef.view.width > (int)vid.maxtexturesize_2d || r_refdef.view.height > (int)vid.maxtexturesize_2d))
7772 Cvar_SetValueQuick(&r_hdr, 0);
7773 Cvar_SetValueQuick(&r_bloom, 0);
7774 Cvar_SetValueQuick(&r_motionblur, 0);
7775 Cvar_SetValueQuick(&r_damageblur, 0);
7778 if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial)) && !r_bloom.integer && !r_hdr.integer && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0)))
7779 screentexturewidth = screentextureheight = 0;
7780 if (!r_hdr.integer && !r_bloom.integer)
7781 bloomtexturewidth = bloomtextureheight = 0;
7783 // allocate textures as needed
7784 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
7786 if (r_bloomstate.texture_screen)
7787 R_FreeTexture(r_bloomstate.texture_screen);
7788 r_bloomstate.texture_screen = NULL;
7789 r_bloomstate.screentexturewidth = screentexturewidth;
7790 r_bloomstate.screentextureheight = screentextureheight;
7791 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
7792 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, NULL);
7794 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
7796 if (r_bloomstate.texture_bloom)
7797 R_FreeTexture(r_bloomstate.texture_bloom);
7798 r_bloomstate.texture_bloom = NULL;
7799 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
7800 r_bloomstate.bloomtextureheight = bloomtextureheight;
7801 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
7802 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7805 // when doing a reduced render (HDR) we want to use a smaller area
7806 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
7807 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
7808 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
7809 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
7810 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
7812 // set up a texcoord array for the full resolution screen image
7813 // (we have to keep this around to copy back during final render)
7814 r_bloomstate.screentexcoord2f[0] = 0;
7815 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7816 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7817 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7818 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7819 r_bloomstate.screentexcoord2f[5] = 0;
7820 r_bloomstate.screentexcoord2f[6] = 0;
7821 r_bloomstate.screentexcoord2f[7] = 0;
7823 // set up a texcoord array for the reduced resolution bloom image
7824 // (which will be additive blended over the screen image)
7825 r_bloomstate.bloomtexcoord2f[0] = 0;
7826 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7827 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7828 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7829 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7830 r_bloomstate.bloomtexcoord2f[5] = 0;
7831 r_bloomstate.bloomtexcoord2f[6] = 0;
7832 r_bloomstate.bloomtexcoord2f[7] = 0;
7834 if (r_hdr.integer || r_bloom.integer)
7836 r_bloomstate.enabled = true;
7837 r_bloomstate.hdr = r_hdr.integer != 0;
7840 R_Viewport_InitOrtho(&r_bloomstate.viewport, &identitymatrix, r_refdef.view.x, vid.height - r_bloomstate.bloomheight - r_refdef.view.y, r_bloomstate.bloomwidth, r_bloomstate.bloomheight, 0, 0, 1, 1, -10, 100, NULL);
7843 void R_Bloom_CopyBloomTexture(float colorscale)
7845 r_refdef.stats.bloom++;
7847 // scale down screen texture to the bloom texture size
7849 R_SetViewport(&r_bloomstate.viewport);
7850 GL_BlendFunc(GL_ONE, GL_ZERO);
7851 GL_Color(colorscale, colorscale, colorscale, 1);
7852 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
7853 // TODO: do boxfilter scale-down in shader?
7854 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
7855 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7856 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7858 // we now have a bloom image in the framebuffer
7859 // copy it into the bloom image texture for later processing
7860 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
7861 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7864 void R_Bloom_CopyHDRTexture(void)
7866 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7867 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
7870 void R_Bloom_MakeTexture(void)
7873 float xoffset, yoffset, r, brighten;
7875 r_refdef.stats.bloom++;
7877 R_ResetViewRendering2D();
7879 // we have a bloom image in the framebuffer
7881 R_SetViewport(&r_bloomstate.viewport);
7883 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
7886 r = bound(0, r_bloom_colorexponent.value / x, 1);
7887 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
7889 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7890 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7891 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7892 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7894 // copy the vertically blurred bloom view to a texture
7895 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
7896 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7899 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
7900 brighten = r_bloom_brighten.value;
7902 brighten *= r_hdr_range.value;
7903 brighten = sqrt(brighten);
7905 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
7906 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7908 for (dir = 0;dir < 2;dir++)
7910 // blend on at multiple vertical offsets to achieve a vertical blur
7911 // TODO: do offset blends using GLSL
7912 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
7913 GL_BlendFunc(GL_ONE, GL_ZERO);
7914 for (x = -range;x <= range;x++)
7916 if (!dir){xoffset = 0;yoffset = x;}
7917 else {xoffset = x;yoffset = 0;}
7918 xoffset /= (float)r_bloomstate.bloomtexturewidth;
7919 yoffset /= (float)r_bloomstate.bloomtextureheight;
7920 // compute a texcoord array with the specified x and y offset
7921 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
7922 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7923 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7924 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7925 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7926 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
7927 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
7928 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
7929 // this r value looks like a 'dot' particle, fading sharply to
7930 // black at the edges
7931 // (probably not realistic but looks good enough)
7932 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
7933 //r = brighten/(range*2+1);
7934 r = brighten / (range * 2 + 1);
7936 r *= (1 - x*x/(float)(range*range));
7937 GL_Color(r, r, r, 1);
7938 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
7939 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7940 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7941 GL_BlendFunc(GL_ONE, GL_ONE);
7944 // copy the vertically blurred bloom view to a texture
7945 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
7946 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7949 // apply subtract last
7950 // (just like it would be in a GLSL shader)
7951 if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
7953 GL_BlendFunc(GL_ONE, GL_ZERO);
7955 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7956 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7957 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7958 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7960 GL_BlendFunc(GL_ONE, GL_ONE);
7961 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
7962 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
7963 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
7964 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7965 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7966 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7967 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
7969 // copy the darkened bloom view to a texture
7970 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
7971 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7975 void R_HDR_RenderBloomTexture(void)
7977 int oldwidth, oldheight;
7978 float oldcolorscale;
7980 oldcolorscale = r_refdef.view.colorscale;
7981 oldwidth = r_refdef.view.width;
7982 oldheight = r_refdef.view.height;
7983 r_refdef.view.width = r_bloomstate.bloomwidth;
7984 r_refdef.view.height = r_bloomstate.bloomheight;
7986 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
7987 // TODO: add exposure compensation features
7988 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
7990 r_refdef.view.showdebug = false;
7991 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
7993 R_ResetViewRendering3D();
7995 R_ClearScreen(r_refdef.fogenabled);
7996 if (r_timereport_active)
7997 R_TimeReport("HDRclear");
8000 if (r_timereport_active)
8001 R_TimeReport("visibility");
8003 // only do secondary renders with HDR if r_hdr is 2 or higher
8004 r_waterstate.numwaterplanes = 0;
8005 if (r_waterstate.enabled && r_hdr.integer >= 2)
8006 R_RenderWaterPlanes();
8008 r_refdef.view.showdebug = true;
8010 r_waterstate.numwaterplanes = 0;
8012 R_ResetViewRendering2D();
8014 R_Bloom_CopyHDRTexture();
8015 R_Bloom_MakeTexture();
8017 // restore the view settings
8018 r_refdef.view.width = oldwidth;
8019 r_refdef.view.height = oldheight;
8020 r_refdef.view.colorscale = oldcolorscale;
8022 R_ResetViewRendering3D();
8024 R_ClearScreen(r_refdef.fogenabled);
8025 if (r_timereport_active)
8026 R_TimeReport("viewclear");
8029 static void R_BlendView(void)
8031 unsigned int permutation;
8032 float uservecs[4][4];
8034 switch (vid.renderpath)
8036 case RENDERPATH_GL20:
8037 case RENDERPATH_CGGL:
8039 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8040 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8041 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8042 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8043 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8045 if (r_bloomstate.texture_screen)
8047 // make sure the buffer is available
8048 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8050 R_ResetViewRendering2D();
8052 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8054 // declare variables
8056 static float avgspeed;
8058 speed = VectorLength(cl.movement_velocity);
8060 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8061 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8063 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8064 speed = bound(0, speed, 1);
8065 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8067 // calculate values into a standard alpha
8068 cl.motionbluralpha = 1 - exp(-
8070 (r_motionblur.value * speed / 80)
8072 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8075 max(0.0001, cl.time - cl.oldtime) // fps independent
8078 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8079 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8081 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8083 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8084 GL_Color(1, 1, 1, cl.motionbluralpha);
8085 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8086 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8087 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8088 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8092 // copy view into the screen texture
8093 R_Mesh_CopyToTexture(r_bloomstate.texture_screen, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8094 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8096 else if (!r_bloomstate.texture_bloom)
8098 // we may still have to do view tint...
8099 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8101 // apply a color tint to the whole view
8102 R_ResetViewRendering2D();
8103 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8104 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8105 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8106 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8107 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8109 break; // no screen processing, no bloom, skip it
8112 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8114 // render simple bloom effect
8115 // copy the screen and shrink it and darken it for the bloom process
8116 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8117 // make the bloom texture
8118 R_Bloom_MakeTexture();
8121 #if _MSC_VER >= 1400
8122 #define sscanf sscanf_s
8124 memset(uservecs, 0, sizeof(uservecs));
8125 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8126 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8127 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8128 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8130 R_ResetViewRendering2D();
8131 GL_Color(1, 1, 1, 1);
8132 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8133 GL_BlendFunc(GL_ONE, GL_ZERO);
8135 switch(vid.renderpath)
8137 case RENDERPATH_GL20:
8138 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8139 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8140 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8141 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8142 if (r_glsl_permutation->loc_ViewTintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8143 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8144 if (r_glsl_permutation->loc_UserVec1 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8145 if (r_glsl_permutation->loc_UserVec2 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8146 if (r_glsl_permutation->loc_UserVec3 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8147 if (r_glsl_permutation->loc_UserVec4 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8148 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8149 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8151 case RENDERPATH_CGGL:
8153 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8154 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
8155 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
8156 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
8157 if (r_cg_permutation->fp_ViewTintColor ) cgGLSetParameter4f( r_cg_permutation->fp_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);CHECKCGERROR
8158 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8159 if (r_cg_permutation->fp_UserVec1 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);CHECKCGERROR
8160 if (r_cg_permutation->fp_UserVec2 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);CHECKCGERROR
8161 if (r_cg_permutation->fp_UserVec3 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);CHECKCGERROR
8162 if (r_cg_permutation->fp_UserVec4 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);CHECKCGERROR
8163 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
8164 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8170 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8171 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8173 case RENDERPATH_GL13:
8174 case RENDERPATH_GL11:
8175 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8177 // apply a color tint to the whole view
8178 R_ResetViewRendering2D();
8179 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8180 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8181 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8182 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8183 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8189 matrix4x4_t r_waterscrollmatrix;
8191 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8193 if (r_refdef.fog_density)
8195 r_refdef.fogcolor[0] = r_refdef.fog_red;
8196 r_refdef.fogcolor[1] = r_refdef.fog_green;
8197 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8199 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8200 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8201 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8202 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8206 VectorCopy(r_refdef.fogcolor, fogvec);
8207 // color.rgb *= ContrastBoost * SceneBrightness;
8208 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8209 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8210 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8211 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8216 void R_UpdateVariables(void)
8220 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8222 r_refdef.farclip = r_farclip_base.value;
8223 if (r_refdef.scene.worldmodel)
8224 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8225 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8227 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8228 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8229 r_refdef.polygonfactor = 0;
8230 r_refdef.polygonoffset = 0;
8231 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8232 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8234 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8235 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8236 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8237 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8238 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8239 if (r_showsurfaces.integer)
8241 r_refdef.scene.rtworld = false;
8242 r_refdef.scene.rtworldshadows = false;
8243 r_refdef.scene.rtdlight = false;
8244 r_refdef.scene.rtdlightshadows = false;
8245 r_refdef.lightmapintensity = 0;
8248 if (gamemode == GAME_NEHAHRA)
8250 if (gl_fogenable.integer)
8252 r_refdef.oldgl_fogenable = true;
8253 r_refdef.fog_density = gl_fogdensity.value;
8254 r_refdef.fog_red = gl_fogred.value;
8255 r_refdef.fog_green = gl_foggreen.value;
8256 r_refdef.fog_blue = gl_fogblue.value;
8257 r_refdef.fog_alpha = 1;
8258 r_refdef.fog_start = 0;
8259 r_refdef.fog_end = gl_skyclip.value;
8260 r_refdef.fog_height = 1<<30;
8261 r_refdef.fog_fadedepth = 128;
8263 else if (r_refdef.oldgl_fogenable)
8265 r_refdef.oldgl_fogenable = false;
8266 r_refdef.fog_density = 0;
8267 r_refdef.fog_red = 0;
8268 r_refdef.fog_green = 0;
8269 r_refdef.fog_blue = 0;
8270 r_refdef.fog_alpha = 0;
8271 r_refdef.fog_start = 0;
8272 r_refdef.fog_end = 0;
8273 r_refdef.fog_height = 1<<30;
8274 r_refdef.fog_fadedepth = 128;
8278 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8279 r_refdef.fog_start = max(0, r_refdef.fog_start);
8280 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8282 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8284 if (r_refdef.fog_density && r_drawfog.integer)
8286 r_refdef.fogenabled = true;
8287 // this is the point where the fog reaches 0.9986 alpha, which we
8288 // consider a good enough cutoff point for the texture
8289 // (0.9986 * 256 == 255.6)
8290 if (r_fog_exp2.integer)
8291 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8293 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8294 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8295 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8296 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8297 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8298 R_BuildFogHeightTexture();
8299 // fog color was already set
8300 // update the fog texture
8301 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
8302 R_BuildFogTexture();
8303 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8304 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8307 r_refdef.fogenabled = false;
8309 switch(vid.renderpath)
8311 case RENDERPATH_GL20:
8312 case RENDERPATH_CGGL:
8313 if(v_glslgamma.integer && !vid_gammatables_trivial)
8315 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8317 // build GLSL gamma texture
8318 #define RAMPWIDTH 256
8319 unsigned short ramp[RAMPWIDTH * 3];
8320 unsigned char rampbgr[RAMPWIDTH][4];
8323 r_texture_gammaramps_serial = vid_gammatables_serial;
8325 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8326 for(i = 0; i < RAMPWIDTH; ++i)
8328 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8329 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8330 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8333 if (r_texture_gammaramps)
8335 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8339 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, NULL);
8345 // remove GLSL gamma texture
8348 case RENDERPATH_GL13:
8349 case RENDERPATH_GL11:
8354 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8355 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8361 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8362 if( scenetype != r_currentscenetype ) {
8363 // store the old scenetype
8364 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8365 r_currentscenetype = scenetype;
8366 // move in the new scene
8367 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8376 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8378 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8379 if( scenetype == r_currentscenetype ) {
8380 return &r_refdef.scene;
8382 return &r_scenes_store[ scenetype ];
8391 void R_RenderView(void)
8393 if (r_timereport_active)
8394 R_TimeReport("start");
8395 r_textureframe++; // used only by R_GetCurrentTexture
8396 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8398 if (!r_drawentities.integer)
8399 r_refdef.scene.numentities = 0;
8401 R_AnimCache_ClearCache();
8402 R_FrameData_NewFrame();
8404 if (r_refdef.view.isoverlay)
8406 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8407 GL_Clear( GL_DEPTH_BUFFER_BIT );
8408 R_TimeReport("depthclear");
8410 r_refdef.view.showdebug = false;
8412 r_waterstate.enabled = false;
8413 r_waterstate.numwaterplanes = 0;
8421 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8422 return; //Host_Error ("R_RenderView: NULL worldmodel");
8424 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8426 R_RenderView_UpdateViewVectors();
8428 R_Shadow_UpdateWorldLightSelection();
8430 R_Bloom_StartFrame();
8431 R_Water_StartFrame();
8434 if (r_timereport_active)
8435 R_TimeReport("viewsetup");
8437 R_ResetViewRendering3D();
8439 if (r_refdef.view.clear || r_refdef.fogenabled)
8441 R_ClearScreen(r_refdef.fogenabled);
8442 if (r_timereport_active)
8443 R_TimeReport("viewclear");
8445 r_refdef.view.clear = true;
8447 // this produces a bloom texture to be used in R_BlendView() later
8448 if (r_hdr.integer && r_bloomstate.bloomwidth)
8450 R_HDR_RenderBloomTexture();
8451 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8452 r_textureframe++; // used only by R_GetCurrentTexture
8455 r_refdef.view.showdebug = true;
8458 if (r_timereport_active)
8459 R_TimeReport("visibility");
8461 r_waterstate.numwaterplanes = 0;
8462 if (r_waterstate.enabled)
8463 R_RenderWaterPlanes();
8466 r_waterstate.numwaterplanes = 0;
8469 if (r_timereport_active)
8470 R_TimeReport("blendview");
8472 GL_Scissor(0, 0, vid.width, vid.height);
8473 GL_ScissorTest(false);
8477 void R_RenderWaterPlanes(void)
8479 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8481 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8482 if (r_timereport_active)
8483 R_TimeReport("waterworld");
8486 // don't let sound skip if going slow
8487 if (r_refdef.scene.extraupdate)
8490 R_DrawModelsAddWaterPlanes();
8491 if (r_timereport_active)
8492 R_TimeReport("watermodels");
8494 if (r_waterstate.numwaterplanes)
8496 R_Water_ProcessPlanes();
8497 if (r_timereport_active)
8498 R_TimeReport("waterscenes");
8502 extern void R_DrawLightningBeams (void);
8503 extern void VM_CL_AddPolygonsToMeshQueue (void);
8504 extern void R_DrawPortals (void);
8505 extern cvar_t cl_locs_show;
8506 static void R_DrawLocs(void);
8507 static void R_DrawEntityBBoxes(void);
8508 static void R_DrawModelDecals(void);
8509 extern void R_DrawModelShadows(void);
8510 extern void R_DrawModelShadowMaps(void);
8511 extern cvar_t cl_decals_newsystem;
8512 extern qboolean r_shadow_usingdeferredprepass;
8513 void R_RenderScene(void)
8515 qboolean shadowmapping = false;
8517 if (r_timereport_active)
8518 R_TimeReport("beginscene");
8520 r_refdef.stats.renders++;
8524 // don't let sound skip if going slow
8525 if (r_refdef.scene.extraupdate)
8528 R_MeshQueue_BeginScene();
8532 Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
8534 if (r_timereport_active)
8535 R_TimeReport("skystartframe");
8537 if (cl.csqc_vidvars.drawworld)
8539 // don't let sound skip if going slow
8540 if (r_refdef.scene.extraupdate)
8543 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8545 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8546 if (r_timereport_active)
8547 R_TimeReport("worldsky");
8550 if (R_DrawBrushModelsSky() && r_timereport_active)
8551 R_TimeReport("bmodelsky");
8553 if (skyrendermasked && skyrenderlater)
8555 // we have to force off the water clipping plane while rendering sky
8559 if (r_timereport_active)
8560 R_TimeReport("sky");
8564 R_AnimCache_CacheVisibleEntities();
8565 if (r_timereport_active)
8566 R_TimeReport("animation");
8568 R_Shadow_PrepareLights();
8569 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8570 R_Shadow_PrepareModelShadows();
8571 if (r_timereport_active)
8572 R_TimeReport("preparelights");
8574 if (R_Shadow_ShadowMappingEnabled())
8575 shadowmapping = true;
8577 if (r_shadow_usingdeferredprepass)
8578 R_Shadow_DrawPrepass();
8580 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8582 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8583 if (r_timereport_active)
8584 R_TimeReport("worlddepth");
8586 if (r_depthfirst.integer >= 2)
8588 R_DrawModelsDepth();
8589 if (r_timereport_active)
8590 R_TimeReport("modeldepth");
8593 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8595 R_DrawModelShadowMaps();
8596 R_ResetViewRendering3D();
8597 // don't let sound skip if going slow
8598 if (r_refdef.scene.extraupdate)
8602 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8604 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8605 if (r_timereport_active)
8606 R_TimeReport("world");
8609 // don't let sound skip if going slow
8610 if (r_refdef.scene.extraupdate)
8614 if (r_timereport_active)
8615 R_TimeReport("models");
8617 // don't let sound skip if going slow
8618 if (r_refdef.scene.extraupdate)
8621 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8623 R_DrawModelShadows();
8624 R_ResetViewRendering3D();
8625 // don't let sound skip if going slow
8626 if (r_refdef.scene.extraupdate)
8630 if (!r_shadow_usingdeferredprepass)
8632 R_Shadow_DrawLights();
8633 if (r_timereport_active)
8634 R_TimeReport("rtlights");
8637 // don't let sound skip if going slow
8638 if (r_refdef.scene.extraupdate)
8641 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8643 R_DrawModelShadows();
8644 R_ResetViewRendering3D();
8645 // don't let sound skip if going slow
8646 if (r_refdef.scene.extraupdate)
8650 if (cl.csqc_vidvars.drawworld)
8652 if (cl_decals_newsystem.integer)
8654 R_DrawModelDecals();
8655 if (r_timereport_active)
8656 R_TimeReport("modeldecals");
8661 if (r_timereport_active)
8662 R_TimeReport("decals");
8666 if (r_timereport_active)
8667 R_TimeReport("particles");
8670 if (r_timereport_active)
8671 R_TimeReport("explosions");
8673 R_DrawLightningBeams();
8674 if (r_timereport_active)
8675 R_TimeReport("lightning");
8678 VM_CL_AddPolygonsToMeshQueue();
8680 if (r_refdef.view.showdebug)
8682 if (cl_locs_show.integer)
8685 if (r_timereport_active)
8686 R_TimeReport("showlocs");
8689 if (r_drawportals.integer)
8692 if (r_timereport_active)
8693 R_TimeReport("portals");
8696 if (r_showbboxes.value > 0)
8698 R_DrawEntityBBoxes();
8699 if (r_timereport_active)
8700 R_TimeReport("bboxes");
8704 R_MeshQueue_RenderTransparent();
8705 if (r_timereport_active)
8706 R_TimeReport("drawtrans");
8708 if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value != 0 || r_showcollisionbrushes.value > 0))
8710 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
8711 if (r_timereport_active)
8712 R_TimeReport("worlddebug");
8713 R_DrawModelsDebug();
8714 if (r_timereport_active)
8715 R_TimeReport("modeldebug");
8718 if (cl.csqc_vidvars.drawworld)
8720 R_Shadow_DrawCoronas();
8721 if (r_timereport_active)
8722 R_TimeReport("coronas");
8725 // don't let sound skip if going slow
8726 if (r_refdef.scene.extraupdate)
8729 R_ResetViewRendering2D();
8732 static const unsigned short bboxelements[36] =
8742 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
8745 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
8747 RSurf_ActiveWorldEntity();
8749 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8750 GL_DepthMask(false);
8751 GL_DepthRange(0, 1);
8752 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8753 R_Mesh_ResetTextureState();
8755 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
8756 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
8757 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
8758 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
8759 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
8760 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
8761 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
8762 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
8763 R_FillColors(color4f, 8, cr, cg, cb, ca);
8764 if (r_refdef.fogenabled)
8766 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
8768 f1 = RSurf_FogVertex(v);
8770 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
8771 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
8772 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
8775 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
8776 R_Mesh_ResetTextureState();
8777 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8778 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
8781 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8785 prvm_edict_t *edict;
8786 prvm_prog_t *prog_save = prog;
8788 // this function draws bounding boxes of server entities
8792 GL_CullFace(GL_NONE);
8793 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8797 for (i = 0;i < numsurfaces;i++)
8799 edict = PRVM_EDICT_NUM(surfacelist[i]);
8800 switch ((int)edict->fields.server->solid)
8802 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
8803 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
8804 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
8805 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
8806 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
8807 default: Vector4Set(color, 0, 0, 0, 0.50);break;
8809 color[3] *= r_showbboxes.value;
8810 color[3] = bound(0, color[3], 1);
8811 GL_DepthTest(!r_showdisabledepthtest.integer);
8812 GL_CullFace(r_refdef.view.cullface_front);
8813 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
8819 static void R_DrawEntityBBoxes(void)
8822 prvm_edict_t *edict;
8824 prvm_prog_t *prog_save = prog;
8826 // this function draws bounding boxes of server entities
8832 for (i = 0;i < prog->num_edicts;i++)
8834 edict = PRVM_EDICT_NUM(i);
8835 if (edict->priv.server->free)
8837 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
8838 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
8840 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
8842 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
8843 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
8849 static const int nomodelelement3i[24] =
8861 static const unsigned short nomodelelement3s[24] =
8873 static const float nomodelvertex3f[6*3] =
8883 static const float nomodelcolor4f[6*4] =
8885 0.0f, 0.0f, 0.5f, 1.0f,
8886 0.0f, 0.0f, 0.5f, 1.0f,
8887 0.0f, 0.5f, 0.0f, 1.0f,
8888 0.0f, 0.5f, 0.0f, 1.0f,
8889 0.5f, 0.0f, 0.0f, 1.0f,
8890 0.5f, 0.0f, 0.0f, 1.0f
8893 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8899 RSurf_ActiveCustomEntity(&ent->matrix, &ent->inversematrix, ent->flags, ent->shadertime, ent->colormod[0], ent->colormod[1], ent->colormod[2], ent->alpha, 6, nomodelvertex3f, NULL, NULL, NULL, NULL, nomodelcolor4f, 8, nomodelelement3i, nomodelelement3s, false, false);
8901 // this is only called once per entity so numsurfaces is always 1, and
8902 // surfacelist is always {0}, so this code does not handle batches
8904 if (rsurface.ent_flags & RENDER_ADDITIVE)
8906 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
8907 GL_DepthMask(false);
8909 else if (rsurface.colormod[3] < 1)
8911 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8912 GL_DepthMask(false);
8916 GL_BlendFunc(GL_ONE, GL_ZERO);
8919 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
8920 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
8921 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
8922 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
8923 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8924 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
8925 for (i = 0, c = color4f;i < 6;i++, c += 4)
8927 c[0] *= rsurface.colormod[0];
8928 c[1] *= rsurface.colormod[1];
8929 c[2] *= rsurface.colormod[2];
8930 c[3] *= rsurface.colormod[3];
8932 if (r_refdef.fogenabled)
8934 for (i = 0, c = color4f;i < 6;i++, c += 4)
8936 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
8938 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
8939 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
8940 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
8943 R_Mesh_ResetTextureState();
8944 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
8945 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
8948 void R_DrawNoModel(entity_render_t *ent)
8951 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
8952 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
8953 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
8955 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
8958 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
8960 vec3_t right1, right2, diff, normal;
8962 VectorSubtract (org2, org1, normal);
8964 // calculate 'right' vector for start
8965 VectorSubtract (r_refdef.view.origin, org1, diff);
8966 CrossProduct (normal, diff, right1);
8967 VectorNormalize (right1);
8969 // calculate 'right' vector for end
8970 VectorSubtract (r_refdef.view.origin, org2, diff);
8971 CrossProduct (normal, diff, right2);
8972 VectorNormalize (right2);
8974 vert[ 0] = org1[0] + width * right1[0];
8975 vert[ 1] = org1[1] + width * right1[1];
8976 vert[ 2] = org1[2] + width * right1[2];
8977 vert[ 3] = org1[0] - width * right1[0];
8978 vert[ 4] = org1[1] - width * right1[1];
8979 vert[ 5] = org1[2] - width * right1[2];
8980 vert[ 6] = org2[0] - width * right2[0];
8981 vert[ 7] = org2[1] - width * right2[1];
8982 vert[ 8] = org2[2] - width * right2[2];
8983 vert[ 9] = org2[0] + width * right2[0];
8984 vert[10] = org2[1] + width * right2[1];
8985 vert[11] = org2[2] + width * right2[2];
8988 void R_CalcSprite_Vertex3f(float *vertex3f, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2)
8990 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
8991 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
8992 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
8993 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
8994 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
8995 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
8996 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
8997 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
8998 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
8999 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9000 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9001 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9004 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9009 VectorSet(v, x, y, z);
9010 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9011 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9013 if (i == mesh->numvertices)
9015 if (mesh->numvertices < mesh->maxvertices)
9017 VectorCopy(v, vertex3f);
9018 mesh->numvertices++;
9020 return mesh->numvertices;
9026 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9030 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9031 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9032 e = mesh->element3i + mesh->numtriangles * 3;
9033 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9035 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9036 if (mesh->numtriangles < mesh->maxtriangles)
9041 mesh->numtriangles++;
9043 element[1] = element[2];
9047 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9051 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9052 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9053 e = mesh->element3i + mesh->numtriangles * 3;
9054 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9056 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9057 if (mesh->numtriangles < mesh->maxtriangles)
9062 mesh->numtriangles++;
9064 element[1] = element[2];
9068 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9069 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9071 int planenum, planenum2;
9074 mplane_t *plane, *plane2;
9076 double temppoints[2][256*3];
9077 // figure out how large a bounding box we need to properly compute this brush
9079 for (w = 0;w < numplanes;w++)
9080 maxdist = max(maxdist, fabs(planes[w].dist));
9081 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9082 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9083 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9087 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9088 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9090 if (planenum2 == planenum)
9092 PolygonD_Divide(tempnumpoints, temppoints[w], plane2->normal[0], plane2->normal[1], plane2->normal[2], plane2->dist, R_MESH_PLANE_DIST_EPSILON, 0, NULL, NULL, 256, temppoints[!w], &tempnumpoints, NULL);
9095 if (tempnumpoints < 3)
9097 // generate elements forming a triangle fan for this polygon
9098 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9102 static void R_Texture_AddLayer(texture_t *t, qboolean depthmask, int blendfunc1, int blendfunc2, texturelayertype_t type, rtexture_t *texture, const matrix4x4_t *matrix, float r, float g, float b, float a)
9104 texturelayer_t *layer;
9105 layer = t->currentlayers + t->currentnumlayers++;
9107 layer->depthmask = depthmask;
9108 layer->blendfunc1 = blendfunc1;
9109 layer->blendfunc2 = blendfunc2;
9110 layer->texture = texture;
9111 layer->texmatrix = *matrix;
9112 layer->color[0] = r;
9113 layer->color[1] = g;
9114 layer->color[2] = b;
9115 layer->color[3] = a;
9118 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9121 index = parms[2] + r_refdef.scene.time * parms[3];
9122 index -= floor(index);
9126 case Q3WAVEFUNC_NONE:
9127 case Q3WAVEFUNC_NOISE:
9128 case Q3WAVEFUNC_COUNT:
9131 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9132 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9133 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9134 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9135 case Q3WAVEFUNC_TRIANGLE:
9137 f = index - floor(index);
9148 return (float)(parms[0] + parms[1] * f);
9151 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9156 matrix4x4_t matrix, temp;
9157 switch(tcmod->tcmod)
9161 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9162 matrix = r_waterscrollmatrix;
9164 matrix = identitymatrix;
9166 case Q3TCMOD_ENTITYTRANSLATE:
9167 // this is used in Q3 to allow the gamecode to control texcoord
9168 // scrolling on the entity, which is not supported in darkplaces yet.
9169 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9171 case Q3TCMOD_ROTATE:
9172 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9173 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9174 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9177 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9179 case Q3TCMOD_SCROLL:
9180 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9182 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9183 w = (int) tcmod->parms[0];
9184 h = (int) tcmod->parms[1];
9185 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9187 idx = (int) floor(f * w * h);
9188 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9190 case Q3TCMOD_STRETCH:
9191 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9192 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9194 case Q3TCMOD_TRANSFORM:
9195 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
9196 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
9197 VectorSet(tcmat + 6, 0 , 0 , 1);
9198 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
9199 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9201 case Q3TCMOD_TURBULENT:
9202 // this is handled in the RSurf_PrepareVertices function
9203 matrix = identitymatrix;
9207 Matrix4x4_Concat(texmatrix, &matrix, &temp);
9210 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9212 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9213 char name[MAX_QPATH];
9214 skinframe_t *skinframe;
9215 unsigned char pixels[296*194];
9216 strlcpy(cache->name, skinname, sizeof(cache->name));
9217 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9218 if (developer_loading.integer)
9219 Con_Printf("loading %s\n", name);
9220 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9221 if (!skinframe || !skinframe->base)
9224 fs_offset_t filesize;
9226 f = FS_LoadFile(name, tempmempool, true, &filesize);
9229 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9230 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9234 cache->skinframe = skinframe;
9237 texture_t *R_GetCurrentTexture(texture_t *t)
9240 const entity_render_t *ent = rsurface.entity;
9241 dp_model_t *model = ent->model;
9242 q3shaderinfo_layer_tcmod_t *tcmod;
9244 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9245 return t->currentframe;
9246 t->update_lastrenderframe = r_textureframe;
9247 t->update_lastrenderentity = (void *)ent;
9249 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9250 t->camera_entity = ent->entitynumber;
9252 t->camera_entity = 0;
9254 // switch to an alternate material if this is a q1bsp animated material
9256 texture_t *texture = t;
9257 int s = rsurface.ent_skinnum;
9258 if ((unsigned int)s >= (unsigned int)model->numskins)
9260 if (model->skinscenes)
9262 if (model->skinscenes[s].framecount > 1)
9263 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9265 s = model->skinscenes[s].firstframe;
9268 t = t + s * model->num_surfaces;
9271 // use an alternate animation if the entity's frame is not 0,
9272 // and only if the texture has an alternate animation
9273 if (rsurface.ent_alttextures && t->anim_total[1])
9274 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9276 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9278 texture->currentframe = t;
9281 // update currentskinframe to be a qw skin or animation frame
9282 if (rsurface.ent_qwskin >= 0)
9284 i = rsurface.ent_qwskin;
9285 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9287 r_qwskincache_size = cl.maxclients;
9289 Mem_Free(r_qwskincache);
9290 r_qwskincache = Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9292 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9293 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9294 t->currentskinframe = r_qwskincache[i].skinframe;
9295 if (t->currentskinframe == NULL)
9296 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9298 else if (t->numskinframes >= 2)
9299 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9300 if (t->backgroundnumskinframes >= 2)
9301 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9303 t->currentmaterialflags = t->basematerialflags;
9304 t->currentalpha = rsurface.colormod[3];
9305 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9306 t->currentalpha *= r_wateralpha.value;
9307 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9308 t->currentalpha *= t->r_water_wateralpha;
9309 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9310 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9311 if (!(rsurface.ent_flags & RENDER_LIGHT))
9312 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9313 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9315 // pick a model lighting mode
9316 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9317 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9319 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9321 if (rsurface.ent_flags & RENDER_ADDITIVE)
9322 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9323 else if (t->currentalpha < 1)
9324 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9325 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9326 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9327 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9328 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9329 if (t->backgroundnumskinframes)
9330 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9331 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9333 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9334 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9337 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9338 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9339 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9341 // there is no tcmod
9342 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9344 t->currenttexmatrix = r_waterscrollmatrix;
9345 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9347 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9349 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9350 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9353 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9354 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9355 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9356 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9358 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9359 if (t->currentskinframe->qpixels)
9360 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9361 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9362 if (!t->basetexture)
9363 t->basetexture = r_texture_notexture;
9364 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9365 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9366 t->nmaptexture = t->currentskinframe->nmap;
9367 if (!t->nmaptexture)
9368 t->nmaptexture = r_texture_blanknormalmap;
9369 t->glosstexture = r_texture_black;
9370 t->glowtexture = t->currentskinframe->glow;
9371 t->fogtexture = t->currentskinframe->fog;
9372 t->reflectmasktexture = t->currentskinframe->reflect;
9373 if (t->backgroundnumskinframes)
9375 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9376 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9377 t->backgroundglosstexture = r_texture_black;
9378 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9379 if (!t->backgroundnmaptexture)
9380 t->backgroundnmaptexture = r_texture_blanknormalmap;
9384 t->backgroundbasetexture = r_texture_white;
9385 t->backgroundnmaptexture = r_texture_blanknormalmap;
9386 t->backgroundglosstexture = r_texture_black;
9387 t->backgroundglowtexture = NULL;
9389 t->specularpower = r_shadow_glossexponent.value;
9390 // TODO: store reference values for these in the texture?
9391 t->specularscale = 0;
9392 if (r_shadow_gloss.integer > 0)
9394 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9396 if (r_shadow_glossintensity.value > 0)
9398 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9399 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9400 t->specularscale = r_shadow_glossintensity.value;
9403 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9405 t->glosstexture = r_texture_white;
9406 t->backgroundglosstexture = r_texture_white;
9407 t->specularscale = r_shadow_gloss2intensity.value;
9408 t->specularpower = r_shadow_gloss2exponent.value;
9411 t->specularscale *= t->specularscalemod;
9412 t->specularpower *= t->specularpowermod;
9414 // lightmaps mode looks bad with dlights using actual texturing, so turn
9415 // off the colormap and glossmap, but leave the normalmap on as it still
9416 // accurately represents the shading involved
9417 if (gl_lightmaps.integer)
9419 t->basetexture = r_texture_grey128;
9420 t->pantstexture = r_texture_black;
9421 t->shirttexture = r_texture_black;
9422 t->nmaptexture = r_texture_blanknormalmap;
9423 t->glosstexture = r_texture_black;
9424 t->glowtexture = NULL;
9425 t->fogtexture = NULL;
9426 t->reflectmasktexture = NULL;
9427 t->backgroundbasetexture = NULL;
9428 t->backgroundnmaptexture = r_texture_blanknormalmap;
9429 t->backgroundglosstexture = r_texture_black;
9430 t->backgroundglowtexture = NULL;
9431 t->specularscale = 0;
9432 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9435 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9436 VectorClear(t->dlightcolor);
9437 t->currentnumlayers = 0;
9438 if (t->currentmaterialflags & MATERIALFLAG_WALL)
9440 int blendfunc1, blendfunc2;
9442 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9444 blendfunc1 = GL_SRC_ALPHA;
9445 blendfunc2 = GL_ONE;
9447 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9449 blendfunc1 = GL_SRC_ALPHA;
9450 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9452 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9454 blendfunc1 = t->customblendfunc[0];
9455 blendfunc2 = t->customblendfunc[1];
9459 blendfunc1 = GL_ONE;
9460 blendfunc2 = GL_ZERO;
9462 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9463 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9465 // fullbright is not affected by r_refdef.lightmapintensity
9466 R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
9467 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9468 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9469 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9470 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9474 vec3_t ambientcolor;
9476 // set the color tint used for lights affecting this surface
9477 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9479 // q3bsp has no lightmap updates, so the lightstylevalue that
9480 // would normally be baked into the lightmap must be
9481 // applied to the color
9482 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9483 if (model->type == mod_brushq3)
9484 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9485 colorscale *= r_refdef.lightmapintensity;
9486 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9487 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9488 // basic lit geometry
9489 R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
9490 // add pants/shirt if needed
9491 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9492 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9493 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9494 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9495 // now add ambient passes if needed
9496 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9498 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
9499 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9500 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * ambientcolor[0], rsurface.colormap_pantscolor[1] * ambientcolor[1], rsurface.colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
9501 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9502 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * ambientcolor[0], rsurface.colormap_shirtcolor[1] * ambientcolor[1], rsurface.colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
9505 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9506 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->glowtexture, &t->currenttexmatrix, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2], t->lightmapcolor[3]);
9507 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9509 // if this is opaque use alpha blend which will darken the earlier
9512 // if this is an alpha blended material, all the earlier passes
9513 // were darkened by fog already, so we only need to add the fog
9514 // color ontop through the fog mask texture
9516 // if this is an additive blended material, all the earlier passes
9517 // were darkened by fog already, and we should not add fog color
9518 // (because the background was not darkened, there is no fog color
9519 // that was lost behind it).
9520 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->fogtexture, &t->currenttexmatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->lightmapcolor[3]);
9524 return t->currentframe;
9527 rsurfacestate_t rsurface;
9529 void R_Mesh_ResizeArrays(int newvertices)
9531 unsigned char *base;
9533 if (rsurface.array_size >= newvertices)
9535 if (rsurface.array_base)
9536 Mem_Free(rsurface.array_base);
9537 rsurface.array_size = (newvertices + 1023) & ~1023;
9539 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9540 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9541 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9542 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9543 size += rsurface.array_size * sizeof(float[3]);
9544 size += rsurface.array_size * sizeof(float[3]);
9545 size += rsurface.array_size * sizeof(float[3]);
9546 size += rsurface.array_size * sizeof(float[3]);
9547 size += rsurface.array_size * sizeof(float[3]);
9548 size += rsurface.array_size * sizeof(float[3]);
9549 size += rsurface.array_size * sizeof(float[3]);
9550 size += rsurface.array_size * sizeof(float[3]);
9551 size += rsurface.array_size * sizeof(float[4]);
9552 size += rsurface.array_size * sizeof(float[2]);
9553 size += rsurface.array_size * sizeof(float[2]);
9554 size += rsurface.array_size * sizeof(float[4]);
9555 size += rsurface.array_size * sizeof(int[3]);
9556 size += rsurface.array_size * sizeof(unsigned short[3]);
9557 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
9558 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9559 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9560 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9561 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9562 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9563 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9564 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9565 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9566 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9567 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9568 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9569 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9570 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9571 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9572 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9573 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9574 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
9575 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
9578 void RSurf_ActiveWorldEntity(void)
9580 dp_model_t *model = r_refdef.scene.worldmodel;
9581 //if (rsurface.entity == r_refdef.scene.worldentity)
9583 rsurface.entity = r_refdef.scene.worldentity;
9584 rsurface.skeleton = NULL;
9585 rsurface.ent_skinnum = 0;
9586 rsurface.ent_qwskin = -1;
9587 rsurface.ent_shadertime = 0;
9588 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9589 if (rsurface.array_size < model->surfmesh.num_vertices)
9590 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9591 rsurface.matrix = identitymatrix;
9592 rsurface.inversematrix = identitymatrix;
9593 rsurface.matrixscale = 1;
9594 rsurface.inversematrixscale = 1;
9595 R_EntityMatrix(&identitymatrix);
9596 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9597 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9598 rsurface.fograngerecip = r_refdef.fograngerecip;
9599 rsurface.fogheightfade = r_refdef.fogheightfade;
9600 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9601 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9602 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9603 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9604 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9605 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9606 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9607 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9608 rsurface.colormod[3] = 1;
9609 VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
9610 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9611 rsurface.frameblend[0].lerp = 1;
9612 rsurface.ent_alttextures = false;
9613 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9614 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9615 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9616 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9617 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9618 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9619 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9620 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9621 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9622 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9623 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9624 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9625 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9626 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9627 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9628 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9629 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9630 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9631 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9632 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9633 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9634 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9635 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9636 rsurface.modelelement3i = model->surfmesh.data_element3i;
9637 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9638 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9639 rsurface.modelelement3s = model->surfmesh.data_element3s;
9640 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9641 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9642 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9643 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9644 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9645 rsurface.modelsurfaces = model->data_surfaces;
9646 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9647 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9648 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9649 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9650 rsurface.modelgeneratedvertex = false;
9651 rsurface.batchgeneratedvertex = false;
9652 rsurface.batchfirstvertex = 0;
9653 rsurface.batchnumvertices = 0;
9654 rsurface.batchfirsttriangle = 0;
9655 rsurface.batchnumtriangles = 0;
9656 rsurface.batchvertex3f = NULL;
9657 rsurface.batchvertex3f_vertexbuffer = NULL;
9658 rsurface.batchvertex3f_bufferoffset = 0;
9659 rsurface.batchsvector3f = NULL;
9660 rsurface.batchsvector3f_vertexbuffer = NULL;
9661 rsurface.batchsvector3f_bufferoffset = 0;
9662 rsurface.batchtvector3f = NULL;
9663 rsurface.batchtvector3f_vertexbuffer = NULL;
9664 rsurface.batchtvector3f_bufferoffset = 0;
9665 rsurface.batchnormal3f = NULL;
9666 rsurface.batchnormal3f_vertexbuffer = NULL;
9667 rsurface.batchnormal3f_bufferoffset = 0;
9668 rsurface.batchlightmapcolor4f = NULL;
9669 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9670 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9671 rsurface.batchtexcoordtexture2f = NULL;
9672 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9673 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9674 rsurface.batchtexcoordlightmap2f = NULL;
9675 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9676 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9677 rsurface.batchvertexmesh = NULL;
9678 rsurface.batchvertexmeshbuffer = NULL;
9679 rsurface.batchvertexposition = NULL;
9680 rsurface.batchvertexpositionbuffer = NULL;
9681 rsurface.batchelement3i = NULL;
9682 rsurface.batchelement3i_indexbuffer = NULL;
9683 rsurface.batchelement3i_bufferoffset = 0;
9684 rsurface.batchelement3s = NULL;
9685 rsurface.batchelement3s_indexbuffer = NULL;
9686 rsurface.batchelement3s_bufferoffset = 0;
9687 rsurface.passcolor4f = NULL;
9688 rsurface.passcolor4f_vertexbuffer = NULL;
9689 rsurface.passcolor4f_bufferoffset = 0;
9692 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9694 dp_model_t *model = ent->model;
9695 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9697 rsurface.entity = (entity_render_t *)ent;
9698 rsurface.skeleton = ent->skeleton;
9699 rsurface.ent_skinnum = ent->skinnum;
9700 rsurface.ent_qwskin = (ent->entitynumber <= cl.maxclients && ent->entitynumber >= 1 && cls.protocol == PROTOCOL_QUAKEWORLD && cl.scores[ent->entitynumber - 1].qw_skin[0] && !strcmp(ent->model->name, "progs/player.mdl")) ? (ent->entitynumber - 1) : -1;
9701 rsurface.ent_shadertime = ent->shadertime;
9702 rsurface.ent_flags = ent->flags;
9703 if (rsurface.array_size < model->surfmesh.num_vertices)
9704 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9705 rsurface.matrix = ent->matrix;
9706 rsurface.inversematrix = ent->inversematrix;
9707 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9708 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9709 R_EntityMatrix(&rsurface.matrix);
9710 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9711 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9712 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9713 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9714 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9715 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9716 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
9717 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
9718 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
9719 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
9720 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
9721 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
9722 rsurface.colormod[3] = ent->alpha;
9723 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
9724 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
9725 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
9726 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9727 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9728 if (ent->model->brush.submodel && !prepass)
9730 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
9731 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
9733 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
9735 if (ent->animcache_vertex3f && !r_framedata_failed)
9737 rsurface.modelvertex3f = ent->animcache_vertex3f;
9738 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
9739 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
9740 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
9741 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
9742 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
9743 rsurface.modelvertexposition = ent->animcache_vertexposition;
9744 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
9746 else if (wanttangents)
9748 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9749 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
9750 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
9751 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9752 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
9753 rsurface.modelvertexmesh = NULL;
9754 rsurface.modelvertexmeshbuffer = NULL;
9755 rsurface.modelvertexposition = NULL;
9756 rsurface.modelvertexpositionbuffer = NULL;
9758 else if (wantnormals)
9760 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9761 rsurface.modelsvector3f = NULL;
9762 rsurface.modeltvector3f = NULL;
9763 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9764 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
9765 rsurface.modelvertexmesh = NULL;
9766 rsurface.modelvertexmeshbuffer = NULL;
9767 rsurface.modelvertexposition = NULL;
9768 rsurface.modelvertexpositionbuffer = NULL;
9772 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9773 rsurface.modelsvector3f = NULL;
9774 rsurface.modeltvector3f = NULL;
9775 rsurface.modelnormal3f = NULL;
9776 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
9777 rsurface.modelvertexmesh = NULL;
9778 rsurface.modelvertexmeshbuffer = NULL;
9779 rsurface.modelvertexposition = NULL;
9780 rsurface.modelvertexpositionbuffer = NULL;
9782 rsurface.modelvertex3f_vertexbuffer = 0;
9783 rsurface.modelvertex3f_bufferoffset = 0;
9784 rsurface.modelsvector3f_vertexbuffer = 0;
9785 rsurface.modelsvector3f_bufferoffset = 0;
9786 rsurface.modeltvector3f_vertexbuffer = 0;
9787 rsurface.modeltvector3f_bufferoffset = 0;
9788 rsurface.modelnormal3f_vertexbuffer = 0;
9789 rsurface.modelnormal3f_bufferoffset = 0;
9790 rsurface.modelgeneratedvertex = true;
9794 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9795 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9796 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9797 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9798 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9799 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9800 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9801 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9802 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9803 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9804 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9805 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9806 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9807 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9808 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9809 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9810 rsurface.modelgeneratedvertex = false;
9812 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9813 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9814 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9815 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9816 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9817 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9818 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9819 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9820 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9821 rsurface.modelelement3i = model->surfmesh.data_element3i;
9822 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9823 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9824 rsurface.modelelement3s = model->surfmesh.data_element3s;
9825 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9826 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9827 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9828 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9829 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9830 rsurface.modelsurfaces = model->data_surfaces;
9831 rsurface.batchgeneratedvertex = false;
9832 rsurface.batchfirstvertex = 0;
9833 rsurface.batchnumvertices = 0;
9834 rsurface.batchfirsttriangle = 0;
9835 rsurface.batchnumtriangles = 0;
9836 rsurface.batchvertex3f = NULL;
9837 rsurface.batchvertex3f_vertexbuffer = NULL;
9838 rsurface.batchvertex3f_bufferoffset = 0;
9839 rsurface.batchsvector3f = NULL;
9840 rsurface.batchsvector3f_vertexbuffer = NULL;
9841 rsurface.batchsvector3f_bufferoffset = 0;
9842 rsurface.batchtvector3f = NULL;
9843 rsurface.batchtvector3f_vertexbuffer = NULL;
9844 rsurface.batchtvector3f_bufferoffset = 0;
9845 rsurface.batchnormal3f = NULL;
9846 rsurface.batchnormal3f_vertexbuffer = NULL;
9847 rsurface.batchnormal3f_bufferoffset = 0;
9848 rsurface.batchlightmapcolor4f = NULL;
9849 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9850 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9851 rsurface.batchtexcoordtexture2f = NULL;
9852 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9853 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9854 rsurface.batchtexcoordlightmap2f = NULL;
9855 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9856 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9857 rsurface.batchvertexmesh = NULL;
9858 rsurface.batchvertexmeshbuffer = NULL;
9859 rsurface.batchvertexposition = NULL;
9860 rsurface.batchvertexpositionbuffer = NULL;
9861 rsurface.batchelement3i = NULL;
9862 rsurface.batchelement3i_indexbuffer = NULL;
9863 rsurface.batchelement3i_bufferoffset = 0;
9864 rsurface.batchelement3s = NULL;
9865 rsurface.batchelement3s_indexbuffer = NULL;
9866 rsurface.batchelement3s_bufferoffset = 0;
9867 rsurface.passcolor4f = NULL;
9868 rsurface.passcolor4f_vertexbuffer = NULL;
9869 rsurface.passcolor4f_bufferoffset = 0;
9872 void RSurf_ActiveCustomEntity(const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, int entflags, double shadertime, float r, float g, float b, float a, int numvertices, const float *vertex3f, const float *texcoord2f, const float *normal3f, const float *svector3f, const float *tvector3f, const float *color4f, int numtriangles, const int *element3i, const unsigned short *element3s, qboolean wantnormals, qboolean wanttangents)
9876 rsurface.entity = r_refdef.scene.worldentity;
9877 rsurface.skeleton = NULL;
9878 rsurface.ent_skinnum = 0;
9879 rsurface.ent_qwskin = -1;
9880 rsurface.ent_shadertime = shadertime;
9881 rsurface.ent_flags = entflags;
9882 rsurface.modelnumvertices = numvertices;
9883 rsurface.modelnumtriangles = numtriangles;
9884 if (rsurface.array_size < rsurface.modelnumvertices)
9885 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
9886 rsurface.matrix = *matrix;
9887 rsurface.inversematrix = *inversematrix;
9888 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9889 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9890 R_EntityMatrix(&rsurface.matrix);
9891 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9892 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9893 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9894 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9895 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9896 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9897 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9898 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9899 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9900 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9901 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9902 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
9903 VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
9904 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9905 rsurface.frameblend[0].lerp = 1;
9906 rsurface.ent_alttextures = false;
9907 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9908 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9911 rsurface.modelvertex3f = vertex3f;
9912 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
9913 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
9914 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
9916 else if (wantnormals)
9918 rsurface.modelvertex3f = vertex3f;
9919 rsurface.modelsvector3f = NULL;
9920 rsurface.modeltvector3f = NULL;
9921 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
9925 rsurface.modelvertex3f = vertex3f;
9926 rsurface.modelsvector3f = NULL;
9927 rsurface.modeltvector3f = NULL;
9928 rsurface.modelnormal3f = NULL;
9930 rsurface.modelvertexmesh = NULL;
9931 rsurface.modelvertexmeshbuffer = NULL;
9932 rsurface.modelvertexposition = NULL;
9933 rsurface.modelvertexpositionbuffer = NULL;
9934 rsurface.modelvertex3f_vertexbuffer = 0;
9935 rsurface.modelvertex3f_bufferoffset = 0;
9936 rsurface.modelsvector3f_vertexbuffer = 0;
9937 rsurface.modelsvector3f_bufferoffset = 0;
9938 rsurface.modeltvector3f_vertexbuffer = 0;
9939 rsurface.modeltvector3f_bufferoffset = 0;
9940 rsurface.modelnormal3f_vertexbuffer = 0;
9941 rsurface.modelnormal3f_bufferoffset = 0;
9942 rsurface.modelgeneratedvertex = true;
9943 rsurface.modellightmapcolor4f = color4f;
9944 rsurface.modellightmapcolor4f_vertexbuffer = 0;
9945 rsurface.modellightmapcolor4f_bufferoffset = 0;
9946 rsurface.modeltexcoordtexture2f = texcoord2f;
9947 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
9948 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
9949 rsurface.modeltexcoordlightmap2f = NULL;
9950 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
9951 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
9952 rsurface.modelelement3i = element3i;
9953 rsurface.modelelement3i_indexbuffer = NULL;
9954 rsurface.modelelement3i_bufferoffset = 0;
9955 rsurface.modelelement3s = element3s;
9956 rsurface.modelelement3s_indexbuffer = NULL;
9957 rsurface.modelelement3s_bufferoffset = 0;
9958 rsurface.modellightmapoffsets = NULL;
9959 rsurface.modelsurfaces = NULL;
9960 rsurface.batchgeneratedvertex = false;
9961 rsurface.batchfirstvertex = 0;
9962 rsurface.batchnumvertices = 0;
9963 rsurface.batchfirsttriangle = 0;
9964 rsurface.batchnumtriangles = 0;
9965 rsurface.batchvertex3f = NULL;
9966 rsurface.batchvertex3f_vertexbuffer = NULL;
9967 rsurface.batchvertex3f_bufferoffset = 0;
9968 rsurface.batchsvector3f = NULL;
9969 rsurface.batchsvector3f_vertexbuffer = NULL;
9970 rsurface.batchsvector3f_bufferoffset = 0;
9971 rsurface.batchtvector3f = NULL;
9972 rsurface.batchtvector3f_vertexbuffer = NULL;
9973 rsurface.batchtvector3f_bufferoffset = 0;
9974 rsurface.batchnormal3f = NULL;
9975 rsurface.batchnormal3f_vertexbuffer = NULL;
9976 rsurface.batchnormal3f_bufferoffset = 0;
9977 rsurface.batchlightmapcolor4f = NULL;
9978 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9979 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9980 rsurface.batchtexcoordtexture2f = NULL;
9981 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9982 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9983 rsurface.batchtexcoordlightmap2f = NULL;
9984 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9985 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9986 rsurface.batchvertexmesh = NULL;
9987 rsurface.batchvertexmeshbuffer = NULL;
9988 rsurface.batchvertexposition = NULL;
9989 rsurface.batchvertexpositionbuffer = NULL;
9990 rsurface.batchelement3i = NULL;
9991 rsurface.batchelement3i_indexbuffer = NULL;
9992 rsurface.batchelement3i_bufferoffset = 0;
9993 rsurface.batchelement3s = NULL;
9994 rsurface.batchelement3s_indexbuffer = NULL;
9995 rsurface.batchelement3s_bufferoffset = 0;
9996 rsurface.passcolor4f = NULL;
9997 rsurface.passcolor4f_vertexbuffer = NULL;
9998 rsurface.passcolor4f_bufferoffset = 0;
10000 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10002 if ((wantnormals || wanttangents) && !normal3f)
10004 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10005 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10007 if (wanttangents && !svector3f)
10009 Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
10010 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10011 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10015 // now convert arrays into vertexmesh structs
10016 for (i = 0;i < numvertices;i++)
10018 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
10019 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
10020 if (rsurface.modelsvector3f)
10021 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
10022 if (rsurface.modeltvector3f)
10023 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
10024 if (rsurface.modelnormal3f)
10025 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
10026 if (rsurface.modellightmapcolor4f)
10027 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
10028 if (rsurface.modeltexcoordtexture2f)
10029 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
10030 if (rsurface.modeltexcoordlightmap2f)
10031 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
10035 float RSurf_FogPoint(const float *v)
10037 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10038 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10039 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10040 float FogHeightFade = r_refdef.fogheightfade;
10042 unsigned int fogmasktableindex;
10043 if (r_refdef.fogplaneviewabove)
10044 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10046 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10047 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10048 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10051 float RSurf_FogVertex(const float *v)
10053 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10054 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10055 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10056 float FogHeightFade = rsurface.fogheightfade;
10058 unsigned int fogmasktableindex;
10059 if (r_refdef.fogplaneviewabove)
10060 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10062 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10063 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10064 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10067 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10070 for (i = 0;i < numelements;i++)
10071 outelement3i[i] = inelement3i[i] + adjust;
10074 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10075 extern cvar_t gl_vbo;
10076 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10084 int surfacefirsttriangle;
10085 int surfacenumtriangles;
10086 int surfacefirstvertex;
10087 int surfaceendvertex;
10088 int surfacenumvertices;
10089 int surfaceadjustvertex;
10093 qboolean dynamicvertex;
10097 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10098 float waveparms[4];
10099 q3shaderinfo_deform_t *deform;
10100 const msurface_t *surface, *firstsurface;
10101 r_vertexposition_t *vertexposition;
10102 r_vertexmesh_t *vertexmesh;
10103 if (!texturenumsurfaces)
10105 // find vertex range of this surface batch
10107 firstsurface = texturesurfacelist[0];
10108 firsttriangle = firstsurface->num_firsttriangle;
10110 firstvertex = endvertex = firstsurface->num_firstvertex;
10111 for (i = 0;i < texturenumsurfaces;i++)
10113 surface = texturesurfacelist[i];
10114 if (surface != firstsurface + i)
10116 surfacefirstvertex = surface->num_firstvertex;
10117 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10118 surfacenumtriangles = surface->num_triangles;
10119 if (firstvertex > surfacefirstvertex)
10120 firstvertex = surfacefirstvertex;
10121 if (endvertex < surfaceendvertex)
10122 endvertex = surfaceendvertex;
10123 numtriangles += surfacenumtriangles;
10128 // we now know the vertex range used, and if there are any gaps in it
10129 rsurface.batchfirstvertex = firstvertex;
10130 rsurface.batchnumvertices = endvertex - firstvertex;
10131 rsurface.batchfirsttriangle = firsttriangle;
10132 rsurface.batchnumtriangles = numtriangles;
10134 // this variable holds flags for which properties have been updated that
10135 // may require regenerating vertexmesh or vertexposition arrays...
10138 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10139 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
10140 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10142 switch (deform->deform)
10145 case Q3DEFORM_PROJECTIONSHADOW:
10146 case Q3DEFORM_TEXT0:
10147 case Q3DEFORM_TEXT1:
10148 case Q3DEFORM_TEXT2:
10149 case Q3DEFORM_TEXT3:
10150 case Q3DEFORM_TEXT4:
10151 case Q3DEFORM_TEXT5:
10152 case Q3DEFORM_TEXT6:
10153 case Q3DEFORM_TEXT7:
10154 case Q3DEFORM_NONE:
10156 case Q3DEFORM_AUTOSPRITE:
10157 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10158 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10160 case Q3DEFORM_AUTOSPRITE2:
10161 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10162 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10164 case Q3DEFORM_NORMAL:
10165 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10166 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10168 case Q3DEFORM_WAVE:
10169 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10170 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10172 case Q3DEFORM_BULGE:
10173 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10174 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10176 case Q3DEFORM_MOVE:
10177 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10178 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
10182 switch(rsurface.texture->tcgen.tcgen)
10185 case Q3TCGEN_TEXTURE:
10187 case Q3TCGEN_LIGHTMAP:
10188 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
10189 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
10191 case Q3TCGEN_VECTOR:
10192 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10193 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10195 case Q3TCGEN_ENVIRONMENT:
10196 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
10197 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10200 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10202 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10203 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10206 // check if any dynamic vertex processing must occur
10207 dynamicvertex = false;
10209 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10211 dynamicvertex = true;
10212 batchneed |= BATCHNEED_NOGAPS;
10213 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
10216 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10218 dynamicvertex = true;
10219 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10220 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
10223 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
10225 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
10226 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
10227 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
10228 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
10229 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
10230 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
10231 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
10234 // when the model data has no vertex buffer (dynamic mesh), we need to
10236 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
10237 batchneed |= BATCHNEED_NOGAPS;
10239 // if needsupdate, we have to do a dynamic vertex batch for sure
10240 if (needsupdate & batchneed)
10241 dynamicvertex = true;
10243 // see if we need to build vertexmesh from arrays
10244 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10245 dynamicvertex = true;
10247 // see if we need to build vertexposition from arrays
10248 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
10249 dynamicvertex = true;
10251 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
10252 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
10253 dynamicvertex = true;
10255 // if there is a chance of animated vertex colors, it's a dynamic batch
10256 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10257 dynamicvertex = true;
10259 rsurface.batchvertex3f = rsurface.modelvertex3f;
10260 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
10261 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10262 rsurface.batchsvector3f = rsurface.modelsvector3f;
10263 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
10264 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10265 rsurface.batchtvector3f = rsurface.modeltvector3f;
10266 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
10267 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10268 rsurface.batchnormal3f = rsurface.modelnormal3f;
10269 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
10270 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10271 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
10272 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
10273 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
10274 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
10275 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
10276 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
10277 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
10278 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
10279 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10280 rsurface.batchvertexposition = rsurface.modelvertexposition;
10281 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
10282 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
10283 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
10284 rsurface.batchelement3i = rsurface.modelelement3i;
10285 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
10286 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
10287 rsurface.batchelement3s = rsurface.modelelement3s;
10288 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
10289 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
10291 // if any dynamic vertex processing has to occur in software, we copy the
10292 // entire surface list together before processing to rebase the vertices
10293 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
10295 // if any gaps exist and we do not have a static vertex buffer, we have to
10296 // copy the surface list together to avoid wasting upload bandwidth on the
10297 // vertices in the gaps.
10299 // if gaps exist and we have a static vertex buffer, we still have to
10300 // combine the index buffer ranges into one dynamic index buffer.
10302 // in all cases we end up with data that can be drawn in one call.
10304 if (!dynamicvertex)
10306 // static vertex data, just set pointers...
10307 rsurface.batchgeneratedvertex = false;
10308 // if there are gaps, we want to build a combined index buffer,
10309 // otherwise use the original static buffer with an appropriate offset
10314 for (i = 0;i < texturenumsurfaces;i++)
10316 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10317 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10318 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
10319 numtriangles += surfacenumtriangles;
10321 rsurface.batchelement3i = rsurface.array_batchelement3i;
10322 rsurface.batchelement3i_indexbuffer = NULL;
10323 rsurface.batchelement3i_bufferoffset = 0;
10324 rsurface.batchelement3s = NULL;
10325 rsurface.batchelement3s_indexbuffer = NULL;
10326 rsurface.batchelement3s_bufferoffset = 0;
10327 if (endvertex <= 65536)
10329 rsurface.batchelement3s = rsurface.array_batchelement3s;
10330 for (i = 0;i < numtriangles*3;i++)
10331 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10333 rsurface.batchfirsttriangle = firsttriangle;
10334 rsurface.batchnumtriangles = numtriangles;
10339 // something needs software processing, do it for real...
10340 // we only directly handle interleaved array data in this case...
10341 rsurface.batchgeneratedvertex = true;
10343 // now copy the vertex data into a combined array and make an index array
10344 // (this is what Quake3 does all the time)
10345 //if (gaps || rsurface.batchfirstvertex)
10347 rsurface.batchvertexposition = NULL;
10348 rsurface.batchvertexpositionbuffer = NULL;
10349 rsurface.batchvertexmesh = NULL;
10350 rsurface.batchvertexmeshbuffer = NULL;
10351 rsurface.batchvertex3f = NULL;
10352 rsurface.batchvertex3f_vertexbuffer = NULL;
10353 rsurface.batchvertex3f_bufferoffset = 0;
10354 rsurface.batchsvector3f = NULL;
10355 rsurface.batchsvector3f_vertexbuffer = NULL;
10356 rsurface.batchsvector3f_bufferoffset = 0;
10357 rsurface.batchtvector3f = NULL;
10358 rsurface.batchtvector3f_vertexbuffer = NULL;
10359 rsurface.batchtvector3f_bufferoffset = 0;
10360 rsurface.batchnormal3f = NULL;
10361 rsurface.batchnormal3f_vertexbuffer = NULL;
10362 rsurface.batchnormal3f_bufferoffset = 0;
10363 rsurface.batchlightmapcolor4f = NULL;
10364 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10365 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10366 rsurface.batchtexcoordtexture2f = NULL;
10367 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10368 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10369 rsurface.batchtexcoordlightmap2f = NULL;
10370 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10371 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10372 rsurface.batchelement3i = rsurface.array_batchelement3i;
10373 rsurface.batchelement3i_indexbuffer = NULL;
10374 rsurface.batchelement3i_bufferoffset = 0;
10375 rsurface.batchelement3s = NULL;
10376 rsurface.batchelement3s_indexbuffer = NULL;
10377 rsurface.batchelement3s_bufferoffset = 0;
10378 // we'll only be setting up certain arrays as needed
10379 if (batchneed & BATCHNEED_VERTEXPOSITION)
10380 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10381 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10382 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10383 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10384 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10385 if (batchneed & BATCHNEED_ARRAY_NORMAL)
10386 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10387 if (batchneed & BATCHNEED_ARRAY_VECTOR)
10389 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10390 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10392 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
10393 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10394 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
10395 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10396 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
10397 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
10400 for (i = 0;i < texturenumsurfaces;i++)
10402 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
10403 surfacenumvertices = texturesurfacelist[i]->num_vertices;
10404 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10405 surfaceadjustvertex = numvertices - surfacefirstvertex;
10406 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10407 // copy only the data requested
10408 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
10409 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
10410 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
10411 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
10412 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
10414 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10415 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10416 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
10417 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10418 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
10420 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10421 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10423 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
10424 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
10425 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
10426 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10427 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
10428 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10430 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
10431 numvertices += surfacenumvertices;
10432 numtriangles += surfacenumtriangles;
10435 // generate a 16bit index array as well if possible
10436 // (in general, dynamic batches fit)
10437 if (numvertices <= 65536)
10439 rsurface.batchelement3s = rsurface.array_batchelement3s;
10440 for (i = 0;i < numtriangles*3;i++)
10441 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10444 // since we've copied everything, the batch now starts at 0
10445 rsurface.batchfirstvertex = 0;
10446 rsurface.batchnumvertices = numvertices;
10447 rsurface.batchfirsttriangle = 0;
10448 rsurface.batchnumtriangles = numtriangles;
10451 // q1bsp surfaces rendered in vertex color mode have to have colors
10452 // calculated based on lightstyles
10453 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10455 // generate color arrays for the surfaces in this list
10459 const int *offsets;
10460 const unsigned char *lm;
10462 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10463 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10464 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10465 for (i = 0;i < texturenumsurfaces;i++)
10467 surface = texturesurfacelist[i];
10468 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
10469 surfacenumvertices = surface->num_vertices;
10470 if (surface->lightmapinfo->samples)
10472 for (j = 0;j < surfacenumvertices;j++)
10474 lm = surface->lightmapinfo->samples + offsets[j];
10475 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
10476 VectorScale(lm, scale, c);
10477 if (surface->lightmapinfo->styles[1] != 255)
10479 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
10481 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
10482 VectorMA(c, scale, lm, c);
10483 if (surface->lightmapinfo->styles[2] != 255)
10486 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
10487 VectorMA(c, scale, lm, c);
10488 if (surface->lightmapinfo->styles[3] != 255)
10491 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
10492 VectorMA(c, scale, lm, c);
10499 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, min(c[0], 255) * (1.0f / 255.0f), min(c[1], 255) * (1.0f / 255.0f), min(c[2], 255) * (1.0f / 255.0f), 1);
10505 for (j = 0;j < surfacenumvertices;j++)
10507 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
10514 // if vertices are deformed (sprite flares and things in maps, possibly
10515 // water waves, bulges and other deformations), modify the copied vertices
10517 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10519 switch (deform->deform)
10522 case Q3DEFORM_PROJECTIONSHADOW:
10523 case Q3DEFORM_TEXT0:
10524 case Q3DEFORM_TEXT1:
10525 case Q3DEFORM_TEXT2:
10526 case Q3DEFORM_TEXT3:
10527 case Q3DEFORM_TEXT4:
10528 case Q3DEFORM_TEXT5:
10529 case Q3DEFORM_TEXT6:
10530 case Q3DEFORM_TEXT7:
10531 case Q3DEFORM_NONE:
10533 case Q3DEFORM_AUTOSPRITE:
10534 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10535 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10536 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10537 VectorNormalize(newforward);
10538 VectorNormalize(newright);
10539 VectorNormalize(newup);
10540 // a single autosprite surface can contain multiple sprites...
10541 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10543 VectorClear(center);
10544 for (i = 0;i < 4;i++)
10545 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10546 VectorScale(center, 0.25f, center);
10547 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
10548 VectorCopy(rsurface.batchsvector3f + 3*j, right);
10549 VectorCopy(rsurface.batchtvector3f + 3*j, up);
10550 for (i = 0;i < 4;i++)
10552 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
10553 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
10556 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10557 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10558 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10559 rsurface.batchvertex3f_vertexbuffer = NULL;
10560 rsurface.batchvertex3f_bufferoffset = 0;
10561 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10562 rsurface.batchsvector3f_vertexbuffer = NULL;
10563 rsurface.batchsvector3f_bufferoffset = 0;
10564 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10565 rsurface.batchtvector3f_vertexbuffer = NULL;
10566 rsurface.batchtvector3f_bufferoffset = 0;
10567 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10568 rsurface.batchnormal3f_vertexbuffer = NULL;
10569 rsurface.batchnormal3f_bufferoffset = 0;
10571 case Q3DEFORM_AUTOSPRITE2:
10572 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10573 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10574 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10575 VectorNormalize(newforward);
10576 VectorNormalize(newright);
10577 VectorNormalize(newup);
10579 const float *v1, *v2;
10589 memset(shortest, 0, sizeof(shortest));
10590 // a single autosprite surface can contain multiple sprites...
10591 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10593 VectorClear(center);
10594 for (i = 0;i < 4;i++)
10595 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10596 VectorScale(center, 0.25f, center);
10597 // find the two shortest edges, then use them to define the
10598 // axis vectors for rotating around the central axis
10599 for (i = 0;i < 6;i++)
10601 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
10602 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
10603 l = VectorDistance2(v1, v2);
10604 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10605 if (v1[2] != v2[2])
10606 l += (1.0f / 1024.0f);
10607 if (shortest[0].length2 > l || i == 0)
10609 shortest[1] = shortest[0];
10610 shortest[0].length2 = l;
10611 shortest[0].v1 = v1;
10612 shortest[0].v2 = v2;
10614 else if (shortest[1].length2 > l || i == 1)
10616 shortest[1].length2 = l;
10617 shortest[1].v1 = v1;
10618 shortest[1].v2 = v2;
10621 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10622 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10623 // this calculates the right vector from the shortest edge
10624 // and the up vector from the edge midpoints
10625 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10626 VectorNormalize(right);
10627 VectorSubtract(end, start, up);
10628 VectorNormalize(up);
10629 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10630 VectorSubtract(rsurface.localvieworigin, center, forward);
10631 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10632 VectorNegate(forward, forward);
10633 VectorReflect(forward, 0, up, forward);
10634 VectorNormalize(forward);
10635 CrossProduct(up, forward, newright);
10636 VectorNormalize(newright);
10637 // rotate the quad around the up axis vector, this is made
10638 // especially easy by the fact we know the quad is flat,
10639 // so we only have to subtract the center position and
10640 // measure distance along the right vector, and then
10641 // multiply that by the newright vector and add back the
10643 // we also need to subtract the old position to undo the
10644 // displacement from the center, which we do with a
10645 // DotProduct, the subtraction/addition of center is also
10646 // optimized into DotProducts here
10647 l = DotProduct(right, center);
10648 for (i = 0;i < 4;i++)
10650 v1 = rsurface.batchvertex3f + 3*(j+i);
10651 f = DotProduct(right, v1) - l;
10652 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
10656 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10657 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10658 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10659 rsurface.batchvertex3f_vertexbuffer = NULL;
10660 rsurface.batchvertex3f_bufferoffset = 0;
10661 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10662 rsurface.batchsvector3f_vertexbuffer = NULL;
10663 rsurface.batchsvector3f_bufferoffset = 0;
10664 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10665 rsurface.batchtvector3f_vertexbuffer = NULL;
10666 rsurface.batchtvector3f_bufferoffset = 0;
10667 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10668 rsurface.batchnormal3f_vertexbuffer = NULL;
10669 rsurface.batchnormal3f_bufferoffset = 0;
10671 case Q3DEFORM_NORMAL:
10672 // deform the normals to make reflections wavey
10673 for (j = 0;j < rsurface.batchnumvertices;j++)
10676 float *normal = rsurface.array_batchnormal3f + 3*j;
10677 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
10678 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10679 normal[1] = rsurface.batchnormal3f[j*3+1] + deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10680 normal[2] = rsurface.batchnormal3f[j*3+2] + deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10681 VectorNormalize(normal);
10683 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10684 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10685 rsurface.batchsvector3f_vertexbuffer = NULL;
10686 rsurface.batchsvector3f_bufferoffset = 0;
10687 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10688 rsurface.batchtvector3f_vertexbuffer = NULL;
10689 rsurface.batchtvector3f_bufferoffset = 0;
10690 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10691 rsurface.batchnormal3f_vertexbuffer = NULL;
10692 rsurface.batchnormal3f_bufferoffset = 0;
10694 case Q3DEFORM_WAVE:
10695 // deform vertex array to make wavey water and flags and such
10696 waveparms[0] = deform->waveparms[0];
10697 waveparms[1] = deform->waveparms[1];
10698 waveparms[2] = deform->waveparms[2];
10699 waveparms[3] = deform->waveparms[3];
10700 // this is how a divisor of vertex influence on deformation
10701 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10702 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10703 for (j = 0;j < rsurface.batchnumvertices;j++)
10705 // if the wavefunc depends on time, evaluate it per-vertex
10708 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
10709 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10711 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10713 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10714 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10715 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10716 rsurface.batchvertex3f_vertexbuffer = NULL;
10717 rsurface.batchvertex3f_bufferoffset = 0;
10718 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10719 rsurface.batchsvector3f_vertexbuffer = NULL;
10720 rsurface.batchsvector3f_bufferoffset = 0;
10721 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10722 rsurface.batchtvector3f_vertexbuffer = NULL;
10723 rsurface.batchtvector3f_bufferoffset = 0;
10724 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10725 rsurface.batchnormal3f_vertexbuffer = NULL;
10726 rsurface.batchnormal3f_bufferoffset = 0;
10728 case Q3DEFORM_BULGE:
10729 // deform vertex array to make the surface have moving bulges
10730 for (j = 0;j < rsurface.batchnumvertices;j++)
10732 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
10733 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10735 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10736 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10737 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10738 rsurface.batchvertex3f_vertexbuffer = NULL;
10739 rsurface.batchvertex3f_bufferoffset = 0;
10740 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10741 rsurface.batchsvector3f_vertexbuffer = NULL;
10742 rsurface.batchsvector3f_bufferoffset = 0;
10743 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10744 rsurface.batchtvector3f_vertexbuffer = NULL;
10745 rsurface.batchtvector3f_bufferoffset = 0;
10746 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10747 rsurface.batchnormal3f_vertexbuffer = NULL;
10748 rsurface.batchnormal3f_bufferoffset = 0;
10750 case Q3DEFORM_MOVE:
10751 // deform vertex array
10752 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10753 VectorScale(deform->parms, scale, waveparms);
10754 for (j = 0;j < rsurface.batchnumvertices;j++)
10755 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
10756 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10757 rsurface.batchvertex3f_vertexbuffer = NULL;
10758 rsurface.batchvertex3f_bufferoffset = 0;
10763 // generate texcoords based on the chosen texcoord source
10764 switch(rsurface.texture->tcgen.tcgen)
10767 case Q3TCGEN_TEXTURE:
10769 case Q3TCGEN_LIGHTMAP:
10770 if (rsurface.batchtexcoordlightmap2f)
10771 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
10772 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10773 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10774 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10776 case Q3TCGEN_VECTOR:
10777 for (j = 0;j < rsurface.batchnumvertices;j++)
10779 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
10780 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
10782 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10783 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10784 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10786 case Q3TCGEN_ENVIRONMENT:
10787 // make environment reflections using a spheremap
10788 for (j = 0;j < rsurface.batchnumvertices;j++)
10790 // identical to Q3A's method, but executed in worldspace so
10791 // carried models can be shiny too
10793 float viewer[3], d, reflected[3], worldreflected[3];
10795 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
10796 // VectorNormalize(viewer);
10798 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
10800 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
10801 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
10802 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
10803 // note: this is proportinal to viewer, so we can normalize later
10805 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10806 VectorNormalize(worldreflected);
10808 // note: this sphere map only uses world x and z!
10809 // so positive and negative y will LOOK THE SAME.
10810 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
10811 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
10813 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10814 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10815 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10818 // the only tcmod that needs software vertex processing is turbulent, so
10819 // check for it here and apply the changes if needed
10820 // and we only support that as the first one
10821 // (handling a mixture of turbulent and other tcmods would be problematic
10822 // without punting it entirely to a software path)
10823 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10825 amplitude = rsurface.texture->tcmods[0].parms[1];
10826 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10827 for (j = 0;j < rsurface.batchnumvertices;j++)
10829 rsurface.array_batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10830 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10832 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10833 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10834 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10837 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10839 // convert the modified arrays to vertex structs
10840 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10841 rsurface.batchvertexmeshbuffer = NULL;
10842 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
10843 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10844 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
10845 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
10846 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10847 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
10848 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
10850 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10852 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
10853 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
10856 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
10857 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10858 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
10859 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
10860 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10861 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
10862 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
10863 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10864 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
10867 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10869 // convert the modified arrays to vertex structs
10870 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10871 rsurface.batchvertexpositionbuffer = NULL;
10872 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
10873 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
10875 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
10876 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
10880 void RSurf_DrawBatch(void)
10882 R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
10885 static void RSurf_BindLightmapForBatch(void)
10887 switch(vid.renderpath)
10889 case RENDERPATH_CGGL:
10891 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture );CHECKCGERROR
10892 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, rsurface.deluxemaptexture);CHECKCGERROR
10895 case RENDERPATH_GL20:
10896 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture );
10897 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, rsurface.deluxemaptexture);
10899 case RENDERPATH_GL13:
10900 case RENDERPATH_GL11:
10901 R_Mesh_TexBind(0, rsurface.lightmaptexture);
10906 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
10908 // pick the closest matching water plane
10909 int planeindex, vertexindex, bestplaneindex = -1;
10913 r_waterstate_waterplane_t *p;
10915 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
10917 if(p->camera_entity != rsurface.texture->camera_entity)
10920 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
10921 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
10923 Matrix4x4_Transform(&rsurface.matrix, v, vert);
10924 d += fabs(PlaneDiff(vert, &p->plane));
10926 if (bestd > d || bestplaneindex < 0)
10929 bestplaneindex = planeindex;
10932 return bestplaneindex;
10935 static void RSurf_BindReflectionForBatch(int planeindex)
10937 // pick the closest matching water plane and bind textures
10938 r_waterstate_waterplane_t *bestp = planeindex >= 0 ? r_waterstate.waterplanes + planeindex : NULL;
10939 switch(vid.renderpath)
10941 case RENDERPATH_CGGL:
10943 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
10944 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
10945 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
10948 case RENDERPATH_GL20:
10949 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
10950 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
10951 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
10953 case RENDERPATH_GL13:
10954 case RENDERPATH_GL11:
10959 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
10962 for (i = 0;i < rsurface.batchnumvertices;i++)
10963 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
10964 rsurface.passcolor4f = rsurface.array_passcolor4f;
10965 rsurface.passcolor4f_vertexbuffer = 0;
10966 rsurface.passcolor4f_bufferoffset = 0;
10969 static void RSurf_DrawBatch_GL11_ApplyFog(void)
10976 if (rsurface.passcolor4f)
10978 // generate color arrays
10979 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
10981 f = RSurf_FogVertex(v);
10990 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
10992 f = RSurf_FogVertex(v);
10999 rsurface.passcolor4f = rsurface.array_passcolor4f;
11000 rsurface.passcolor4f_vertexbuffer = 0;
11001 rsurface.passcolor4f_bufferoffset = 0;
11004 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11011 if (!rsurface.passcolor4f)
11013 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11015 f = RSurf_FogVertex(v);
11016 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11017 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11018 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11021 rsurface.passcolor4f = rsurface.array_passcolor4f;
11022 rsurface.passcolor4f_vertexbuffer = 0;
11023 rsurface.passcolor4f_bufferoffset = 0;
11026 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11031 if (!rsurface.passcolor4f)
11033 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11040 rsurface.passcolor4f = rsurface.array_passcolor4f;
11041 rsurface.passcolor4f_vertexbuffer = 0;
11042 rsurface.passcolor4f_bufferoffset = 0;
11045 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11050 if (!rsurface.passcolor4f)
11052 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11054 c2[0] = c[0] + r_refdef.scene.ambient;
11055 c2[1] = c[1] + r_refdef.scene.ambient;
11056 c2[2] = c[2] + r_refdef.scene.ambient;
11059 rsurface.passcolor4f = rsurface.array_passcolor4f;
11060 rsurface.passcolor4f_vertexbuffer = 0;
11061 rsurface.passcolor4f_bufferoffset = 0;
11064 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11067 rsurface.passcolor4f = NULL;
11068 rsurface.passcolor4f_vertexbuffer = 0;
11069 rsurface.passcolor4f_bufferoffset = 0;
11070 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11071 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11072 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11073 GL_Color(r, g, b, a);
11074 RSurf_BindLightmapForBatch();
11078 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11080 // TODO: optimize applyfog && applycolor case
11081 // just apply fog if necessary, and tint the fog color array if necessary
11082 rsurface.passcolor4f = NULL;
11083 rsurface.passcolor4f_vertexbuffer = 0;
11084 rsurface.passcolor4f_bufferoffset = 0;
11085 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11086 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11087 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11088 GL_Color(r, g, b, a);
11092 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11095 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11096 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11097 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11098 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11099 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11100 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11101 GL_Color(r, g, b, a);
11105 static void RSurf_DrawBatch_GL11_ClampColor(void)
11110 if (!rsurface.passcolor4f)
11112 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11114 c2[0] = bound(0.0f, c1[0], 1.0f);
11115 c2[1] = bound(0.0f, c1[1], 1.0f);
11116 c2[2] = bound(0.0f, c1[2], 1.0f);
11117 c2[3] = bound(0.0f, c1[3], 1.0f);
11121 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11129 vec3_t ambientcolor;
11130 vec3_t diffusecolor;
11134 VectorCopy(rsurface.modellight_lightdir, lightdir);
11135 f = 0.5f * r_refdef.lightmapintensity;
11136 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11137 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11138 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11139 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11140 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11141 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11143 if (VectorLength2(diffusecolor) > 0)
11145 // q3-style directional shading
11146 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
11148 if ((f = DotProduct(n, lightdir)) > 0)
11149 VectorMA(ambientcolor, f, diffusecolor, c);
11151 VectorCopy(ambientcolor, c);
11158 rsurface.passcolor4f = rsurface.array_passcolor4f;
11159 rsurface.passcolor4f_vertexbuffer = 0;
11160 rsurface.passcolor4f_bufferoffset = 0;
11161 *applycolor = false;
11165 *r = ambientcolor[0];
11166 *g = ambientcolor[1];
11167 *b = ambientcolor[2];
11168 rsurface.passcolor4f = NULL;
11169 rsurface.passcolor4f_vertexbuffer = 0;
11170 rsurface.passcolor4f_bufferoffset = 0;
11174 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11176 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
11177 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11178 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11179 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11180 GL_Color(r, g, b, a);
11184 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
11190 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
11192 f = 1 - RSurf_FogVertex(v);
11200 void RSurf_SetupDepthAndCulling(void)
11202 // submodels are biased to avoid z-fighting with world surfaces that they
11203 // may be exactly overlapping (avoids z-fighting artifacts on certain
11204 // doors and things in Quake maps)
11205 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11206 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11207 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11208 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11211 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11213 // transparent sky would be ridiculous
11214 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11216 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11217 skyrenderlater = true;
11218 RSurf_SetupDepthAndCulling();
11219 GL_DepthMask(true);
11220 // LordHavoc: HalfLife maps have freaky skypolys so don't use
11221 // skymasking on them, and Quake3 never did sky masking (unlike
11222 // software Quake and software Quake2), so disable the sky masking
11223 // in Quake3 maps as it causes problems with q3map2 sky tricks,
11224 // and skymasking also looks very bad when noclipping outside the
11225 // level, so don't use it then either.
11226 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11228 R_Mesh_ResetTextureState();
11229 if (skyrendermasked)
11231 R_SetupShader_DepthOrShadow();
11232 // depth-only (masking)
11233 GL_ColorMask(0,0,0,0);
11234 // just to make sure that braindead drivers don't draw
11235 // anything despite that colormask...
11236 GL_BlendFunc(GL_ZERO, GL_ONE);
11237 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11238 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11242 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11244 GL_BlendFunc(GL_ONE, GL_ZERO);
11245 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
11246 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11247 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11250 if (skyrendermasked)
11251 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11253 R_Mesh_ResetTextureState();
11254 GL_Color(1, 1, 1, 1);
11257 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11258 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11259 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11261 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11265 // render screenspace normalmap to texture
11266 GL_DepthMask(true);
11267 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist);
11272 // bind lightmap texture
11274 // water/refraction/reflection/camera surfaces have to be handled specially
11275 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
11277 int start, end, startplaneindex;
11278 for (start = 0;start < texturenumsurfaces;start = end)
11280 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
11281 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
11283 // now that we have a batch using the same planeindex, render it
11284 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11286 // render water or distortion background
11287 GL_DepthMask(true);
11288 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start);
11289 RSurf_BindReflectionForBatch(startplaneindex);
11290 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11291 RSurf_BindLightmapForBatch();
11293 // blend surface on top
11294 GL_DepthMask(false);
11295 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11298 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
11300 // render surface with reflection texture as input
11301 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11302 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11303 RSurf_BindReflectionForBatch(startplaneindex);
11304 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11305 RSurf_BindLightmapForBatch();
11312 // render surface batch normally
11313 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11314 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
11315 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11316 RSurf_BindLightmapForBatch();
11320 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11322 // OpenGL 1.3 path - anything not completely ancient
11323 qboolean applycolor;
11326 const texturelayer_t *layer;
11327 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11328 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11330 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11333 int layertexrgbscale;
11334 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11336 if (layerindex == 0)
11337 GL_AlphaTest(true);
11340 GL_AlphaTest(false);
11341 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11344 GL_DepthMask(layer->depthmask && writedepth);
11345 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11346 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11348 layertexrgbscale = 4;
11349 VectorScale(layer->color, 0.25f, layercolor);
11351 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11353 layertexrgbscale = 2;
11354 VectorScale(layer->color, 0.5f, layercolor);
11358 layertexrgbscale = 1;
11359 VectorScale(layer->color, 1.0f, layercolor);
11361 layercolor[3] = layer->color[3];
11362 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11363 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11364 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11365 switch (layer->type)
11367 case TEXTURELAYERTYPE_LITTEXTURE:
11368 // single-pass lightmapped texture with 2x rgbscale
11369 R_Mesh_TexBind(0, r_texture_white);
11370 R_Mesh_TexMatrix(0, NULL);
11371 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11372 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11373 R_Mesh_TexBind(1, layer->texture);
11374 R_Mesh_TexMatrix(1, &layer->texmatrix);
11375 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11376 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11377 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11378 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11379 else if (rsurface.uselightmaptexture)
11380 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11382 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11384 case TEXTURELAYERTYPE_TEXTURE:
11385 // singletexture unlit texture with transparency support
11386 R_Mesh_TexBind(0, layer->texture);
11387 R_Mesh_TexMatrix(0, &layer->texmatrix);
11388 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11389 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11390 R_Mesh_TexBind(1, 0);
11391 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11392 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11394 case TEXTURELAYERTYPE_FOG:
11395 // singletexture fogging
11396 if (layer->texture)
11398 R_Mesh_TexBind(0, layer->texture);
11399 R_Mesh_TexMatrix(0, &layer->texmatrix);
11400 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11401 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11405 R_Mesh_TexBind(0, 0);
11406 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11408 R_Mesh_TexBind(1, 0);
11409 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11410 // generate a color array for the fog pass
11411 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11412 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
11416 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11420 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11422 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11423 GL_AlphaTest(false);
11427 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11429 // OpenGL 1.1 - crusty old voodoo path
11432 const texturelayer_t *layer;
11433 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11434 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11436 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11438 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11440 if (layerindex == 0)
11441 GL_AlphaTest(true);
11444 GL_AlphaTest(false);
11445 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11448 GL_DepthMask(layer->depthmask && writedepth);
11449 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11450 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11451 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11452 switch (layer->type)
11454 case TEXTURELAYERTYPE_LITTEXTURE:
11455 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11457 // two-pass lit texture with 2x rgbscale
11458 // first the lightmap pass
11459 R_Mesh_TexBind(0, r_texture_white);
11460 R_Mesh_TexMatrix(0, NULL);
11461 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11462 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11463 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11464 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
11465 else if (rsurface.uselightmaptexture)
11466 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
11468 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
11469 // then apply the texture to it
11470 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11471 R_Mesh_TexBind(0, layer->texture);
11472 R_Mesh_TexMatrix(0, &layer->texmatrix);
11473 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11474 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11475 RSurf_DrawBatch_GL11_Unlit(layer->color[0] * 0.5f, layer->color[1] * 0.5f, layer->color[2] * 0.5f, layer->color[3], layer->color[0] != 2 || layer->color[1] != 2 || layer->color[2] != 2 || layer->color[3] != 1, false);
11479 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11480 R_Mesh_TexBind(0, layer->texture);
11481 R_Mesh_TexMatrix(0, &layer->texmatrix);
11482 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11483 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11484 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11485 RSurf_DrawBatch_GL11_VertexShade(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
11487 RSurf_DrawBatch_GL11_VertexColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
11490 case TEXTURELAYERTYPE_TEXTURE:
11491 // singletexture unlit texture with transparency support
11492 R_Mesh_TexBind(0, layer->texture);
11493 R_Mesh_TexMatrix(0, &layer->texmatrix);
11494 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11495 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11496 RSurf_DrawBatch_GL11_Unlit(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
11498 case TEXTURELAYERTYPE_FOG:
11499 // singletexture fogging
11500 if (layer->texture)
11502 R_Mesh_TexBind(0, layer->texture);
11503 R_Mesh_TexMatrix(0, &layer->texmatrix);
11504 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11505 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11509 R_Mesh_TexBind(0, 0);
11510 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11512 // generate a color array for the fog pass
11513 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11514 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
11518 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11522 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11524 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11525 GL_AlphaTest(false);
11529 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11533 r_vertexgeneric_t *batchvertex;
11536 GL_AlphaTest(false);
11537 R_Mesh_ResetTextureState();
11538 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11540 if(rsurface.texture && rsurface.texture->currentskinframe)
11542 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11543 c[3] *= rsurface.texture->currentalpha;
11553 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11555 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11556 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11557 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11560 // brighten it up (as texture value 127 means "unlit")
11561 c[0] *= 2 * r_refdef.view.colorscale;
11562 c[1] *= 2 * r_refdef.view.colorscale;
11563 c[2] *= 2 * r_refdef.view.colorscale;
11565 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11566 c[3] *= r_wateralpha.value;
11568 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11570 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11571 GL_DepthMask(false);
11573 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11575 GL_BlendFunc(GL_ONE, GL_ONE);
11576 GL_DepthMask(false);
11578 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11580 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11581 GL_DepthMask(false);
11583 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11585 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11586 GL_DepthMask(false);
11590 GL_BlendFunc(GL_ONE, GL_ZERO);
11591 GL_DepthMask(writedepth);
11594 if (r_showsurfaces.integer == 3)
11596 rsurface.passcolor4f = NULL;
11598 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11600 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11602 rsurface.passcolor4f = NULL;
11603 rsurface.passcolor4f_vertexbuffer = 0;
11604 rsurface.passcolor4f_bufferoffset = 0;
11606 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11608 qboolean applycolor = true;
11611 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11613 r_refdef.lightmapintensity = 1;
11614 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
11615 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11619 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11621 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11622 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11623 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11626 if(!rsurface.passcolor4f)
11627 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
11629 RSurf_DrawBatch_GL11_ApplyAmbient();
11630 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
11631 if(r_refdef.fogenabled)
11632 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
11633 RSurf_DrawBatch_GL11_ClampColor();
11635 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
11636 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11639 else if (!r_refdef.view.showdebug)
11641 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11642 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11643 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11645 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11646 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
11648 R_Mesh_PrepareVertices_Generic_Unlock();
11651 else if (r_showsurfaces.integer == 4)
11653 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11654 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11655 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11657 unsigned char c = vi << 3;
11658 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11659 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
11661 R_Mesh_PrepareVertices_Generic_Unlock();
11664 else if (r_showsurfaces.integer == 2)
11667 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11668 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
11669 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
11671 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
11672 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
11673 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
11674 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
11675 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
11676 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
11677 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
11679 R_Mesh_PrepareVertices_Generic_Unlock();
11680 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
11684 int texturesurfaceindex;
11686 const msurface_t *surface;
11687 unsigned char surfacecolor4ub[4];
11688 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11689 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
11691 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11693 surface = texturesurfacelist[texturesurfaceindex];
11694 k = (int)(((size_t)surface) / sizeof(msurface_t));
11695 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
11696 for (j = 0;j < surface->num_vertices;j++)
11698 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11699 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
11703 R_Mesh_PrepareVertices_Generic_Unlock();
11708 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11711 RSurf_SetupDepthAndCulling();
11712 if (r_showsurfaces.integer)
11714 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11717 switch (vid.renderpath)
11719 case RENDERPATH_GL20:
11720 case RENDERPATH_CGGL:
11721 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11723 case RENDERPATH_GL13:
11724 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11726 case RENDERPATH_GL11:
11727 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11733 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11736 RSurf_SetupDepthAndCulling();
11737 if (r_showsurfaces.integer)
11739 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11742 switch (vid.renderpath)
11744 case RENDERPATH_GL20:
11745 case RENDERPATH_CGGL:
11746 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11748 case RENDERPATH_GL13:
11749 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11751 case RENDERPATH_GL11:
11752 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11758 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11761 int texturenumsurfaces, endsurface;
11762 texture_t *texture;
11763 const msurface_t *surface;
11764 #define MAXBATCH_TRANSPARENTSURFACES 256
11765 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11767 // if the model is static it doesn't matter what value we give for
11768 // wantnormals and wanttangents, so this logic uses only rules applicable
11769 // to a model, knowing that they are meaningless otherwise
11770 if (ent == r_refdef.scene.worldentity)
11771 RSurf_ActiveWorldEntity();
11772 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11773 RSurf_ActiveModelEntity(ent, false, false, false);
11776 switch (vid.renderpath)
11778 case RENDERPATH_GL20:
11779 case RENDERPATH_CGGL:
11780 RSurf_ActiveModelEntity(ent, true, true, false);
11782 case RENDERPATH_GL13:
11783 case RENDERPATH_GL11:
11784 RSurf_ActiveModelEntity(ent, true, false, false);
11789 if (r_transparentdepthmasking.integer)
11791 qboolean setup = false;
11792 for (i = 0;i < numsurfaces;i = j)
11795 surface = rsurface.modelsurfaces + surfacelist[i];
11796 texture = surface->texture;
11797 rsurface.texture = R_GetCurrentTexture(texture);
11798 rsurface.lightmaptexture = NULL;
11799 rsurface.deluxemaptexture = NULL;
11800 rsurface.uselightmaptexture = false;
11801 // scan ahead until we find a different texture
11802 endsurface = min(i + 1024, numsurfaces);
11803 texturenumsurfaces = 0;
11804 texturesurfacelist[texturenumsurfaces++] = surface;
11805 for (;j < endsurface;j++)
11807 surface = rsurface.modelsurfaces + surfacelist[j];
11808 if (texture != surface->texture)
11810 texturesurfacelist[texturenumsurfaces++] = surface;
11812 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11814 // render the range of surfaces as depth
11818 GL_ColorMask(0,0,0,0);
11820 GL_DepthTest(true);
11821 GL_BlendFunc(GL_ONE, GL_ZERO);
11822 GL_DepthMask(true);
11823 GL_AlphaTest(false);
11824 R_Mesh_ResetTextureState();
11825 R_SetupShader_DepthOrShadow();
11827 RSurf_SetupDepthAndCulling();
11828 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11829 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11833 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11836 for (i = 0;i < numsurfaces;i = j)
11839 surface = rsurface.modelsurfaces + surfacelist[i];
11840 texture = surface->texture;
11841 rsurface.texture = R_GetCurrentTexture(texture);
11842 rsurface.lightmaptexture = surface->lightmaptexture;
11843 rsurface.deluxemaptexture = surface->deluxemaptexture;
11844 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11845 // scan ahead until we find a different texture
11846 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
11847 texturenumsurfaces = 0;
11848 texturesurfacelist[texturenumsurfaces++] = surface;
11849 for (;j < endsurface;j++)
11851 surface = rsurface.modelsurfaces + surfacelist[j];
11852 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
11854 texturesurfacelist[texturenumsurfaces++] = surface;
11856 // render the range of surfaces
11857 if (ent == r_refdef.scene.worldentity)
11858 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11860 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11862 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11863 GL_AlphaTest(false);
11866 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
11868 // transparent surfaces get pushed off into the transparent queue
11869 int surfacelistindex;
11870 const msurface_t *surface;
11871 vec3_t tempcenter, center;
11872 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
11874 surface = texturesurfacelist[surfacelistindex];
11875 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
11876 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
11877 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
11878 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
11879 if (queueentity->transparent_offset) // transparent offset
11881 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
11882 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
11883 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
11885 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
11889 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11891 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
11893 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
11895 RSurf_SetupDepthAndCulling();
11896 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11897 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11901 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
11903 const entity_render_t *queueentity = r_refdef.scene.worldentity;
11906 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
11909 if (!rsurface.texture->currentnumlayers)
11911 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11912 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11914 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11916 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
11917 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
11918 else if (!rsurface.texture->currentnumlayers)
11920 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
11922 // in the deferred case, transparent surfaces were queued during prepass
11923 if (!r_shadow_usingdeferredprepass)
11924 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11928 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
11929 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
11934 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
11937 texture_t *texture;
11938 // break the surface list down into batches by texture and use of lightmapping
11939 for (i = 0;i < numsurfaces;i = j)
11942 // texture is the base texture pointer, rsurface.texture is the
11943 // current frame/skin the texture is directing us to use (for example
11944 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
11945 // use skin 1 instead)
11946 texture = surfacelist[i]->texture;
11947 rsurface.texture = R_GetCurrentTexture(texture);
11948 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
11949 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
11950 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
11951 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
11953 // if this texture is not the kind we want, skip ahead to the next one
11954 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
11958 // simply scan ahead until we find a different texture or lightmap state
11959 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
11961 // render the range of surfaces
11962 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
11966 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
11970 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
11973 if (!rsurface.texture->currentnumlayers)
11975 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11976 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11978 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11980 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
11981 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
11982 else if (!rsurface.texture->currentnumlayers)
11984 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
11986 // in the deferred case, transparent surfaces were queued during prepass
11987 if (!r_shadow_usingdeferredprepass)
11988 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11992 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
11993 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
11998 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12001 texture_t *texture;
12002 // break the surface list down into batches by texture and use of lightmapping
12003 for (i = 0;i < numsurfaces;i = j)
12006 // texture is the base texture pointer, rsurface.texture is the
12007 // current frame/skin the texture is directing us to use (for example
12008 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12009 // use skin 1 instead)
12010 texture = surfacelist[i]->texture;
12011 rsurface.texture = R_GetCurrentTexture(texture);
12012 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12013 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12014 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12015 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12017 // if this texture is not the kind we want, skip ahead to the next one
12018 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12022 // simply scan ahead until we find a different texture or lightmap state
12023 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12025 // render the range of surfaces
12026 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12030 float locboxvertex3f[6*4*3] =
12032 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12033 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12034 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12035 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12036 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12037 1,0,0, 0,0,0, 0,1,0, 1,1,0
12040 unsigned short locboxelements[6*2*3] =
12045 12,13,14, 12,14,15,
12046 16,17,18, 16,18,19,
12050 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12053 cl_locnode_t *loc = (cl_locnode_t *)ent;
12055 float vertex3f[6*4*3];
12057 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12058 GL_DepthMask(false);
12059 GL_DepthRange(0, 1);
12060 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12061 GL_DepthTest(true);
12062 GL_CullFace(GL_NONE);
12063 R_EntityMatrix(&identitymatrix);
12065 R_Mesh_ResetTextureState();
12067 i = surfacelist[0];
12068 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12069 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12070 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12071 surfacelist[0] < 0 ? 0.5f : 0.125f);
12073 if (VectorCompare(loc->mins, loc->maxs))
12075 VectorSet(size, 2, 2, 2);
12076 VectorMA(loc->mins, -0.5f, size, mins);
12080 VectorCopy(loc->mins, mins);
12081 VectorSubtract(loc->maxs, loc->mins, size);
12084 for (i = 0;i < 6*4*3;)
12085 for (j = 0;j < 3;j++, i++)
12086 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12088 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
12089 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12090 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
12093 void R_DrawLocs(void)
12096 cl_locnode_t *loc, *nearestloc;
12098 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12099 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12101 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12102 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12106 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12108 if (decalsystem->decals)
12109 Mem_Free(decalsystem->decals);
12110 memset(decalsystem, 0, sizeof(*decalsystem));
12113 static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
12116 tridecal_t *decals;
12119 // expand or initialize the system
12120 if (decalsystem->maxdecals <= decalsystem->numdecals)
12122 decalsystem_t old = *decalsystem;
12123 qboolean useshortelements;
12124 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12125 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12126 decalsystem->decals = Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12127 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12128 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12129 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12130 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12131 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12132 if (decalsystem->numdecals)
12133 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12135 Mem_Free(old.decals);
12136 for (i = 0;i < decalsystem->maxdecals*3;i++)
12137 decalsystem->element3i[i] = i;
12138 if (useshortelements)
12139 for (i = 0;i < decalsystem->maxdecals*3;i++)
12140 decalsystem->element3s[i] = i;
12143 // grab a decal and search for another free slot for the next one
12144 decals = decalsystem->decals;
12145 decal = decalsystem->decals + (i = decalsystem->freedecal++);
12146 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12148 decalsystem->freedecal = i;
12149 if (decalsystem->numdecals <= i)
12150 decalsystem->numdecals = i + 1;
12152 // initialize the decal
12154 decal->triangleindex = triangleindex;
12155 decal->surfaceindex = surfaceindex;
12156 decal->decalsequence = decalsequence;
12157 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12158 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12159 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12160 decal->color4ub[0][3] = 255;
12161 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12162 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12163 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12164 decal->color4ub[1][3] = 255;
12165 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12166 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12167 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12168 decal->color4ub[2][3] = 255;
12169 decal->vertex3f[0][0] = v0[0];
12170 decal->vertex3f[0][1] = v0[1];
12171 decal->vertex3f[0][2] = v0[2];
12172 decal->vertex3f[1][0] = v1[0];
12173 decal->vertex3f[1][1] = v1[1];
12174 decal->vertex3f[1][2] = v1[2];
12175 decal->vertex3f[2][0] = v2[0];
12176 decal->vertex3f[2][1] = v2[1];
12177 decal->vertex3f[2][2] = v2[2];
12178 decal->texcoord2f[0][0] = t0[0];
12179 decal->texcoord2f[0][1] = t0[1];
12180 decal->texcoord2f[1][0] = t1[0];
12181 decal->texcoord2f[1][1] = t1[1];
12182 decal->texcoord2f[2][0] = t2[0];
12183 decal->texcoord2f[2][1] = t2[1];
12186 extern cvar_t cl_decals_bias;
12187 extern cvar_t cl_decals_models;
12188 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12189 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12191 matrix4x4_t projection;
12192 decalsystem_t *decalsystem;
12195 const float *vertex3f;
12196 const msurface_t *surface;
12197 const msurface_t *surfaces;
12198 const int *surfacelist;
12199 const texture_t *texture;
12201 int numsurfacelist;
12202 int surfacelistindex;
12209 float localorigin[3];
12210 float localnormal[3];
12211 float localmins[3];
12212 float localmaxs[3];
12218 float planes[6][4];
12220 float points[2][9][3];
12224 decalsystem = &ent->decalsystem;
12225 model = ent->model;
12226 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12228 R_DecalSystem_Reset(&ent->decalsystem);
12232 if (!model->brush.data_nodes && !cl_decals_models.integer)
12234 if (decalsystem->model)
12235 R_DecalSystem_Reset(decalsystem);
12239 if (decalsystem->model != model)
12240 R_DecalSystem_Reset(decalsystem);
12241 decalsystem->model = model;
12243 RSurf_ActiveModelEntity(ent, false, false, false);
12245 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12246 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12247 VectorNormalize(localnormal);
12248 localsize = worldsize*rsurface.inversematrixscale;
12249 localmins[0] = localorigin[0] - localsize;
12250 localmins[1] = localorigin[1] - localsize;
12251 localmins[2] = localorigin[2] - localsize;
12252 localmaxs[0] = localorigin[0] + localsize;
12253 localmaxs[1] = localorigin[1] + localsize;
12254 localmaxs[2] = localorigin[2] + localsize;
12256 //VectorCopy(localnormal, planes[4]);
12257 //VectorVectors(planes[4], planes[2], planes[0]);
12258 AnglesFromVectors(angles, localnormal, NULL, false);
12259 AngleVectors(angles, planes[0], planes[2], planes[4]);
12260 VectorNegate(planes[0], planes[1]);
12261 VectorNegate(planes[2], planes[3]);
12262 VectorNegate(planes[4], planes[5]);
12263 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12264 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12265 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12266 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12267 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12268 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12273 matrix4x4_t forwardprojection;
12274 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12275 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12280 float projectionvector[4][3];
12281 VectorScale(planes[0], ilocalsize, projectionvector[0]);
12282 VectorScale(planes[2], ilocalsize, projectionvector[1]);
12283 VectorScale(planes[4], ilocalsize, projectionvector[2]);
12284 projectionvector[0][0] = planes[0][0] * ilocalsize;
12285 projectionvector[0][1] = planes[1][0] * ilocalsize;
12286 projectionvector[0][2] = planes[2][0] * ilocalsize;
12287 projectionvector[1][0] = planes[0][1] * ilocalsize;
12288 projectionvector[1][1] = planes[1][1] * ilocalsize;
12289 projectionvector[1][2] = planes[2][1] * ilocalsize;
12290 projectionvector[2][0] = planes[0][2] * ilocalsize;
12291 projectionvector[2][1] = planes[1][2] * ilocalsize;
12292 projectionvector[2][2] = planes[2][2] * ilocalsize;
12293 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12294 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12295 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12296 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12300 dynamic = model->surfmesh.isanimated;
12301 vertex3f = rsurface.modelvertex3f;
12302 numsurfacelist = model->nummodelsurfaces;
12303 surfacelist = model->sortedmodelsurfaces;
12304 surfaces = model->data_surfaces;
12305 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12307 surfaceindex = surfacelist[surfacelistindex];
12308 surface = surfaces + surfaceindex;
12309 // check cull box first because it rejects more than any other check
12310 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12312 // skip transparent surfaces
12313 texture = surface->texture;
12314 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12316 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12318 numtriangles = surface->num_triangles;
12319 for (triangleindex = 0, e = rsurface.modelelement3i + 3*surface->num_firsttriangle;triangleindex < numtriangles;triangleindex++, e += 3)
12321 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12323 index = 3*e[cornerindex];
12324 VectorCopy(vertex3f + index, v[cornerindex]);
12327 //TriangleNormal(v[0], v[1], v[2], normal);
12328 //if (DotProduct(normal, localnormal) < 0.0f)
12330 // clip by each of the box planes formed from the projection matrix
12331 // if anything survives, we emit the decal
12332 numpoints = PolygonF_Clip(3 , v[0] , planes[0][0], planes[0][1], planes[0][2], planes[0][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12335 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[1][0], planes[1][1], planes[1][2], planes[1][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
12338 numpoints = PolygonF_Clip(numpoints, points[0][0], planes[2][0], planes[2][1], planes[2][2], planes[2][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12341 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[3][0], planes[3][1], planes[3][2], planes[3][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
12344 numpoints = PolygonF_Clip(numpoints, points[0][0], planes[4][0], planes[4][1], planes[4][2], planes[4][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12347 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[5][0], planes[5][1], planes[5][2], planes[5][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), v[0]);
12350 // some part of the triangle survived, so we have to accept it...
12353 // dynamic always uses the original triangle
12355 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12357 index = 3*e[cornerindex];
12358 VectorCopy(vertex3f + index, v[cornerindex]);
12361 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12363 // convert vertex positions to texcoords
12364 Matrix4x4_Transform(&projection, v[cornerindex], temp);
12365 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12366 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12367 // calculate distance fade from the projection origin
12368 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12369 f = bound(0.0f, f, 1.0f);
12370 c[cornerindex][0] = r * f;
12371 c[cornerindex][1] = g * f;
12372 c[cornerindex][2] = b * f;
12373 c[cornerindex][3] = 1.0f;
12374 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12377 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex+surface->num_firsttriangle, surfaceindex, decalsequence);
12379 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12380 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
12385 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12386 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12388 int renderentityindex;
12389 float worldmins[3];
12390 float worldmaxs[3];
12391 entity_render_t *ent;
12393 if (!cl_decals_newsystem.integer)
12396 worldmins[0] = worldorigin[0] - worldsize;
12397 worldmins[1] = worldorigin[1] - worldsize;
12398 worldmins[2] = worldorigin[2] - worldsize;
12399 worldmaxs[0] = worldorigin[0] + worldsize;
12400 worldmaxs[1] = worldorigin[1] + worldsize;
12401 worldmaxs[2] = worldorigin[2] + worldsize;
12403 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12405 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12407 ent = r_refdef.scene.entities[renderentityindex];
12408 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12411 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12415 typedef struct r_decalsystem_splatqueue_s
12417 vec3_t worldorigin;
12418 vec3_t worldnormal;
12424 r_decalsystem_splatqueue_t;
12426 int r_decalsystem_numqueued = 0;
12427 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12429 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
12431 r_decalsystem_splatqueue_t *queue;
12433 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12436 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12437 VectorCopy(worldorigin, queue->worldorigin);
12438 VectorCopy(worldnormal, queue->worldnormal);
12439 Vector4Set(queue->color, r, g, b, a);
12440 Vector4Set(queue->tcrange, s1, t1, s2, t2);
12441 queue->worldsize = worldsize;
12442 queue->decalsequence = cl.decalsequence++;
12445 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12448 r_decalsystem_splatqueue_t *queue;
12450 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12451 R_DecalSystem_ApplySplatEntities(queue->worldorigin, queue->worldnormal, queue->color[0], queue->color[1], queue->color[2], queue->color[3], queue->tcrange[0], queue->tcrange[1], queue->tcrange[2], queue->tcrange[3], queue->worldsize, queue->decalsequence);
12452 r_decalsystem_numqueued = 0;
12455 extern cvar_t cl_decals_max;
12456 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12459 decalsystem_t *decalsystem = &ent->decalsystem;
12466 if (!decalsystem->numdecals)
12469 if (r_showsurfaces.integer)
12472 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12474 R_DecalSystem_Reset(decalsystem);
12478 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12479 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12481 if (decalsystem->lastupdatetime)
12482 frametime = (cl.time - decalsystem->lastupdatetime);
12485 decalsystem->lastupdatetime = cl.time;
12486 decal = decalsystem->decals;
12487 numdecals = decalsystem->numdecals;
12489 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12491 if (decal->color4ub[0][3])
12493 decal->lived += frametime;
12494 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12496 memset(decal, 0, sizeof(*decal));
12497 if (decalsystem->freedecal > i)
12498 decalsystem->freedecal = i;
12502 decal = decalsystem->decals;
12503 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12506 // collapse the array by shuffling the tail decals into the gaps
12509 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12510 decalsystem->freedecal++;
12511 if (decalsystem->freedecal == numdecals)
12513 decal[decalsystem->freedecal] = decal[--numdecals];
12516 decalsystem->numdecals = numdecals;
12518 if (numdecals <= 0)
12520 // if there are no decals left, reset decalsystem
12521 R_DecalSystem_Reset(decalsystem);
12525 extern skinframe_t *decalskinframe;
12526 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12529 decalsystem_t *decalsystem = &ent->decalsystem;
12538 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12541 numdecals = decalsystem->numdecals;
12545 if (r_showsurfaces.integer)
12548 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12550 R_DecalSystem_Reset(decalsystem);
12554 // if the model is static it doesn't matter what value we give for
12555 // wantnormals and wanttangents, so this logic uses only rules applicable
12556 // to a model, knowing that they are meaningless otherwise
12557 if (ent == r_refdef.scene.worldentity)
12558 RSurf_ActiveWorldEntity();
12560 RSurf_ActiveModelEntity(ent, false, false, false);
12562 decalsystem->lastupdatetime = cl.time;
12563 decal = decalsystem->decals;
12565 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12567 // update vertex positions for animated models
12568 v3f = decalsystem->vertex3f;
12569 c4f = decalsystem->color4f;
12570 t2f = decalsystem->texcoord2f;
12571 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12573 if (!decal->color4ub[0][3])
12576 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12579 // update color values for fading decals
12580 if (decal->lived >= cl_decals_time.value)
12582 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12583 alpha *= (1.0f/255.0f);
12586 alpha = 1.0f/255.0f;
12588 c4f[ 0] = decal->color4ub[0][0] * alpha;
12589 c4f[ 1] = decal->color4ub[0][1] * alpha;
12590 c4f[ 2] = decal->color4ub[0][2] * alpha;
12592 c4f[ 4] = decal->color4ub[1][0] * alpha;
12593 c4f[ 5] = decal->color4ub[1][1] * alpha;
12594 c4f[ 6] = decal->color4ub[1][2] * alpha;
12596 c4f[ 8] = decal->color4ub[2][0] * alpha;
12597 c4f[ 9] = decal->color4ub[2][1] * alpha;
12598 c4f[10] = decal->color4ub[2][2] * alpha;
12601 t2f[0] = decal->texcoord2f[0][0];
12602 t2f[1] = decal->texcoord2f[0][1];
12603 t2f[2] = decal->texcoord2f[1][0];
12604 t2f[3] = decal->texcoord2f[1][1];
12605 t2f[4] = decal->texcoord2f[2][0];
12606 t2f[5] = decal->texcoord2f[2][1];
12608 // update vertex positions for animated models
12609 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
12611 e = rsurface.modelelement3i + 3*decal->triangleindex;
12612 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
12613 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
12614 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
12618 VectorCopy(decal->vertex3f[0], v3f);
12619 VectorCopy(decal->vertex3f[1], v3f + 3);
12620 VectorCopy(decal->vertex3f[2], v3f + 6);
12623 if (r_refdef.fogenabled)
12625 alpha = RSurf_FogVertex(v3f);
12626 VectorScale(c4f, alpha, c4f);
12627 alpha = RSurf_FogVertex(v3f + 3);
12628 VectorScale(c4f + 4, alpha, c4f + 4);
12629 alpha = RSurf_FogVertex(v3f + 6);
12630 VectorScale(c4f + 8, alpha, c4f + 8);
12641 r_refdef.stats.drawndecals += numtris;
12643 // now render the decals all at once
12644 // (this assumes they all use one particle font texture!)
12645 RSurf_ActiveCustomEntity(&rsurface.matrix, &rsurface.inversematrix, rsurface.ent_flags, rsurface.ent_shadertime, 1, 1, 1, 1, numdecals*3, decalsystem->vertex3f, decalsystem->texcoord2f, NULL, NULL, NULL, decalsystem->color4f, numtris, decalsystem->element3i, decalsystem->element3s, false, false);
12646 R_Mesh_ResetTextureState();
12647 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
12648 GL_DepthMask(false);
12649 GL_DepthRange(0, 1);
12650 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12651 GL_DepthTest(true);
12652 GL_CullFace(GL_NONE);
12653 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12654 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12655 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
12659 static void R_DrawModelDecals(void)
12663 // fade faster when there are too many decals
12664 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12665 for (i = 0;i < r_refdef.scene.numentities;i++)
12666 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12668 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12669 for (i = 0;i < r_refdef.scene.numentities;i++)
12670 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12671 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12673 R_DecalSystem_ApplySplatEntitiesQueue();
12675 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12676 for (i = 0;i < r_refdef.scene.numentities;i++)
12677 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12679 r_refdef.stats.totaldecals += numdecals;
12681 if (r_showsurfaces.integer)
12684 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12686 for (i = 0;i < r_refdef.scene.numentities;i++)
12688 if (!r_refdef.viewcache.entityvisible[i])
12690 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12691 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12695 extern cvar_t mod_collision_bih;
12696 void R_DrawDebugModel(void)
12698 entity_render_t *ent = rsurface.entity;
12699 int i, j, k, l, flagsmask;
12700 const msurface_t *surface;
12701 dp_model_t *model = ent->model;
12704 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12706 R_Mesh_ResetTextureState();
12707 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12708 GL_DepthRange(0, 1);
12709 GL_DepthTest(!r_showdisabledepthtest.integer);
12710 GL_DepthMask(false);
12711 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12713 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12717 qboolean cullbox = ent == r_refdef.scene.worldentity;
12718 const q3mbrush_t *brush;
12719 const bih_t *bih = &model->collision_bih;
12720 const bih_leaf_t *bihleaf;
12721 float vertex3f[3][3];
12722 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12724 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12726 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12728 switch (bihleaf->type)
12731 brush = model->brush.data_brushes + bihleaf->itemindex;
12732 if (brush->colbrushf && brush->colbrushf->numtriangles)
12734 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12735 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
12736 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
12739 case BIH_COLLISIONTRIANGLE:
12740 triangleindex = bihleaf->itemindex;
12741 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12742 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12743 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12744 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12745 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12746 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12748 case BIH_RENDERTRIANGLE:
12749 triangleindex = bihleaf->itemindex;
12750 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12751 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12752 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12753 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12754 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12755 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12761 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12763 if (r_showtris.integer || r_shownormals.integer)
12765 if (r_showdisabledepthtest.integer)
12767 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12768 GL_DepthMask(false);
12772 GL_BlendFunc(GL_ONE, GL_ZERO);
12773 GL_DepthMask(true);
12775 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12777 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12779 rsurface.texture = R_GetCurrentTexture(surface->texture);
12780 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12782 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
12783 if (r_showtris.value > 0)
12785 if (!rsurface.texture->currentlayers->depthmask)
12786 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12787 else if (ent == r_refdef.scene.worldentity)
12788 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12790 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12791 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12792 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
12794 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
12797 if (r_shownormals.value < 0)
12799 qglBegin(GL_LINES);
12800 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12802 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12803 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
12804 qglVertex3f(v[0], v[1], v[2]);
12805 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
12806 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12807 qglVertex3f(v[0], v[1], v[2]);
12812 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
12814 qglBegin(GL_LINES);
12815 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12817 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12818 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
12819 qglVertex3f(v[0], v[1], v[2]);
12820 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
12821 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12822 qglVertex3f(v[0], v[1], v[2]);
12826 qglBegin(GL_LINES);
12827 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12829 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12830 GL_Color(0, r_refdef.view.colorscale, 0, 1);
12831 qglVertex3f(v[0], v[1], v[2]);
12832 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
12833 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12834 qglVertex3f(v[0], v[1], v[2]);
12838 qglBegin(GL_LINES);
12839 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12841 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12842 GL_Color(0, 0, r_refdef.view.colorscale, 1);
12843 qglVertex3f(v[0], v[1], v[2]);
12844 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
12845 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12846 qglVertex3f(v[0], v[1], v[2]);
12853 rsurface.texture = NULL;
12857 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
12858 int r_maxsurfacelist = 0;
12859 const msurface_t **r_surfacelist = NULL;
12860 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
12862 int i, j, endj, flagsmask;
12863 dp_model_t *model = r_refdef.scene.worldmodel;
12864 msurface_t *surfaces;
12865 unsigned char *update;
12866 int numsurfacelist = 0;
12870 if (r_maxsurfacelist < model->num_surfaces)
12872 r_maxsurfacelist = model->num_surfaces;
12874 Mem_Free((msurface_t**)r_surfacelist);
12875 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
12878 RSurf_ActiveWorldEntity();
12880 surfaces = model->data_surfaces;
12881 update = model->brushq1.lightmapupdateflags;
12883 // update light styles on this submodel
12884 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
12886 model_brush_lightstyleinfo_t *style;
12887 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
12889 if (style->value != r_refdef.scene.lightstylevalue[style->style])
12891 int *list = style->surfacelist;
12892 style->value = r_refdef.scene.lightstylevalue[style->style];
12893 for (j = 0;j < style->numsurfaces;j++)
12894 update[list[j]] = true;
12899 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
12903 R_DrawDebugModel();
12904 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12908 rsurface.lightmaptexture = NULL;
12909 rsurface.deluxemaptexture = NULL;
12910 rsurface.uselightmaptexture = false;
12911 rsurface.texture = NULL;
12912 rsurface.rtlight = NULL;
12913 numsurfacelist = 0;
12914 // add visible surfaces to draw list
12915 for (i = 0;i < model->nummodelsurfaces;i++)
12917 j = model->sortedmodelsurfaces[i];
12918 if (r_refdef.viewcache.world_surfacevisible[j])
12919 r_surfacelist[numsurfacelist++] = surfaces + j;
12921 // update lightmaps if needed
12922 if (model->brushq1.firstrender)
12924 model->brushq1.firstrender = false;
12925 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
12927 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
12931 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
12932 if (r_refdef.viewcache.world_surfacevisible[j])
12934 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
12936 // don't do anything if there were no surfaces
12937 if (!numsurfacelist)
12939 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12942 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
12943 GL_AlphaTest(false);
12945 // add to stats if desired
12946 if (r_speeds.integer && !skysurfaces && !depthonly)
12948 r_refdef.stats.world_surfaces += numsurfacelist;
12949 for (j = 0;j < numsurfacelist;j++)
12950 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
12953 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12956 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
12958 int i, j, endj, flagsmask;
12959 dp_model_t *model = ent->model;
12960 msurface_t *surfaces;
12961 unsigned char *update;
12962 int numsurfacelist = 0;
12966 if (r_maxsurfacelist < model->num_surfaces)
12968 r_maxsurfacelist = model->num_surfaces;
12970 Mem_Free((msurface_t **)r_surfacelist);
12971 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
12974 // if the model is static it doesn't matter what value we give for
12975 // wantnormals and wanttangents, so this logic uses only rules applicable
12976 // to a model, knowing that they are meaningless otherwise
12977 if (ent == r_refdef.scene.worldentity)
12978 RSurf_ActiveWorldEntity();
12979 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12980 RSurf_ActiveModelEntity(ent, false, false, false);
12982 RSurf_ActiveModelEntity(ent, true, true, true);
12983 else if (depthonly)
12985 switch (vid.renderpath)
12987 case RENDERPATH_GL20:
12988 case RENDERPATH_CGGL:
12989 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
12991 case RENDERPATH_GL13:
12992 case RENDERPATH_GL11:
12993 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
12999 switch (vid.renderpath)
13001 case RENDERPATH_GL20:
13002 case RENDERPATH_CGGL:
13003 RSurf_ActiveModelEntity(ent, true, true, false);
13005 case RENDERPATH_GL13:
13006 case RENDERPATH_GL11:
13007 RSurf_ActiveModelEntity(ent, true, false, false);
13012 surfaces = model->data_surfaces;
13013 update = model->brushq1.lightmapupdateflags;
13015 // update light styles
13016 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13018 model_brush_lightstyleinfo_t *style;
13019 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13021 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13023 int *list = style->surfacelist;
13024 style->value = r_refdef.scene.lightstylevalue[style->style];
13025 for (j = 0;j < style->numsurfaces;j++)
13026 update[list[j]] = true;
13031 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13035 R_DrawDebugModel();
13036 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13040 rsurface.lightmaptexture = NULL;
13041 rsurface.deluxemaptexture = NULL;
13042 rsurface.uselightmaptexture = false;
13043 rsurface.texture = NULL;
13044 rsurface.rtlight = NULL;
13045 numsurfacelist = 0;
13046 // add visible surfaces to draw list
13047 for (i = 0;i < model->nummodelsurfaces;i++)
13048 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13049 // don't do anything if there were no surfaces
13050 if (!numsurfacelist)
13052 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13055 // update lightmaps if needed
13059 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13064 R_BuildLightMap(ent, surfaces + j);
13069 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13071 R_BuildLightMap(ent, surfaces + j);
13072 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13073 GL_AlphaTest(false);
13075 // add to stats if desired
13076 if (r_speeds.integer && !skysurfaces && !depthonly)
13078 r_refdef.stats.entities_surfaces += numsurfacelist;
13079 for (j = 0;j < numsurfacelist;j++)
13080 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13083 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13086 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13088 static texture_t texture;
13089 static msurface_t surface;
13090 const msurface_t *surfacelist = &surface;
13092 // fake enough texture and surface state to render this geometry
13094 texture.update_lastrenderframe = -1; // regenerate this texture
13095 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13096 texture.currentskinframe = skinframe;
13097 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13098 texture.offsetmapping = OFFSETMAPPING_OFF;
13099 texture.offsetscale = 1;
13100 texture.specularscalemod = 1;
13101 texture.specularpowermod = 1;
13103 surface.texture = &texture;
13104 surface.num_triangles = numtriangles;
13105 surface.num_firsttriangle = firsttriangle;
13106 surface.num_vertices = numvertices;
13107 surface.num_firstvertex = firstvertex;
13110 rsurface.texture = R_GetCurrentTexture(surface.texture);
13111 rsurface.lightmaptexture = NULL;
13112 rsurface.deluxemaptexture = NULL;
13113 rsurface.uselightmaptexture = false;
13114 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13117 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13119 static msurface_t surface;
13120 const msurface_t *surfacelist = &surface;
13122 // fake enough texture and surface state to render this geometry
13124 surface.texture = texture;
13125 surface.num_triangles = numtriangles;
13126 surface.num_firsttriangle = firsttriangle;
13127 surface.num_vertices = numvertices;
13128 surface.num_firstvertex = firstvertex;
13131 rsurface.texture = R_GetCurrentTexture(surface.texture);
13132 rsurface.lightmaptexture = NULL;
13133 rsurface.deluxemaptexture = NULL;
13134 rsurface.uselightmaptexture = false;
13135 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);