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_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
80 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
81 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
82 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
83 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
84 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)"};
85 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)"};
86 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
87 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
88 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
89 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
90 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
91 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
92 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
93 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."};
94 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
95 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
96 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
97 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."};
98 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
99 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
100 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
101 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
102 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"};
103 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"};
104 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
105 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
106 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
107 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
108 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"};
110 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
111 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
112 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
113 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
114 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
115 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
116 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
117 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
119 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)"};
120 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"};
122 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
123 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
124 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
125 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
126 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
128 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
129 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
130 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
132 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)"};
133 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
134 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
135 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
136 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
137 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)"};
138 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)"};
139 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)"};
140 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)"};
142 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)"};
143 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
144 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"};
145 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
146 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
148 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
149 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
150 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
151 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
153 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
154 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
155 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
156 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
157 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
158 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
159 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
161 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
162 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
163 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
164 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)"};
166 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"};
168 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"};
170 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
172 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
173 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"};
174 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
175 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
176 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
177 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
178 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)"};
180 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
182 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)"};
184 extern cvar_t v_glslgamma;
186 extern qboolean v_flipped_state;
188 static struct r_bloomstate_s
193 int bloomwidth, bloomheight;
195 int screentexturewidth, screentextureheight;
196 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
198 int bloomtexturewidth, bloomtextureheight;
199 rtexture_t *texture_bloom;
201 // arrays for rendering the screen passes
202 float screentexcoord2f[8];
203 float bloomtexcoord2f[8];
204 float offsettexcoord2f[8];
206 r_viewport_t viewport;
210 r_waterstate_t r_waterstate;
212 /// shadow volume bsp struct with automatically growing nodes buffer
215 rtexture_t *r_texture_blanknormalmap;
216 rtexture_t *r_texture_white;
217 rtexture_t *r_texture_grey128;
218 rtexture_t *r_texture_black;
219 rtexture_t *r_texture_notexture;
220 rtexture_t *r_texture_whitecube;
221 rtexture_t *r_texture_normalizationcube;
222 rtexture_t *r_texture_fogattenuation;
223 rtexture_t *r_texture_fogheighttexture;
224 rtexture_t *r_texture_gammaramps;
225 unsigned int r_texture_gammaramps_serial;
226 //rtexture_t *r_texture_fogintensity;
227 rtexture_t *r_texture_reflectcube;
229 // TODO: hash lookups?
230 typedef struct cubemapinfo_s
237 int r_texture_numcubemaps;
238 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
240 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
241 unsigned int r_numqueries;
242 unsigned int r_maxqueries;
244 typedef struct r_qwskincache_s
246 char name[MAX_QPATH];
247 skinframe_t *skinframe;
251 static r_qwskincache_t *r_qwskincache;
252 static int r_qwskincache_size;
254 /// vertex coordinates for a quad that covers the screen exactly
255 extern const float r_screenvertex3f[12];
256 const float r_screenvertex3f[12] =
264 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
267 for (i = 0;i < verts;i++)
278 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
281 for (i = 0;i < verts;i++)
291 // FIXME: move this to client?
294 if (gamemode == GAME_NEHAHRA)
296 Cvar_Set("gl_fogenable", "0");
297 Cvar_Set("gl_fogdensity", "0.2");
298 Cvar_Set("gl_fogred", "0.3");
299 Cvar_Set("gl_foggreen", "0.3");
300 Cvar_Set("gl_fogblue", "0.3");
302 r_refdef.fog_density = 0;
303 r_refdef.fog_red = 0;
304 r_refdef.fog_green = 0;
305 r_refdef.fog_blue = 0;
306 r_refdef.fog_alpha = 1;
307 r_refdef.fog_start = 0;
308 r_refdef.fog_end = 16384;
309 r_refdef.fog_height = 1<<30;
310 r_refdef.fog_fadedepth = 128;
311 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
314 static void R_BuildBlankTextures(void)
316 unsigned char data[4];
317 data[2] = 128; // normal X
318 data[1] = 128; // normal Y
319 data[0] = 255; // normal Z
320 data[3] = 128; // height
321 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
326 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
331 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
336 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
339 static void R_BuildNoTexture(void)
342 unsigned char pix[16][16][4];
343 // this makes a light grey/dark grey checkerboard texture
344 for (y = 0;y < 16;y++)
346 for (x = 0;x < 16;x++)
348 if ((y < 8) ^ (x < 8))
364 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
367 static void R_BuildWhiteCube(void)
369 unsigned char data[6*1*1*4];
370 memset(data, 255, sizeof(data));
371 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
374 static void R_BuildNormalizationCube(void)
378 vec_t s, t, intensity;
381 data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
382 for (side = 0;side < 6;side++)
384 for (y = 0;y < NORMSIZE;y++)
386 for (x = 0;x < NORMSIZE;x++)
388 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
389 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
424 intensity = 127.0f / sqrt(DotProduct(v, v));
425 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
426 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
427 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
428 data[((side*64+y)*64+x)*4+3] = 255;
432 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
436 static void R_BuildFogTexture(void)
440 unsigned char data1[FOGWIDTH][4];
441 //unsigned char data2[FOGWIDTH][4];
444 r_refdef.fogmasktable_start = r_refdef.fog_start;
445 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
446 r_refdef.fogmasktable_range = r_refdef.fogrange;
447 r_refdef.fogmasktable_density = r_refdef.fog_density;
449 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
450 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
452 d = (x * r - r_refdef.fogmasktable_start);
453 if(developer_extra.integer)
454 Con_DPrintf("%f ", d);
456 if (r_fog_exp2.integer)
457 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
459 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
460 if(developer_extra.integer)
461 Con_DPrintf(" : %f ", alpha);
462 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
463 if(developer_extra.integer)
464 Con_DPrintf(" = %f\n", alpha);
465 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
468 for (x = 0;x < FOGWIDTH;x++)
470 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
475 //data2[x][0] = 255 - b;
476 //data2[x][1] = 255 - b;
477 //data2[x][2] = 255 - b;
480 if (r_texture_fogattenuation)
482 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
483 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
487 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
488 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
492 static void R_BuildFogHeightTexture(void)
494 unsigned char *inpixels;
502 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
503 if (r_refdef.fogheighttexturename[0])
504 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
507 r_refdef.fog_height_tablesize = 0;
508 if (r_texture_fogheighttexture)
509 R_FreeTexture(r_texture_fogheighttexture);
510 r_texture_fogheighttexture = NULL;
511 if (r_refdef.fog_height_table2d)
512 Mem_Free(r_refdef.fog_height_table2d);
513 r_refdef.fog_height_table2d = NULL;
514 if (r_refdef.fog_height_table1d)
515 Mem_Free(r_refdef.fog_height_table1d);
516 r_refdef.fog_height_table1d = NULL;
520 r_refdef.fog_height_tablesize = size;
521 r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
522 r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
523 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
525 // LordHavoc: now the magic - what is that table2d for? it is a cooked
526 // average fog color table accounting for every fog layer between a point
527 // and the camera. (Note: attenuation is handled separately!)
528 for (y = 0;y < size;y++)
530 for (x = 0;x < size;x++)
536 for (j = x;j <= y;j++)
538 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
544 for (j = x;j >= y;j--)
546 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
551 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
552 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
553 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
554 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
557 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
560 //=======================================================================================================================================================
562 static const char *builtinshaderstring =
563 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
564 "// written by Forest 'LordHavoc' Hale\n"
565 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
567 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
570 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
571 "#define USELIGHTMAP\n"
573 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
574 "#define USEEYEVECTOR\n"
577 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
578 "# extension GL_ARB_texture_rectangle : enable\n"
581 "#ifdef USESHADOWMAP2D\n"
582 "# ifdef GL_EXT_gpu_shader4\n"
583 "# extension GL_EXT_gpu_shader4 : enable\n"
585 "# ifdef GL_ARB_texture_gather\n"
586 "# extension GL_ARB_texture_gather : enable\n"
588 "# ifdef GL_AMD_texture_texture4\n"
589 "# extension GL_AMD_texture_texture4 : enable\n"
594 "#ifdef USESHADOWMAPCUBE\n"
595 "# extension GL_EXT_gpu_shader4 : enable\n"
598 "//#ifdef USESHADOWSAMPLER\n"
599 "//# extension GL_ARB_shadow : enable\n"
602 "//#ifdef __GLSL_CG_DATA_TYPES\n"
603 "//# define myhalf half\n"
604 "//# define myhalf2 half2\n"
605 "//# define myhalf3 half3\n"
606 "//# define myhalf4 half4\n"
608 "# define myhalf float\n"
609 "# define myhalf2 vec2\n"
610 "# define myhalf3 vec3\n"
611 "# define myhalf4 vec4\n"
614 "#ifdef VERTEX_SHADER\n"
615 "uniform mat4 ModelViewProjectionMatrix;\n"
618 "#ifdef MODE_DEPTH_OR_SHADOW\n"
619 "#ifdef VERTEX_SHADER\n"
622 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
625 "#else // !MODE_DEPTH_ORSHADOW\n"
630 "#ifdef MODE_SHOWDEPTH\n"
631 "#ifdef VERTEX_SHADER\n"
634 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
635 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
639 "#ifdef FRAGMENT_SHADER\n"
642 " gl_FragColor = gl_Color;\n"
645 "#else // !MODE_SHOWDEPTH\n"
650 "#ifdef MODE_POSTPROCESS\n"
651 "varying vec2 TexCoord1;\n"
652 "varying vec2 TexCoord2;\n"
654 "#ifdef VERTEX_SHADER\n"
657 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
658 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
660 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
665 "#ifdef FRAGMENT_SHADER\n"
666 "uniform sampler2D Texture_First;\n"
668 "uniform sampler2D Texture_Second;\n"
670 "#ifdef USEGAMMARAMPS\n"
671 "uniform sampler2D Texture_GammaRamps;\n"
673 "#ifdef USESATURATION\n"
674 "uniform float Saturation;\n"
676 "#ifdef USEVIEWTINT\n"
677 "uniform vec4 ViewTintColor;\n"
679 "//uncomment these if you want to use them:\n"
680 "uniform vec4 UserVec1;\n"
681 "uniform vec4 UserVec2;\n"
682 "// uniform vec4 UserVec3;\n"
683 "// uniform vec4 UserVec4;\n"
684 "// uniform float ClientTime;\n"
685 "uniform vec2 PixelSize;\n"
688 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
690 " gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
692 "#ifdef USEVIEWTINT\n"
693 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
696 "#ifdef USEPOSTPROCESSING\n"
697 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
698 "// 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"
699 " float sobel = 1.0;\n"
700 " // vec2 ts = textureSize(Texture_First, 0);\n"
701 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
702 " vec2 px = PixelSize;\n"
703 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
704 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
705 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
706 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
707 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
708 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
709 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
710 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
711 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
712 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
713 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
714 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
715 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
716 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
717 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
718 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
719 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
720 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
721 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
722 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
723 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
724 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
725 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
726 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
727 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
728 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
729 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
730 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
731 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
732 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
733 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
734 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
737 "#ifdef USESATURATION\n"
738 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
739 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
740 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
741 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
744 "#ifdef USEGAMMARAMPS\n"
745 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
746 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
747 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
751 "#else // !MODE_POSTPROCESS\n"
756 "#ifdef MODE_GENERIC\n"
757 "#ifdef USEDIFFUSE\n"
758 "varying vec2 TexCoord1;\n"
760 "#ifdef USESPECULAR\n"
761 "varying vec2 TexCoord2;\n"
763 "#ifdef VERTEX_SHADER\n"
766 " gl_FrontColor = gl_Color;\n"
767 "#ifdef USEDIFFUSE\n"
768 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
770 "#ifdef USESPECULAR\n"
771 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
773 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
777 "#ifdef FRAGMENT_SHADER\n"
778 "#ifdef USEDIFFUSE\n"
779 "uniform sampler2D Texture_First;\n"
781 "#ifdef USESPECULAR\n"
782 "uniform sampler2D Texture_Second;\n"
787 " gl_FragColor = gl_Color;\n"
788 "#ifdef USEDIFFUSE\n"
789 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
792 "#ifdef USESPECULAR\n"
793 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
794 "# ifdef USECOLORMAPPING\n"
795 " gl_FragColor *= tex2;\n"
798 " gl_FragColor += tex2;\n"
800 "# ifdef USEVERTEXTEXTUREBLEND\n"
801 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
806 "#else // !MODE_GENERIC\n"
811 "#ifdef MODE_BLOOMBLUR\n"
812 "varying TexCoord;\n"
813 "#ifdef VERTEX_SHADER\n"
816 " gl_FrontColor = gl_Color;\n"
817 " TexCoord = gl_MultiTexCoord0.xy;\n"
818 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
822 "#ifdef FRAGMENT_SHADER\n"
823 "uniform sampler2D Texture_First;\n"
824 "uniform vec4 BloomBlur_Parameters;\n"
829 " vec2 tc = TexCoord;\n"
830 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
831 " tc += BloomBlur_Parameters.xy;\n"
832 " for (i = 1;i < SAMPLES;i++)\n"
834 " color += texture2D(Texture_First, tc).rgb;\n"
835 " tc += BloomBlur_Parameters.xy;\n"
837 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
840 "#else // !MODE_BLOOMBLUR\n"
841 "#ifdef MODE_REFRACTION\n"
842 "varying vec2 TexCoord;\n"
843 "varying vec4 ModelViewProjectionPosition;\n"
844 "uniform mat4 TexMatrix;\n"
845 "#ifdef VERTEX_SHADER\n"
849 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
850 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
851 " ModelViewProjectionPosition = gl_Position;\n"
855 "#ifdef FRAGMENT_SHADER\n"
856 "uniform sampler2D Texture_Normal;\n"
857 "uniform sampler2D Texture_Refraction;\n"
858 "uniform sampler2D Texture_Reflection;\n"
860 "uniform vec4 DistortScaleRefractReflect;\n"
861 "uniform vec4 ScreenScaleRefractReflect;\n"
862 "uniform vec4 ScreenCenterRefractReflect;\n"
863 "uniform vec4 RefractColor;\n"
864 "uniform vec4 ReflectColor;\n"
865 "uniform float ReflectFactor;\n"
866 "uniform float ReflectOffset;\n"
870 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
871 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
872 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
873 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
874 " // FIXME temporary hack to detect the case that the reflection\n"
875 " // gets blackened at edges due to leaving the area that contains actual\n"
877 " // Remove this 'ack once we have a better way to stop this thing from\n"
879 " float 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 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
882 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
883 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
884 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
887 "#else // !MODE_REFRACTION\n"
892 "#ifdef MODE_WATER\n"
893 "varying vec2 TexCoord;\n"
894 "varying vec3 EyeVector;\n"
895 "varying vec4 ModelViewProjectionPosition;\n"
896 "#ifdef VERTEX_SHADER\n"
897 "uniform vec3 EyePosition;\n"
898 "uniform mat4 TexMatrix;\n"
902 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
903 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
904 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
905 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
906 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
907 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
908 " ModelViewProjectionPosition = gl_Position;\n"
912 "#ifdef FRAGMENT_SHADER\n"
913 "uniform sampler2D Texture_Normal;\n"
914 "uniform sampler2D Texture_Refraction;\n"
915 "uniform sampler2D Texture_Reflection;\n"
917 "uniform vec4 DistortScaleRefractReflect;\n"
918 "uniform vec4 ScreenScaleRefractReflect;\n"
919 "uniform vec4 ScreenCenterRefractReflect;\n"
920 "uniform vec4 RefractColor;\n"
921 "uniform vec4 ReflectColor;\n"
922 "uniform float ReflectFactor;\n"
923 "uniform float ReflectOffset;\n"
927 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
928 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
929 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
930 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
931 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
932 " // FIXME temporary hack to detect the case that the reflection\n"
933 " // gets blackened at edges due to leaving the area that contains actual\n"
935 " // Remove this 'ack once we have a better way to stop this thing from\n"
937 " float 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 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
940 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
941 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\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 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
945 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
946 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
947 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
948 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
951 "#else // !MODE_WATER\n"
956 "// common definitions between vertex shader and fragment shader:\n"
958 "varying vec2 TexCoord;\n"
959 "#ifdef USEVERTEXTEXTUREBLEND\n"
960 "varying vec2 TexCoord2;\n"
962 "#ifdef USELIGHTMAP\n"
963 "varying vec2 TexCoordLightmap;\n"
966 "#ifdef MODE_LIGHTSOURCE\n"
967 "varying vec3 CubeVector;\n"
970 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
971 "varying vec3 LightVector;\n"
974 "#ifdef USEEYEVECTOR\n"
975 "varying vec3 EyeVector;\n"
978 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
981 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
982 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
983 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
984 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
987 "#ifdef USEREFLECTION\n"
988 "varying vec4 ModelViewProjectionPosition;\n"
990 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
991 "uniform vec3 LightPosition;\n"
992 "varying vec4 ModelViewPosition;\n"
995 "#ifdef MODE_LIGHTSOURCE\n"
996 "uniform vec3 LightPosition;\n"
998 "uniform vec3 EyePosition;\n"
999 "#ifdef MODE_LIGHTDIRECTION\n"
1000 "uniform vec3 LightDir;\n"
1002 "uniform vec4 FogPlane;\n"
1004 "#ifdef USESHADOWMAPORTHO\n"
1005 "varying vec3 ShadowMapTC;\n"
1012 "// 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"
1014 "// fragment shader specific:\n"
1015 "#ifdef FRAGMENT_SHADER\n"
1017 "uniform sampler2D Texture_Normal;\n"
1018 "uniform sampler2D Texture_Color;\n"
1019 "uniform sampler2D Texture_Gloss;\n"
1021 "uniform sampler2D Texture_Glow;\n"
1023 "#ifdef USEVERTEXTEXTUREBLEND\n"
1024 "uniform sampler2D Texture_SecondaryNormal;\n"
1025 "uniform sampler2D Texture_SecondaryColor;\n"
1026 "uniform sampler2D Texture_SecondaryGloss;\n"
1028 "uniform sampler2D Texture_SecondaryGlow;\n"
1031 "#ifdef USECOLORMAPPING\n"
1032 "uniform sampler2D Texture_Pants;\n"
1033 "uniform sampler2D Texture_Shirt;\n"
1036 "#ifdef USEFOGHEIGHTTEXTURE\n"
1037 "uniform sampler2D Texture_FogHeightTexture;\n"
1039 "uniform sampler2D Texture_FogMask;\n"
1041 "#ifdef USELIGHTMAP\n"
1042 "uniform sampler2D Texture_Lightmap;\n"
1044 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1045 "uniform sampler2D Texture_Deluxemap;\n"
1047 "#ifdef USEREFLECTION\n"
1048 "uniform sampler2D Texture_Reflection;\n"
1051 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1052 "uniform sampler2D Texture_ScreenDepth;\n"
1053 "uniform sampler2D Texture_ScreenNormalMap;\n"
1055 "#ifdef USEDEFERREDLIGHTMAP\n"
1056 "uniform sampler2D Texture_ScreenDiffuse;\n"
1057 "uniform sampler2D Texture_ScreenSpecular;\n"
1060 "uniform myhalf3 Color_Pants;\n"
1061 "uniform myhalf3 Color_Shirt;\n"
1062 "uniform myhalf3 FogColor;\n"
1065 "uniform float FogRangeRecip;\n"
1066 "uniform float FogPlaneViewDist;\n"
1067 "uniform float FogHeightFade;\n"
1068 "vec3 FogVertex(vec3 surfacecolor)\n"
1070 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1071 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1073 "#ifdef USEFOGHEIGHTTEXTURE\n"
1074 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1075 " fogfrac = fogheightpixel.a;\n"
1076 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1078 "# ifdef USEFOGOUTSIDE\n"
1079 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1081 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1083 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1088 "#ifdef USEOFFSETMAPPING\n"
1089 "uniform float OffsetMapping_Scale;\n"
1090 "vec2 OffsetMapping(vec2 TexCoord)\n"
1092 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1093 " // 14 sample relief mapping: linear search and then binary search\n"
1094 " // this basically steps forward a small amount repeatedly until it finds\n"
1095 " // itself inside solid, then jitters forward and back using decreasing\n"
1096 " // amounts to find the impact\n"
1097 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1098 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1099 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1100 " vec3 RT = vec3(TexCoord, 1);\n"
1101 " OffsetVector *= 0.1;\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);\n"
1110 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1111 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1112 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1113 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1114 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1115 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1118 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1119 " // this basically moves forward the full distance, and then backs up based\n"
1120 " // on height of samples\n"
1121 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1122 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1123 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1124 " TexCoord += OffsetVector;\n"
1125 " OffsetVector *= 0.333;\n"
1126 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1127 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1128 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1129 " return TexCoord;\n"
1132 "#endif // USEOFFSETMAPPING\n"
1134 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1135 "uniform sampler2D Texture_Attenuation;\n"
1136 "uniform samplerCube Texture_Cube;\n"
1139 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1141 "#ifdef USESHADOWMAPRECT\n"
1142 "# ifdef USESHADOWSAMPLER\n"
1143 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1145 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1149 "#ifdef USESHADOWMAP2D\n"
1150 "# ifdef USESHADOWSAMPLER\n"
1151 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1153 "uniform sampler2D Texture_ShadowMap2D;\n"
1157 "#ifdef USESHADOWMAPVSDCT\n"
1158 "uniform samplerCube Texture_CubeProjection;\n"
1161 "#ifdef USESHADOWMAPCUBE\n"
1162 "# ifdef USESHADOWSAMPLER\n"
1163 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1165 "uniform samplerCube Texture_ShadowMapCube;\n"
1169 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1170 "uniform vec2 ShadowMap_TextureScale;\n"
1171 "uniform vec4 ShadowMap_Parameters;\n"
1174 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1175 "# ifdef USESHADOWMAPORTHO\n"
1176 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1178 "# ifdef USESHADOWMAPVSDCT\n"
1179 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1181 " vec3 adir = abs(dir);\n"
1182 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1183 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1184 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1187 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1189 " vec3 adir = abs(dir);\n"
1190 " float ma = adir.z;\n"
1191 " vec4 proj = vec4(dir, 2.5);\n"
1192 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1193 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1194 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1195 " 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"
1199 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1201 "#ifdef USESHADOWMAPCUBE\n"
1202 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1204 " vec3 adir = abs(dir);\n"
1205 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1209 "# ifdef USESHADOWMAPRECT\n"
1210 "float ShadowMapCompare(vec3 dir)\n"
1212 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1214 "# ifdef USESHADOWSAMPLER\n"
1216 "# ifdef USESHADOWMAPPCF\n"
1217 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1218 " 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"
1220 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1225 "# ifdef USESHADOWMAPPCF\n"
1226 "# if USESHADOWMAPPCF > 1\n"
1227 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1228 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1229 " 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"
1230 " 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"
1231 " 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"
1232 " 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"
1233 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1234 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1236 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1237 " vec2 offset = fract(shadowmaptc.xy);\n"
1238 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1239 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1240 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1241 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1242 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1245 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1249 "# ifdef USESHADOWMAPORTHO\n"
1250 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1257 "# ifdef USESHADOWMAP2D\n"
1258 "float ShadowMapCompare(vec3 dir)\n"
1260 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1263 "# ifdef USESHADOWSAMPLER\n"
1264 "# ifdef USESHADOWMAPPCF\n"
1265 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1266 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1267 " 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"
1269 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1272 "# ifdef USESHADOWMAPPCF\n"
1273 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1274 "# ifdef GL_ARB_texture_gather\n"
1275 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1277 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1279 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1280 "# if USESHADOWMAPPCF > 1\n"
1281 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1282 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1283 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1284 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1285 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1286 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1287 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1288 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1289 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1290 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1291 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1292 " locols.yz += group2.ab;\n"
1293 " hicols.yz += group8.rg;\n"
1294 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1295 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1296 " mix(locols, hicols, offset.y);\n"
1297 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1298 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1299 " f = dot(cols, vec4(1.0/25.0));\n"
1301 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1302 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1303 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1304 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1305 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1306 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1307 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1310 "# ifdef GL_EXT_gpu_shader4\n"
1311 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1313 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1315 "# if USESHADOWMAPPCF > 1\n"
1316 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1317 " center *= ShadowMap_TextureScale;\n"
1318 " 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"
1319 " 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"
1320 " 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"
1321 " 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"
1322 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1323 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1325 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1326 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1327 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1328 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1329 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1330 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1334 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1337 "# ifdef USESHADOWMAPORTHO\n"
1338 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1345 "# ifdef USESHADOWMAPCUBE\n"
1346 "float ShadowMapCompare(vec3 dir)\n"
1348 " // apply depth texture cubemap as light filter\n"
1349 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1351 "# ifdef USESHADOWSAMPLER\n"
1352 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1354 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1359 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1360 "#endif // FRAGMENT_SHADER\n"
1365 "#ifdef MODE_DEFERREDGEOMETRY\n"
1366 "#ifdef VERTEX_SHADER\n"
1367 "uniform mat4 TexMatrix;\n"
1368 "#ifdef USEVERTEXTEXTUREBLEND\n"
1369 "uniform mat4 BackgroundTexMatrix;\n"
1371 "uniform mat4 ModelViewMatrix;\n"
1374 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1375 "#ifdef USEVERTEXTEXTUREBLEND\n"
1376 " gl_FrontColor = gl_Color;\n"
1377 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1380 " // transform unnormalized eye direction into tangent space\n"
1381 "#ifdef USEOFFSETMAPPING\n"
1382 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1383 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1384 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1385 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1388 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1389 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1390 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1391 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1393 "#endif // VERTEX_SHADER\n"
1395 "#ifdef FRAGMENT_SHADER\n"
1398 "#ifdef USEOFFSETMAPPING\n"
1399 " // apply offsetmapping\n"
1400 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1401 "#define TexCoord TexCoordOffset\n"
1404 "#ifdef USEALPHAKILL\n"
1405 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1409 "#ifdef USEVERTEXTEXTUREBLEND\n"
1410 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1411 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1412 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1413 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1416 "#ifdef USEVERTEXTEXTUREBLEND\n"
1417 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1418 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1420 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1421 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1424 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1426 "#endif // FRAGMENT_SHADER\n"
1427 "#else // !MODE_DEFERREDGEOMETRY\n"
1432 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1433 "#ifdef VERTEX_SHADER\n"
1434 "uniform mat4 ModelViewMatrix;\n"
1437 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1438 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1440 "#endif // VERTEX_SHADER\n"
1442 "#ifdef FRAGMENT_SHADER\n"
1443 "uniform mat4 ViewToLight;\n"
1444 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1445 "uniform vec2 ScreenToDepth;\n"
1446 "uniform myhalf3 DeferredColor_Ambient;\n"
1447 "uniform myhalf3 DeferredColor_Diffuse;\n"
1448 "#ifdef USESPECULAR\n"
1449 "uniform myhalf3 DeferredColor_Specular;\n"
1450 "uniform myhalf SpecularPower;\n"
1452 "uniform myhalf2 PixelToScreenTexCoord;\n"
1455 " // calculate viewspace pixel position\n"
1456 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1458 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1459 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1460 " // decode viewspace pixel normal\n"
1461 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1462 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1463 " // surfacenormal = pixel normal in viewspace\n"
1464 " // LightVector = pixel to light in viewspace\n"
1465 " // CubeVector = position in lightspace\n"
1466 " // eyevector = pixel to view in viewspace\n"
1467 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1468 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1469 "#ifdef USEDIFFUSE\n"
1470 " // calculate diffuse shading\n"
1471 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1472 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1474 "#ifdef USESPECULAR\n"
1475 " // calculate directional shading\n"
1476 " vec3 eyevector = position * -1.0;\n"
1477 "# ifdef USEEXACTSPECULARMATH\n"
1478 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1480 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1481 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1485 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1486 " fade *= ShadowMapCompare(CubeVector);\n"
1489 "#ifdef USEDIFFUSE\n"
1490 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1492 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1494 "#ifdef USESPECULAR\n"
1495 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1497 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1500 "# ifdef USECUBEFILTER\n"
1501 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1502 " gl_FragData[0].rgb *= cubecolor;\n"
1503 " gl_FragData[1].rgb *= cubecolor;\n"
1506 "#endif // FRAGMENT_SHADER\n"
1507 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1512 "#ifdef VERTEX_SHADER\n"
1513 "uniform mat4 TexMatrix;\n"
1514 "#ifdef USEVERTEXTEXTUREBLEND\n"
1515 "uniform mat4 BackgroundTexMatrix;\n"
1517 "#ifdef MODE_LIGHTSOURCE\n"
1518 "uniform mat4 ModelToLight;\n"
1520 "#ifdef USESHADOWMAPORTHO\n"
1521 "uniform mat4 ShadowMapMatrix;\n"
1525 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1526 " gl_FrontColor = gl_Color;\n"
1528 " // copy the surface texcoord\n"
1529 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1530 "#ifdef USEVERTEXTEXTUREBLEND\n"
1531 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1533 "#ifdef USELIGHTMAP\n"
1534 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1537 "#ifdef MODE_LIGHTSOURCE\n"
1538 " // transform vertex position into light attenuation/cubemap space\n"
1539 " // (-1 to +1 across the light box)\n"
1540 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1542 "# ifdef USEDIFFUSE\n"
1543 " // transform unnormalized light direction into tangent space\n"
1544 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1545 " // normalize it per pixel)\n"
1546 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1547 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1548 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1549 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1553 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1554 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1555 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1556 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1559 " // transform unnormalized eye direction into tangent space\n"
1560 "#ifdef USEEYEVECTOR\n"
1561 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1562 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1563 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1564 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1568 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1569 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1572 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1573 " VectorS = gl_MultiTexCoord1.xyz;\n"
1574 " VectorT = gl_MultiTexCoord2.xyz;\n"
1575 " VectorR = gl_MultiTexCoord3.xyz;\n"
1578 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1579 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1581 "#ifdef USESHADOWMAPORTHO\n"
1582 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1585 "#ifdef USEREFLECTION\n"
1586 " ModelViewProjectionPosition = gl_Position;\n"
1589 "#endif // VERTEX_SHADER\n"
1594 "#ifdef FRAGMENT_SHADER\n"
1595 "#ifdef USEDEFERREDLIGHTMAP\n"
1596 "uniform myhalf2 PixelToScreenTexCoord;\n"
1597 "uniform myhalf3 DeferredMod_Diffuse;\n"
1598 "uniform myhalf3 DeferredMod_Specular;\n"
1600 "uniform myhalf3 Color_Ambient;\n"
1601 "uniform myhalf3 Color_Diffuse;\n"
1602 "uniform myhalf3 Color_Specular;\n"
1603 "uniform myhalf SpecularPower;\n"
1605 "uniform myhalf3 Color_Glow;\n"
1607 "uniform myhalf Alpha;\n"
1608 "#ifdef USEREFLECTION\n"
1609 "uniform vec4 DistortScaleRefractReflect;\n"
1610 "uniform vec4 ScreenScaleRefractReflect;\n"
1611 "uniform vec4 ScreenCenterRefractReflect;\n"
1612 "uniform myhalf4 ReflectColor;\n"
1614 "#ifdef USEREFLECTCUBE\n"
1615 "uniform mat4 ModelToReflectCube;\n"
1616 "uniform sampler2D Texture_ReflectMask;\n"
1617 "uniform samplerCube Texture_ReflectCube;\n"
1619 "#ifdef MODE_LIGHTDIRECTION\n"
1620 "uniform myhalf3 LightColor;\n"
1622 "#ifdef MODE_LIGHTSOURCE\n"
1623 "uniform myhalf3 LightColor;\n"
1627 "#ifdef USEOFFSETMAPPING\n"
1628 " // apply offsetmapping\n"
1629 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1630 "#define TexCoord TexCoordOffset\n"
1633 " // combine the diffuse textures (base, pants, shirt)\n"
1634 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1635 "#ifdef USEALPHAKILL\n"
1636 " if (color.a < 0.5)\n"
1639 " color.a *= Alpha;\n"
1640 "#ifdef USECOLORMAPPING\n"
1641 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1643 "#ifdef USEVERTEXTEXTUREBLEND\n"
1644 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1645 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1646 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1647 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1649 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1652 " // get the surface normal\n"
1653 "#ifdef USEVERTEXTEXTUREBLEND\n"
1654 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1656 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1659 " // get the material colors\n"
1660 " myhalf3 diffusetex = color.rgb;\n"
1661 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1662 "# ifdef USEVERTEXTEXTUREBLEND\n"
1663 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1665 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1669 "#ifdef USEREFLECTCUBE\n"
1670 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1671 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1672 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1673 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1679 "#ifdef MODE_LIGHTSOURCE\n"
1680 " // light source\n"
1681 "#ifdef USEDIFFUSE\n"
1682 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1683 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1684 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1685 "#ifdef USESPECULAR\n"
1686 "#ifdef USEEXACTSPECULARMATH\n"
1687 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1689 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1690 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1692 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1695 " color.rgb = diffusetex * Color_Ambient;\n"
1697 " color.rgb *= LightColor;\n"
1698 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1699 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1700 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1702 "# ifdef USECUBEFILTER\n"
1703 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1705 "#endif // MODE_LIGHTSOURCE\n"
1710 "#ifdef MODE_LIGHTDIRECTION\n"
1712 "#ifdef USEDIFFUSE\n"
1713 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1715 "#define lightcolor LightColor\n"
1716 "#endif // MODE_LIGHTDIRECTION\n"
1717 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1719 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1720 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1721 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1722 " // convert modelspace light vector to tangentspace\n"
1723 " myhalf3 lightnormal;\n"
1724 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1725 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1726 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1727 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1728 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1729 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1730 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1731 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1732 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1733 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1734 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1735 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1736 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1737 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1738 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1740 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1741 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1742 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1748 "#ifdef MODE_LIGHTMAP\n"
1749 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1750 "#endif // MODE_LIGHTMAP\n"
1751 "#ifdef MODE_VERTEXCOLOR\n"
1752 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1753 "#endif // MODE_VERTEXCOLOR\n"
1754 "#ifdef MODE_FLATCOLOR\n"
1755 " color.rgb = diffusetex * Color_Ambient;\n"
1756 "#endif // MODE_FLATCOLOR\n"
1762 "# ifdef USEDIFFUSE\n"
1763 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1764 "# ifdef USESPECULAR\n"
1765 "# ifdef USEEXACTSPECULARMATH\n"
1766 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1768 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1769 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1771 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1773 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1776 " color.rgb = diffusetex * Color_Ambient;\n"
1780 "#ifdef USESHADOWMAPORTHO\n"
1781 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1784 "#ifdef USEDEFERREDLIGHTMAP\n"
1785 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1786 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1787 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1791 "#ifdef USEVERTEXTEXTUREBLEND\n"
1792 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1794 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1799 " color.rgb = FogVertex(color.rgb);\n"
1802 " // 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"
1803 "#ifdef USEREFLECTION\n"
1804 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1805 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1806 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1807 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1808 " // FIXME temporary hack to detect the case that the reflection\n"
1809 " // gets blackened at edges due to leaving the area that contains actual\n"
1811 " // Remove this 'ack once we have a better way to stop this thing from\n"
1813 " float 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 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1816 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1817 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1818 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1821 " gl_FragColor = vec4(color);\n"
1823 "#endif // FRAGMENT_SHADER\n"
1825 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1826 "#endif // !MODE_DEFERREDGEOMETRY\n"
1827 "#endif // !MODE_WATER\n"
1828 "#endif // !MODE_REFRACTION\n"
1829 "#endif // !MODE_BLOOMBLUR\n"
1830 "#endif // !MODE_GENERIC\n"
1831 "#endif // !MODE_POSTPROCESS\n"
1832 "#endif // !MODE_SHOWDEPTH\n"
1833 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1837 =========================================================================================================================================================
1841 =========================================================================================================================================================
1845 =========================================================================================================================================================
1849 =========================================================================================================================================================
1853 =========================================================================================================================================================
1857 =========================================================================================================================================================
1861 =========================================================================================================================================================
1864 const char *builtincgshaderstring =
1865 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1866 "// written by Forest 'LordHavoc' Hale\n"
1867 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1869 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1870 "#if defined(USEREFLECTION)\n"
1871 "#undef USESHADOWMAPORTHO\n"
1874 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1877 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1878 "#define USELIGHTMAP\n"
1880 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1881 "#define USEEYEVECTOR\n"
1884 "#ifdef FRAGMENT_SHADER\n"
1885 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1888 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1889 "#ifdef VERTEX_SHADER\n"
1892 "float4 gl_Vertex : POSITION,\n"
1893 "uniform float4x4 ModelViewProjectionMatrix,\n"
1894 "out float4 gl_Position : POSITION\n"
1897 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1900 "#else // !MODE_DEPTH_ORSHADOW\n"
1905 "#ifdef MODE_SHOWDEPTH\n"
1906 "#ifdef VERTEX_SHADER\n"
1909 "float4 gl_Vertex : POSITION,\n"
1910 "uniform float4x4 ModelViewProjectionMatrix,\n"
1911 "out float4 gl_Position : POSITION,\n"
1912 "out float4 gl_FrontColor : COLOR0\n"
1915 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1916 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1920 "#ifdef FRAGMENT_SHADER\n"
1923 "float4 gl_FrontColor : COLOR0,\n"
1924 "out float4 gl_FragColor : COLOR\n"
1927 " gl_FragColor = gl_FrontColor;\n"
1930 "#else // !MODE_SHOWDEPTH\n"
1935 "#ifdef MODE_POSTPROCESS\n"
1937 "#ifdef VERTEX_SHADER\n"
1940 "float4 gl_Vertex : POSITION,\n"
1941 "uniform float4x4 ModelViewProjectionMatrix,\n"
1942 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1943 "float4 gl_MultiTexCoord1 : TEXCOORD4,\n"
1944 "out float4 gl_Position : POSITION,\n"
1945 "out float2 TexCoord1 : TEXCOORD0,\n"
1946 "out float2 TexCoord2 : TEXCOORD1\n"
1949 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1950 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1952 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
1957 "#ifdef FRAGMENT_SHADER\n"
1960 "float2 TexCoord1 : TEXCOORD0,\n"
1961 "float2 TexCoord2 : TEXCOORD1,\n"
1962 "uniform sampler2D Texture_First,\n"
1964 "uniform sampler2D Texture_Second,\n"
1966 "#ifdef USEGAMMARAMPS\n"
1967 "uniform sampler2D Texture_GammaRamps,\n"
1969 "#ifdef USESATURATION\n"
1970 "uniform float Saturation,\n"
1972 "#ifdef USEVIEWTINT\n"
1973 "uniform float4 ViewTintColor,\n"
1975 "uniform float4 UserVec1,\n"
1976 "uniform float4 UserVec2,\n"
1977 "uniform float4 UserVec3,\n"
1978 "uniform float4 UserVec4,\n"
1979 "uniform float ClientTime,\n"
1980 "uniform float2 PixelSize,\n"
1981 "out float4 gl_FragColor : COLOR\n"
1984 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1986 " gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
1988 "#ifdef USEVIEWTINT\n"
1989 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1992 "#ifdef USEPOSTPROCESSING\n"
1993 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1994 "// 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"
1995 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1996 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1997 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1998 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
1999 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
2000 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2003 "#ifdef USESATURATION\n"
2004 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2005 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2006 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2007 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2010 "#ifdef USEGAMMARAMPS\n"
2011 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2012 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2013 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2017 "#else // !MODE_POSTPROCESS\n"
2022 "#ifdef MODE_GENERIC\n"
2023 "#ifdef VERTEX_SHADER\n"
2026 "float4 gl_Vertex : POSITION,\n"
2027 "uniform float4x4 ModelViewProjectionMatrix,\n"
2028 "float4 gl_Color : COLOR0,\n"
2029 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2030 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2031 "out float4 gl_Position : POSITION,\n"
2032 "out float4 gl_FrontColor : COLOR,\n"
2033 "out float2 TexCoord1 : TEXCOORD0,\n"
2034 "out float2 TexCoord2 : TEXCOORD1\n"
2037 " gl_FrontColor = gl_Color;\n"
2038 "#ifdef USEDIFFUSE\n"
2039 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2041 "#ifdef USESPECULAR\n"
2042 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2044 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2048 "#ifdef FRAGMENT_SHADER\n"
2052 "float4 gl_FrontColor : COLOR,\n"
2053 "float2 TexCoord1 : TEXCOORD0,\n"
2054 "float2 TexCoord2 : TEXCOORD1,\n"
2055 "#ifdef USEDIFFUSE\n"
2056 "uniform sampler2D Texture_First,\n"
2058 "#ifdef USESPECULAR\n"
2059 "uniform sampler2D Texture_Second,\n"
2061 "out float4 gl_FragColor : COLOR\n"
2064 " gl_FragColor = gl_FrontColor;\n"
2065 "#ifdef USEDIFFUSE\n"
2066 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2069 "#ifdef USESPECULAR\n"
2070 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2071 "# ifdef USECOLORMAPPING\n"
2072 " gl_FragColor *= tex2;\n"
2075 " gl_FragColor += tex2;\n"
2077 "# ifdef USEVERTEXTEXTUREBLEND\n"
2078 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2083 "#else // !MODE_GENERIC\n"
2088 "#ifdef MODE_BLOOMBLUR\n"
2089 "#ifdef VERTEX_SHADER\n"
2092 "float4 gl_Vertex : POSITION,\n"
2093 "uniform float4x4 ModelViewProjectionMatrix,\n"
2094 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2095 "out float4 gl_Position : POSITION,\n"
2096 "out float2 TexCoord : TEXCOORD0\n"
2099 " TexCoord = gl_MultiTexCoord0.xy;\n"
2100 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2104 "#ifdef FRAGMENT_SHADER\n"
2108 "float2 TexCoord : TEXCOORD0,\n"
2109 "uniform sampler2D Texture_First,\n"
2110 "uniform float4 BloomBlur_Parameters,\n"
2111 "out float4 gl_FragColor : COLOR\n"
2115 " float2 tc = TexCoord;\n"
2116 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2117 " tc += BloomBlur_Parameters.xy;\n"
2118 " for (i = 1;i < SAMPLES;i++)\n"
2120 " color += tex2D(Texture_First, tc).rgb;\n"
2121 " tc += BloomBlur_Parameters.xy;\n"
2123 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2126 "#else // !MODE_BLOOMBLUR\n"
2127 "#ifdef MODE_REFRACTION\n"
2128 "#ifdef VERTEX_SHADER\n"
2131 "float4 gl_Vertex : POSITION,\n"
2132 "uniform float4x4 ModelViewProjectionMatrix,\n"
2133 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2134 "uniform float4x4 TexMatrix,\n"
2135 "uniform float3 EyePosition,\n"
2136 "out float4 gl_Position : POSITION,\n"
2137 "out float2 TexCoord : TEXCOORD0,\n"
2138 "out float3 EyeVector : TEXCOORD1,\n"
2139 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2142 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2143 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2144 " ModelViewProjectionPosition = gl_Position;\n"
2148 "#ifdef FRAGMENT_SHADER\n"
2151 "float2 TexCoord : TEXCOORD0,\n"
2152 "float3 EyeVector : TEXCOORD1,\n"
2153 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2154 "uniform sampler2D Texture_Normal,\n"
2155 "uniform sampler2D Texture_Refraction,\n"
2156 "uniform sampler2D Texture_Reflection,\n"
2157 "uniform float4 DistortScaleRefractReflect,\n"
2158 "uniform float4 ScreenScaleRefractReflect,\n"
2159 "uniform float4 ScreenCenterRefractReflect,\n"
2160 "uniform float4 RefractColor,\n"
2161 "out float4 gl_FragColor : COLOR\n"
2164 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2165 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2166 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2167 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2168 " // FIXME temporary hack to detect the case that the reflection\n"
2169 " // gets blackened at edges due to leaving the area that contains actual\n"
2171 " // Remove this 'ack once we have a better way to stop this thing from\n"
2173 " float 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 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2176 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2177 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2178 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2181 "#else // !MODE_REFRACTION\n"
2186 "#ifdef MODE_WATER\n"
2187 "#ifdef VERTEX_SHADER\n"
2191 "float4 gl_Vertex : POSITION,\n"
2192 "uniform float4x4 ModelViewProjectionMatrix,\n"
2193 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2194 "uniform float4x4 TexMatrix,\n"
2195 "uniform float3 EyePosition,\n"
2196 "out float4 gl_Position : POSITION,\n"
2197 "out float2 TexCoord : TEXCOORD0,\n"
2198 "out float3 EyeVector : TEXCOORD1,\n"
2199 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2202 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2203 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2204 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2205 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2206 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2207 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2208 " ModelViewProjectionPosition = gl_Position;\n"
2212 "#ifdef FRAGMENT_SHADER\n"
2215 "float2 TexCoord : TEXCOORD0,\n"
2216 "float3 EyeVector : TEXCOORD1,\n"
2217 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2218 "uniform sampler2D Texture_Normal,\n"
2219 "uniform sampler2D Texture_Refraction,\n"
2220 "uniform sampler2D Texture_Reflection,\n"
2221 "uniform float4 DistortScaleRefractReflect,\n"
2222 "uniform float4 ScreenScaleRefractReflect,\n"
2223 "uniform float4 ScreenCenterRefractReflect,\n"
2224 "uniform float4 RefractColor,\n"
2225 "uniform float4 ReflectColor,\n"
2226 "uniform float ReflectFactor,\n"
2227 "uniform float ReflectOffset,\n"
2228 "out float4 gl_FragColor : COLOR\n"
2231 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2232 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2233 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2234 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2235 " // FIXME temporary hack to detect the case that the reflection\n"
2236 " // gets blackened at edges due to leaving the area that contains actual\n"
2238 " // Remove this 'ack once we have a better way to stop this thing from\n"
2240 " float 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 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2243 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2244 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\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 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2248 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2249 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2250 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2251 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2254 "#else // !MODE_WATER\n"
2259 "// 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"
2261 "// fragment shader specific:\n"
2262 "#ifdef FRAGMENT_SHADER\n"
2265 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2268 "#ifdef USEFOGHEIGHTTEXTURE\n"
2269 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2270 " fogfrac = fogheightpixel.a;\n"
2271 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2273 "# ifdef USEFOGOUTSIDE\n"
2274 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2276 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2278 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2283 "#ifdef USEOFFSETMAPPING\n"
2284 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2286 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2287 " // 14 sample relief mapping: linear search and then binary search\n"
2288 " // this basically steps forward a small amount repeatedly until it finds\n"
2289 " // itself inside solid, then jitters forward and back using decreasing\n"
2290 " // amounts to find the impact\n"
2291 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2292 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2293 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2294 " float3 RT = float3(TexCoord, 1);\n"
2295 " OffsetVector *= 0.1;\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);\n"
2304 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2305 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2306 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2307 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2308 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2309 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2312 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2313 " // this basically moves forward the full distance, and then backs up based\n"
2314 " // on height of samples\n"
2315 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2316 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2317 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2318 " TexCoord += OffsetVector;\n"
2319 " OffsetVector *= 0.333;\n"
2320 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2321 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2322 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2323 " return TexCoord;\n"
2326 "#endif // USEOFFSETMAPPING\n"
2328 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2329 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2330 "# ifdef USESHADOWMAPORTHO\n"
2331 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2333 "# ifdef USESHADOWMAPVSDCT\n"
2334 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2336 " float3 adir = abs(dir);\n"
2337 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2338 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2339 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2342 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2344 " float3 adir = abs(dir);\n"
2345 " float ma = adir.z;\n"
2346 " float4 proj = float4(dir, 2.5);\n"
2347 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2348 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2349 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2350 " 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"
2354 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2356 "#ifdef USESHADOWMAPCUBE\n"
2357 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2359 " float3 adir = abs(dir);\n"
2360 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2364 "# ifdef USESHADOWMAPRECT\n"
2365 "#ifdef USESHADOWMAPVSDCT\n"
2366 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2368 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2371 "#ifdef USESHADOWMAPVSDCT\n"
2372 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2374 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2377 "# ifdef USESHADOWSAMPLER\n"
2379 "# ifdef USESHADOWMAPPCF\n"
2380 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2381 " 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"
2383 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2388 "# ifdef USESHADOWMAPPCF\n"
2389 "# if USESHADOWMAPPCF > 1\n"
2390 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2391 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2392 " 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"
2393 " 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"
2394 " 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"
2395 " 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"
2396 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2397 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2399 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2400 " float2 offset = frac(shadowmaptc.xy);\n"
2401 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2402 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2403 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2404 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2405 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2408 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2412 "# ifdef USESHADOWMAPORTHO\n"
2413 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2420 "# ifdef USESHADOWMAP2D\n"
2421 "#ifdef USESHADOWMAPVSDCT\n"
2422 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2424 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2427 "#ifdef USESHADOWMAPVSDCT\n"
2428 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2430 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2434 "# ifdef USESHADOWSAMPLER\n"
2435 "# ifdef USESHADOWMAPPCF\n"
2436 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
2437 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2438 " 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"
2440 " f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2443 "# ifdef USESHADOWMAPPCF\n"
2444 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2445 "# ifdef GL_ARB_texture_gather\n"
2446 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2448 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2450 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2451 " center *= ShadowMap_TextureScale;\n"
2452 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2453 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2454 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2455 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2456 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2457 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2458 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2460 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale) \n"
2461 "# if USESHADOWMAPPCF > 1\n"
2462 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2463 " center *= ShadowMap_TextureScale;\n"
2464 " 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"
2465 " 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"
2466 " 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"
2467 " 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"
2468 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2469 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2471 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2472 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2473 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2474 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2475 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2476 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2480 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2483 "# ifdef USESHADOWMAPORTHO\n"
2484 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2491 "# ifdef USESHADOWMAPCUBE\n"
2492 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2494 " // apply depth texture cubemap as light filter\n"
2495 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2497 "# ifdef USESHADOWSAMPLER\n"
2498 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2500 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2505 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2506 "#endif // FRAGMENT_SHADER\n"
2511 "#ifdef MODE_DEFERREDGEOMETRY\n"
2512 "#ifdef VERTEX_SHADER\n"
2515 "float4 gl_Vertex : POSITION,\n"
2516 "uniform float4x4 ModelViewProjectionMatrix,\n"
2517 "#ifdef USEVERTEXTEXTUREBLEND\n"
2518 "float4 gl_Color : COLOR0,\n"
2520 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2521 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2522 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2523 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2524 "uniform float4x4 TexMatrix,\n"
2525 "#ifdef USEVERTEXTEXTUREBLEND\n"
2526 "uniform float4x4 BackgroundTexMatrix,\n"
2528 "uniform float4x4 ModelViewMatrix,\n"
2529 "#ifdef USEOFFSETMAPPING\n"
2530 "uniform float3 EyePosition,\n"
2532 "out float4 gl_Position : POSITION,\n"
2533 "out float4 gl_FrontColor : COLOR,\n"
2534 "out float4 TexCoordBoth : TEXCOORD0,\n"
2535 "#ifdef USEOFFSETMAPPING\n"
2536 "out float3 EyeVector : TEXCOORD2,\n"
2538 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2539 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2540 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2543 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2544 "#ifdef USEVERTEXTEXTUREBLEND\n"
2545 " gl_FrontColor = gl_Color;\n"
2546 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2549 " // transform unnormalized eye direction into tangent space\n"
2550 "#ifdef USEOFFSETMAPPING\n"
2551 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2552 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2553 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2554 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2557 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2558 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2559 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2560 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2562 "#endif // VERTEX_SHADER\n"
2564 "#ifdef FRAGMENT_SHADER\n"
2567 "float4 TexCoordBoth : TEXCOORD0,\n"
2568 "float3 EyeVector : TEXCOORD2,\n"
2569 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2570 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2571 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2572 "uniform sampler2D Texture_Normal,\n"
2573 "#ifdef USEALPHAKILL\n"
2574 "uniform sampler2D Texture_Color,\n"
2576 "uniform sampler2D Texture_Gloss,\n"
2577 "#ifdef USEVERTEXTEXTUREBLEND\n"
2578 "uniform sampler2D Texture_SecondaryNormal,\n"
2579 "uniform sampler2D Texture_SecondaryGloss,\n"
2581 "#ifdef USEOFFSETMAPPING\n"
2582 "uniform float OffsetMapping_Scale,\n"
2584 "uniform half SpecularPower,\n"
2585 "out float4 gl_FragColor : COLOR\n"
2588 " float2 TexCoord = TexCoordBoth.xy;\n"
2589 "#ifdef USEOFFSETMAPPING\n"
2590 " // apply offsetmapping\n"
2591 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2592 "#define TexCoord TexCoordOffset\n"
2595 "#ifdef USEALPHAKILL\n"
2596 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2600 "#ifdef USEVERTEXTEXTUREBLEND\n"
2601 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2602 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2603 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2604 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2607 "#ifdef USEVERTEXTEXTUREBLEND\n"
2608 " float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2609 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2611 " float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2612 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2615 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2617 "#endif // FRAGMENT_SHADER\n"
2618 "#else // !MODE_DEFERREDGEOMETRY\n"
2623 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2624 "#ifdef VERTEX_SHADER\n"
2627 "float4 gl_Vertex : POSITION,\n"
2628 "uniform float4x4 ModelViewProjectionMatrix,\n"
2629 "uniform float4x4 ModelViewMatrix,\n"
2630 "out float4 gl_Position : POSITION,\n"
2631 "out float4 ModelViewPosition : TEXCOORD0\n"
2634 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2635 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2637 "#endif // VERTEX_SHADER\n"
2639 "#ifdef FRAGMENT_SHADER\n"
2642 "float2 Pixel : WPOS,\n"
2643 "float4 ModelViewPosition : TEXCOORD0,\n"
2644 "uniform float4x4 ViewToLight,\n"
2645 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2646 "uniform float3 LightPosition,\n"
2647 "uniform half2 PixelToScreenTexCoord,\n"
2648 "uniform half3 DeferredColor_Ambient,\n"
2649 "uniform half3 DeferredColor_Diffuse,\n"
2650 "#ifdef USESPECULAR\n"
2651 "uniform half3 DeferredColor_Specular,\n"
2652 "uniform half SpecularPower,\n"
2654 "uniform sampler2D Texture_Attenuation,\n"
2655 "uniform sampler2D Texture_ScreenDepth,\n"
2656 "uniform sampler2D Texture_ScreenNormalMap,\n"
2658 "#ifdef USECUBEFILTER\n"
2659 "uniform samplerCUBE Texture_Cube,\n"
2662 "#ifdef USESHADOWMAPRECT\n"
2663 "# ifdef USESHADOWSAMPLER\n"
2664 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2666 "uniform samplerRECT Texture_ShadowMapRect,\n"
2670 "#ifdef USESHADOWMAP2D\n"
2671 "# ifdef USESHADOWSAMPLER\n"
2672 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2674 "uniform sampler2D Texture_ShadowMap2D,\n"
2678 "#ifdef USESHADOWMAPVSDCT\n"
2679 "uniform samplerCUBE Texture_CubeProjection,\n"
2682 "#ifdef USESHADOWMAPCUBE\n"
2683 "# ifdef USESHADOWSAMPLER\n"
2684 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2686 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2690 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2691 "uniform float2 ShadowMap_TextureScale,\n"
2692 "uniform float4 ShadowMap_Parameters,\n"
2695 "out float4 gl_FragData0 : COLOR0,\n"
2696 "out float4 gl_FragData1 : COLOR1\n"
2699 " // calculate viewspace pixel position\n"
2700 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2701 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2702 " float3 position;\n"
2703 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2704 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2705 " // decode viewspace pixel normal\n"
2706 " half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2707 " half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2708 " // surfacenormal = pixel normal in viewspace\n"
2709 " // LightVector = pixel to light in viewspace\n"
2710 " // CubeVector = position in lightspace\n"
2711 " // eyevector = pixel to view in viewspace\n"
2712 " float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2713 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2714 "#ifdef USEDIFFUSE\n"
2715 " // calculate diffuse shading\n"
2716 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2717 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2719 "#ifdef USESPECULAR\n"
2720 " // calculate directional shading\n"
2721 " float3 eyevector = position * -1.0;\n"
2722 "# ifdef USEEXACTSPECULARMATH\n"
2723 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2725 " half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2726 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2730 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2731 " fade *= ShadowMapCompare(CubeVector,\n"
2732 "# if defined(USESHADOWMAP2D)\n"
2733 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2735 "# if defined(USESHADOWMAPRECT)\n"
2736 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2738 "# if defined(USESHADOWMAPCUBE)\n"
2739 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2742 "#ifdef USESHADOWMAPVSDCT\n"
2743 ", Texture_CubeProjection\n"
2748 "#ifdef USEDIFFUSE\n"
2749 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2751 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2753 "#ifdef USESPECULAR\n"
2754 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2756 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2759 "# ifdef USECUBEFILTER\n"
2760 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2761 " gl_FragData0.rgb *= cubecolor;\n"
2762 " gl_FragData1.rgb *= cubecolor;\n"
2765 "#endif // FRAGMENT_SHADER\n"
2766 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2771 "#ifdef VERTEX_SHADER\n"
2774 "float4 gl_Vertex : POSITION,\n"
2775 "uniform float4x4 ModelViewProjectionMatrix,\n"
2776 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2777 "float4 gl_Color : COLOR0,\n"
2779 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2780 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2781 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2782 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2783 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2785 "uniform float3 EyePosition,\n"
2786 "uniform float4x4 TexMatrix,\n"
2787 "#ifdef USEVERTEXTEXTUREBLEND\n"
2788 "uniform float4x4 BackgroundTexMatrix,\n"
2790 "#ifdef MODE_LIGHTSOURCE\n"
2791 "uniform float4x4 ModelToLight,\n"
2793 "#ifdef MODE_LIGHTSOURCE\n"
2794 "uniform float3 LightPosition,\n"
2796 "#ifdef MODE_LIGHTDIRECTION\n"
2797 "uniform float3 LightDir,\n"
2799 "uniform float4 FogPlane,\n"
2800 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2801 "uniform float3 LightPosition,\n"
2803 "#ifdef USESHADOWMAPORTHO\n"
2804 "uniform float4x4 ShadowMapMatrix,\n"
2807 "out float4 gl_FrontColor : COLOR,\n"
2808 "out float4 TexCoordBoth : TEXCOORD0,\n"
2809 "#ifdef USELIGHTMAP\n"
2810 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2812 "#ifdef USEEYEVECTOR\n"
2813 "out float3 EyeVector : TEXCOORD2,\n"
2815 "#ifdef USEREFLECTION\n"
2816 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2819 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2821 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2822 "out float3 LightVector : TEXCOORD1,\n"
2824 "#ifdef MODE_LIGHTSOURCE\n"
2825 "out float3 CubeVector : TEXCOORD3,\n"
2827 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2828 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2829 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2830 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2832 "#ifdef USESHADOWMAPORTHO\n"
2833 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2835 "out float4 gl_Position : POSITION\n"
2838 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2839 " gl_FrontColor = gl_Color;\n"
2841 " // copy the surface texcoord\n"
2842 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2843 "#ifdef USEVERTEXTEXTUREBLEND\n"
2844 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2846 "#ifdef USELIGHTMAP\n"
2847 " TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2850 "#ifdef MODE_LIGHTSOURCE\n"
2851 " // transform vertex position into light attenuation/cubemap space\n"
2852 " // (-1 to +1 across the light box)\n"
2853 " CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2855 "# ifdef USEDIFFUSE\n"
2856 " // transform unnormalized light direction into tangent space\n"
2857 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2858 " // normalize it per pixel)\n"
2859 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2860 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2861 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2862 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2866 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2867 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2868 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2869 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2872 " // transform unnormalized eye direction into tangent space\n"
2873 "#ifdef USEEYEVECTOR\n"
2874 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2875 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2876 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2877 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2881 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2882 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2885 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2886 " VectorS = gl_MultiTexCoord1.xyz;\n"
2887 " VectorT = gl_MultiTexCoord2.xyz;\n"
2888 " VectorR = gl_MultiTexCoord3.xyz;\n"
2891 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2892 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2894 "#ifdef USESHADOWMAPORTHO\n"
2895 " ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2898 "#ifdef USEREFLECTION\n"
2899 " ModelViewProjectionPosition = gl_Position;\n"
2902 "#endif // VERTEX_SHADER\n"
2907 "#ifdef FRAGMENT_SHADER\n"
2910 "#ifdef USEDEFERREDLIGHTMAP\n"
2911 "float2 Pixel : WPOS,\n"
2913 "float4 gl_FrontColor : COLOR,\n"
2914 "float4 TexCoordBoth : TEXCOORD0,\n"
2915 "#ifdef USELIGHTMAP\n"
2916 "float2 TexCoordLightmap : TEXCOORD1,\n"
2918 "#ifdef USEEYEVECTOR\n"
2919 "float3 EyeVector : TEXCOORD2,\n"
2921 "#ifdef USEREFLECTION\n"
2922 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2925 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2927 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2928 "float3 LightVector : TEXCOORD1,\n"
2930 "#ifdef MODE_LIGHTSOURCE\n"
2931 "float3 CubeVector : TEXCOORD3,\n"
2933 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2934 "float4 ModelViewPosition : TEXCOORD0,\n"
2936 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2937 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2938 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2939 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2941 "#ifdef USESHADOWMAPORTHO\n"
2942 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2945 "uniform sampler2D Texture_Normal,\n"
2946 "uniform sampler2D Texture_Color,\n"
2947 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2948 "uniform sampler2D Texture_Gloss,\n"
2951 "uniform sampler2D Texture_Glow,\n"
2953 "#ifdef USEVERTEXTEXTUREBLEND\n"
2954 "uniform sampler2D Texture_SecondaryNormal,\n"
2955 "uniform sampler2D Texture_SecondaryColor,\n"
2956 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2957 "uniform sampler2D Texture_SecondaryGloss,\n"
2960 "uniform sampler2D Texture_SecondaryGlow,\n"
2963 "#ifdef USECOLORMAPPING\n"
2964 "uniform sampler2D Texture_Pants,\n"
2965 "uniform sampler2D Texture_Shirt,\n"
2968 "uniform sampler2D Texture_FogHeightTexture,\n"
2969 "uniform sampler2D Texture_FogMask,\n"
2971 "#ifdef USELIGHTMAP\n"
2972 "uniform sampler2D Texture_Lightmap,\n"
2974 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2975 "uniform sampler2D Texture_Deluxemap,\n"
2977 "#ifdef USEREFLECTION\n"
2978 "uniform sampler2D Texture_Reflection,\n"
2981 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2982 "uniform sampler2D Texture_ScreenDepth,\n"
2983 "uniform sampler2D Texture_ScreenNormalMap,\n"
2985 "#ifdef USEDEFERREDLIGHTMAP\n"
2986 "uniform sampler2D Texture_ScreenDiffuse,\n"
2987 "uniform sampler2D Texture_ScreenSpecular,\n"
2990 "#ifdef USECOLORMAPPING\n"
2991 "uniform half3 Color_Pants,\n"
2992 "uniform half3 Color_Shirt,\n"
2995 "uniform float3 FogColor,\n"
2996 "uniform float FogRangeRecip,\n"
2997 "uniform float FogPlaneViewDist,\n"
2998 "uniform float FogHeightFade,\n"
3001 "#ifdef USEOFFSETMAPPING\n"
3002 "uniform float OffsetMapping_Scale,\n"
3005 "#ifdef USEDEFERREDLIGHTMAP\n"
3006 "uniform half2 PixelToScreenTexCoord,\n"
3007 "uniform half3 DeferredMod_Diffuse,\n"
3008 "uniform half3 DeferredMod_Specular,\n"
3010 "uniform half3 Color_Ambient,\n"
3011 "uniform half3 Color_Diffuse,\n"
3012 "uniform half3 Color_Specular,\n"
3013 "uniform half SpecularPower,\n"
3015 "uniform half3 Color_Glow,\n"
3017 "uniform half Alpha,\n"
3018 "#ifdef USEREFLECTION\n"
3019 "uniform float4 DistortScaleRefractReflect,\n"
3020 "uniform float4 ScreenScaleRefractReflect,\n"
3021 "uniform float4 ScreenCenterRefractReflect,\n"
3022 "uniform half4 ReflectColor,\n"
3024 "#ifdef USEREFLECTCUBE\n"
3025 "uniform float4x4 ModelToReflectCube,\n"
3026 "uniform sampler2D Texture_ReflectMask,\n"
3027 "uniform samplerCUBE Texture_ReflectCube,\n"
3029 "#ifdef MODE_LIGHTDIRECTION\n"
3030 "uniform half3 LightColor,\n"
3032 "#ifdef MODE_LIGHTSOURCE\n"
3033 "uniform half3 LightColor,\n"
3036 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3037 "uniform sampler2D Texture_Attenuation,\n"
3038 "uniform samplerCUBE Texture_Cube,\n"
3041 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3043 "#ifdef USESHADOWMAPRECT\n"
3044 "# ifdef USESHADOWSAMPLER\n"
3045 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3047 "uniform samplerRECT Texture_ShadowMapRect,\n"
3051 "#ifdef USESHADOWMAP2D\n"
3052 "# ifdef USESHADOWSAMPLER\n"
3053 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3055 "uniform sampler2D Texture_ShadowMap2D,\n"
3059 "#ifdef USESHADOWMAPVSDCT\n"
3060 "uniform samplerCUBE Texture_CubeProjection,\n"
3063 "#ifdef USESHADOWMAPCUBE\n"
3064 "# ifdef USESHADOWSAMPLER\n"
3065 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3067 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3071 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3072 "uniform float2 ShadowMap_TextureScale,\n"
3073 "uniform float4 ShadowMap_Parameters,\n"
3075 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3077 "out float4 gl_FragColor : COLOR\n"
3080 " float2 TexCoord = TexCoordBoth.xy;\n"
3081 "#ifdef USEVERTEXTEXTUREBLEND\n"
3082 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3084 "#ifdef USEOFFSETMAPPING\n"
3085 " // apply offsetmapping\n"
3086 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3087 "#define TexCoord TexCoordOffset\n"
3090 " // combine the diffuse textures (base, pants, shirt)\n"
3091 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3092 "#ifdef USEALPHAKILL\n"
3093 " if (color.a < 0.5)\n"
3096 " color.a *= Alpha;\n"
3097 "#ifdef USECOLORMAPPING\n"
3098 " color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3100 "#ifdef USEVERTEXTEXTUREBLEND\n"
3101 " float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3102 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3103 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3104 " color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3106 " //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3109 " // get the surface normal\n"
3110 "#ifdef USEVERTEXTEXTUREBLEND\n"
3111 " half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3113 " half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3116 " // get the material colors\n"
3117 " half3 diffusetex = color.rgb;\n"
3118 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3119 "# ifdef USEVERTEXTEXTUREBLEND\n"
3120 " half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3122 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3126 "#ifdef USEREFLECTCUBE\n"
3127 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3128 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3129 " float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3130 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3136 "#ifdef MODE_LIGHTSOURCE\n"
3137 " // light source\n"
3138 "#ifdef USEDIFFUSE\n"
3139 " half3 lightnormal = half3(normalize(LightVector));\n"
3140 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3141 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3142 "#ifdef USESPECULAR\n"
3143 "#ifdef USEEXACTSPECULARMATH\n"
3144 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3146 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3147 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3149 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3152 " color.rgb = diffusetex * Color_Ambient;\n"
3154 " color.rgb *= LightColor;\n"
3155 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3156 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3157 " color.rgb *= ShadowMapCompare(CubeVector,\n"
3158 "# if defined(USESHADOWMAP2D)\n"
3159 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3161 "# if defined(USESHADOWMAPRECT)\n"
3162 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3164 "# if defined(USESHADOWMAPCUBE)\n"
3165 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3168 "#ifdef USESHADOWMAPVSDCT\n"
3169 ", Texture_CubeProjection\n"
3174 "# ifdef USECUBEFILTER\n"
3175 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3177 "#endif // MODE_LIGHTSOURCE\n"
3182 "#ifdef MODE_LIGHTDIRECTION\n"
3184 "#ifdef USEDIFFUSE\n"
3185 " half3 lightnormal = half3(normalize(LightVector));\n"
3187 "#define lightcolor LightColor\n"
3188 "#endif // MODE_LIGHTDIRECTION\n"
3189 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3191 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3192 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3193 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3194 " // convert modelspace light vector to tangentspace\n"
3195 " half3 lightnormal;\n"
3196 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3197 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3198 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3199 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3200 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3201 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3202 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3203 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3204 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3205 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3206 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3207 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3208 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3209 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3210 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3212 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3213 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3214 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3220 "#ifdef MODE_LIGHTMAP\n"
3221 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3222 "#endif // MODE_LIGHTMAP\n"
3223 "#ifdef MODE_VERTEXCOLOR\n"
3224 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3225 "#endif // MODE_VERTEXCOLOR\n"
3226 "#ifdef MODE_FLATCOLOR\n"
3227 " color.rgb = diffusetex * Color_Ambient;\n"
3228 "#endif // MODE_FLATCOLOR\n"
3234 "# ifdef USEDIFFUSE\n"
3235 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3236 "# ifdef USESPECULAR\n"
3237 "# ifdef USEEXACTSPECULARMATH\n"
3238 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3240 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3241 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3243 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3245 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3248 " color.rgb = diffusetex * Color_Ambient;\n"
3252 "#ifdef USESHADOWMAPORTHO\n"
3253 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3254 "# if defined(USESHADOWMAP2D)\n"
3255 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3257 "# if defined(USESHADOWMAPRECT)\n"
3258 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3263 "#ifdef USEDEFERREDLIGHTMAP\n"
3264 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3265 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3266 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3270 "#ifdef USEVERTEXTEXTUREBLEND\n"
3271 " color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3273 " color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3278 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3281 " // 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"
3282 "#ifdef USEREFLECTION\n"
3283 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3284 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3285 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3286 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3287 " // FIXME temporary hack to detect the case that the reflection\n"
3288 " // gets blackened at edges due to leaving the area that contains actual\n"
3290 " // Remove this 'ack once we have a better way to stop this thing from\n"
3292 " float 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 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3295 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3296 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3297 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3300 " gl_FragColor = float4(color);\n"
3302 "#endif // FRAGMENT_SHADER\n"
3304 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3305 "#endif // !MODE_DEFERREDGEOMETRY\n"
3306 "#endif // !MODE_WATER\n"
3307 "#endif // !MODE_REFRACTION\n"
3308 "#endif // !MODE_BLOOMBLUR\n"
3309 "#endif // !MODE_GENERIC\n"
3310 "#endif // !MODE_POSTPROCESS\n"
3311 "#endif // !MODE_SHOWDEPTH\n"
3312 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3315 char *glslshaderstring = NULL;
3316 char *cgshaderstring = NULL;
3318 //=======================================================================================================================================================
3320 typedef struct shaderpermutationinfo_s
3322 const char *pretext;
3325 shaderpermutationinfo_t;
3327 typedef struct shadermodeinfo_s
3329 const char *vertexfilename;
3330 const char *geometryfilename;
3331 const char *fragmentfilename;
3332 const char *pretext;
3337 typedef enum shaderpermutation_e
3339 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3340 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3341 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3342 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3343 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3344 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3345 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3346 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3347 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3348 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3349 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3350 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3351 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3352 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3353 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3354 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3355 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3356 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3357 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3358 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3359 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3360 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3361 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3362 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3363 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3364 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3365 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3366 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3367 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3368 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3369 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3371 shaderpermutation_t;
3373 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3374 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3376 {"#define USEDIFFUSE\n", " diffuse"},
3377 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3378 {"#define USEVIEWTINT\n", " viewtint"},
3379 {"#define USECOLORMAPPING\n", " colormapping"},
3380 {"#define USESATURATION\n", " saturation"},
3381 {"#define USEFOGINSIDE\n", " foginside"},
3382 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3383 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3384 {"#define USEGAMMARAMPS\n", " gammaramps"},
3385 {"#define USECUBEFILTER\n", " cubefilter"},
3386 {"#define USEGLOW\n", " glow"},
3387 {"#define USEBLOOM\n", " bloom"},
3388 {"#define USESPECULAR\n", " specular"},
3389 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3390 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3391 {"#define USEREFLECTION\n", " reflection"},
3392 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3393 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3394 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3395 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3396 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3397 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3398 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3399 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3400 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3401 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3402 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3403 {"#define USEALPHAKILL\n", " alphakill"},
3404 {"#define USEREFLECTCUBE\n", " reflectcube"},
3407 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3408 typedef enum shadermode_e
3410 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3411 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3412 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3413 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3414 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3415 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3416 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3417 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3418 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3419 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3420 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3421 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3422 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3423 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3424 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3429 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3430 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3432 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3433 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3434 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3435 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3436 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3437 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3438 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3439 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3440 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3441 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3442 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3443 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3444 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3445 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3446 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3450 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3452 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3453 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3454 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3455 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3456 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3457 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3458 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3459 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3460 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3461 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3462 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3463 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3464 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3465 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3466 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3470 struct r_glsl_permutation_s;
3471 typedef struct r_glsl_permutation_s
3473 /// hash lookup data
3474 struct r_glsl_permutation_s *hashnext;
3476 unsigned int permutation;
3478 /// indicates if we have tried compiling this permutation already
3480 /// 0 if compilation failed
3482 /// locations of detected uniforms in program object, or -1 if not found
3483 int loc_Texture_First;
3484 int loc_Texture_Second;
3485 int loc_Texture_GammaRamps;
3486 int loc_Texture_Normal;
3487 int loc_Texture_Color;
3488 int loc_Texture_Gloss;
3489 int loc_Texture_Glow;
3490 int loc_Texture_SecondaryNormal;
3491 int loc_Texture_SecondaryColor;
3492 int loc_Texture_SecondaryGloss;
3493 int loc_Texture_SecondaryGlow;
3494 int loc_Texture_Pants;
3495 int loc_Texture_Shirt;
3496 int loc_Texture_FogHeightTexture;
3497 int loc_Texture_FogMask;
3498 int loc_Texture_Lightmap;
3499 int loc_Texture_Deluxemap;
3500 int loc_Texture_Attenuation;
3501 int loc_Texture_Cube;
3502 int loc_Texture_Refraction;
3503 int loc_Texture_Reflection;
3504 int loc_Texture_ShadowMapRect;
3505 int loc_Texture_ShadowMapCube;
3506 int loc_Texture_ShadowMap2D;
3507 int loc_Texture_CubeProjection;
3508 int loc_Texture_ScreenDepth;
3509 int loc_Texture_ScreenNormalMap;
3510 int loc_Texture_ScreenDiffuse;
3511 int loc_Texture_ScreenSpecular;
3512 int loc_Texture_ReflectMask;
3513 int loc_Texture_ReflectCube;
3515 int loc_BloomBlur_Parameters;
3517 int loc_Color_Ambient;
3518 int loc_Color_Diffuse;
3519 int loc_Color_Specular;
3521 int loc_Color_Pants;
3522 int loc_Color_Shirt;
3523 int loc_DeferredColor_Ambient;
3524 int loc_DeferredColor_Diffuse;
3525 int loc_DeferredColor_Specular;
3526 int loc_DeferredMod_Diffuse;
3527 int loc_DeferredMod_Specular;
3528 int loc_DistortScaleRefractReflect;
3529 int loc_EyePosition;
3531 int loc_FogHeightFade;
3533 int loc_FogPlaneViewDist;
3534 int loc_FogRangeRecip;
3537 int loc_LightPosition;
3538 int loc_OffsetMapping_Scale;
3540 int loc_ReflectColor;
3541 int loc_ReflectFactor;
3542 int loc_ReflectOffset;
3543 int loc_RefractColor;
3545 int loc_ScreenCenterRefractReflect;
3546 int loc_ScreenScaleRefractReflect;
3547 int loc_ScreenToDepth;
3548 int loc_ShadowMap_Parameters;
3549 int loc_ShadowMap_TextureScale;
3550 int loc_SpecularPower;
3555 int loc_ViewTintColor;
3556 int loc_ViewToLight;
3557 int loc_ModelToLight;
3559 int loc_BackgroundTexMatrix;
3560 int loc_ModelViewProjectionMatrix;
3561 int loc_ModelViewMatrix;
3562 int loc_PixelToScreenTexCoord;
3563 int loc_ModelToReflectCube;
3564 int loc_ShadowMapMatrix;
3566 r_glsl_permutation_t;
3568 #define SHADERPERMUTATION_HASHSIZE 256
3570 /// information about each possible shader permutation
3571 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3572 /// currently selected permutation
3573 r_glsl_permutation_t *r_glsl_permutation;
3574 /// storage for permutations linked in the hash table
3575 memexpandablearray_t r_glsl_permutationarray;
3577 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3579 //unsigned int hashdepth = 0;
3580 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3581 r_glsl_permutation_t *p;
3582 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3584 if (p->mode == mode && p->permutation == permutation)
3586 //if (hashdepth > 10)
3587 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3592 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3594 p->permutation = permutation;
3595 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3596 r_glsl_permutationhash[mode][hashindex] = p;
3597 //if (hashdepth > 10)
3598 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3602 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3605 if (!filename || !filename[0])
3607 if (!strcmp(filename, "glsl/default.glsl"))
3609 if (!glslshaderstring)
3611 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3612 if (glslshaderstring)
3613 Con_DPrintf("Loading shaders from file %s...\n", filename);
3615 glslshaderstring = (char *)builtinshaderstring;
3617 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3618 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3619 return shaderstring;
3621 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3624 if (printfromdisknotice)
3625 Con_DPrintf("from disk %s... ", filename);
3626 return shaderstring;
3628 return shaderstring;
3631 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3634 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3635 int vertstrings_count = 0;
3636 int geomstrings_count = 0;
3637 int fragstrings_count = 0;
3638 char *vertexstring, *geometrystring, *fragmentstring;
3639 const char *vertstrings_list[32+3];
3640 const char *geomstrings_list[32+3];
3641 const char *fragstrings_list[32+3];
3642 char permutationname[256];
3649 permutationname[0] = 0;
3650 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3651 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3652 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3654 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3656 // the first pretext is which type of shader to compile as
3657 // (later these will all be bound together as a program object)
3658 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3659 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3660 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3662 // the second pretext is the mode (for example a light source)
3663 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3664 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3665 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3666 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3668 // now add all the permutation pretexts
3669 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3671 if (permutation & (1<<i))
3673 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3674 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3675 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3676 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3680 // keep line numbers correct
3681 vertstrings_list[vertstrings_count++] = "\n";
3682 geomstrings_list[geomstrings_count++] = "\n";
3683 fragstrings_list[fragstrings_count++] = "\n";
3687 // now append the shader text itself
3688 vertstrings_list[vertstrings_count++] = vertexstring;
3689 geomstrings_list[geomstrings_count++] = geometrystring;
3690 fragstrings_list[fragstrings_count++] = fragmentstring;
3692 // if any sources were NULL, clear the respective list
3694 vertstrings_count = 0;
3695 if (!geometrystring)
3696 geomstrings_count = 0;
3697 if (!fragmentstring)
3698 fragstrings_count = 0;
3700 // compile the shader program
3701 if (vertstrings_count + geomstrings_count + fragstrings_count)
3702 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3706 qglUseProgramObjectARB(p->program);CHECKGLERROR
3707 // look up all the uniform variable names we care about, so we don't
3708 // have to look them up every time we set them
3710 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3711 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3712 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3713 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3714 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3715 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3716 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3717 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3718 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3719 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3720 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3721 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3722 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3723 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3724 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3725 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3726 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3727 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3728 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3729 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3730 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3731 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3732 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3733 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3734 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3735 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3736 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3737 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3738 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3739 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3740 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3741 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3742 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3743 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3744 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3745 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3746 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3747 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3748 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3749 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3750 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3751 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3752 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3753 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3754 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3755 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3756 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3757 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3758 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3759 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3760 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3761 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3762 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3763 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3764 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3765 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3766 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3767 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3768 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3769 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3770 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3771 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3772 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3773 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3774 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3775 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3776 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3777 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3778 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3779 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3780 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3781 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3782 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3783 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3784 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3785 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3786 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3787 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3788 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3789 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3790 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3791 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3792 // initialize the samplers to refer to the texture units we use
3793 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3794 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3795 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3796 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3797 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3798 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3799 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3800 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3801 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3802 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3803 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3804 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3805 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3806 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3807 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3808 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3809 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3810 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3811 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3812 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3813 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3814 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3815 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3816 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3817 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3818 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3819 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3820 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3821 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3822 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3823 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3825 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3828 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3832 Mem_Free(vertexstring);
3834 Mem_Free(geometrystring);
3836 Mem_Free(fragmentstring);
3839 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3841 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3842 if (r_glsl_permutation != perm)
3844 r_glsl_permutation = perm;
3845 if (!r_glsl_permutation->program)
3847 if (!r_glsl_permutation->compiled)
3848 R_GLSL_CompilePermutation(perm, mode, permutation);
3849 if (!r_glsl_permutation->program)
3851 // remove features until we find a valid permutation
3853 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3855 // reduce i more quickly whenever it would not remove any bits
3856 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3857 if (!(permutation & j))
3860 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3861 if (!r_glsl_permutation->compiled)
3862 R_GLSL_CompilePermutation(perm, mode, permutation);
3863 if (r_glsl_permutation->program)
3866 if (i >= SHADERPERMUTATION_COUNT)
3868 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3869 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3870 qglUseProgramObjectARB(0);CHECKGLERROR
3871 return; // no bit left to clear, entire mode is broken
3876 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3878 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3879 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3880 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3884 #include <Cg/cgGL.h>
3885 struct r_cg_permutation_s;
3886 typedef struct r_cg_permutation_s
3888 /// hash lookup data
3889 struct r_cg_permutation_s *hashnext;
3891 unsigned int permutation;
3893 /// indicates if we have tried compiling this permutation already
3895 /// 0 if compilation failed
3898 /// locations of detected parameters in programs, or NULL if not found
3899 CGparameter vp_EyePosition;
3900 CGparameter vp_FogPlane;
3901 CGparameter vp_LightDir;
3902 CGparameter vp_LightPosition;
3903 CGparameter vp_ModelToLight;
3904 CGparameter vp_TexMatrix;
3905 CGparameter vp_BackgroundTexMatrix;
3906 CGparameter vp_ModelViewProjectionMatrix;
3907 CGparameter vp_ModelViewMatrix;
3908 CGparameter vp_ShadowMapMatrix;
3910 CGparameter fp_Texture_First;
3911 CGparameter fp_Texture_Second;
3912 CGparameter fp_Texture_GammaRamps;
3913 CGparameter fp_Texture_Normal;
3914 CGparameter fp_Texture_Color;
3915 CGparameter fp_Texture_Gloss;
3916 CGparameter fp_Texture_Glow;
3917 CGparameter fp_Texture_SecondaryNormal;
3918 CGparameter fp_Texture_SecondaryColor;
3919 CGparameter fp_Texture_SecondaryGloss;
3920 CGparameter fp_Texture_SecondaryGlow;
3921 CGparameter fp_Texture_Pants;
3922 CGparameter fp_Texture_Shirt;
3923 CGparameter fp_Texture_FogHeightTexture;
3924 CGparameter fp_Texture_FogMask;
3925 CGparameter fp_Texture_Lightmap;
3926 CGparameter fp_Texture_Deluxemap;
3927 CGparameter fp_Texture_Attenuation;
3928 CGparameter fp_Texture_Cube;
3929 CGparameter fp_Texture_Refraction;
3930 CGparameter fp_Texture_Reflection;
3931 CGparameter fp_Texture_ShadowMapRect;
3932 CGparameter fp_Texture_ShadowMapCube;
3933 CGparameter fp_Texture_ShadowMap2D;
3934 CGparameter fp_Texture_CubeProjection;
3935 CGparameter fp_Texture_ScreenDepth;
3936 CGparameter fp_Texture_ScreenNormalMap;
3937 CGparameter fp_Texture_ScreenDiffuse;
3938 CGparameter fp_Texture_ScreenSpecular;
3939 CGparameter fp_Texture_ReflectMask;
3940 CGparameter fp_Texture_ReflectCube;
3941 CGparameter fp_Alpha;
3942 CGparameter fp_BloomBlur_Parameters;
3943 CGparameter fp_ClientTime;
3944 CGparameter fp_Color_Ambient;
3945 CGparameter fp_Color_Diffuse;
3946 CGparameter fp_Color_Specular;
3947 CGparameter fp_Color_Glow;
3948 CGparameter fp_Color_Pants;
3949 CGparameter fp_Color_Shirt;
3950 CGparameter fp_DeferredColor_Ambient;
3951 CGparameter fp_DeferredColor_Diffuse;
3952 CGparameter fp_DeferredColor_Specular;
3953 CGparameter fp_DeferredMod_Diffuse;
3954 CGparameter fp_DeferredMod_Specular;
3955 CGparameter fp_DistortScaleRefractReflect;
3956 CGparameter fp_EyePosition;
3957 CGparameter fp_FogColor;
3958 CGparameter fp_FogHeightFade;
3959 CGparameter fp_FogPlane;
3960 CGparameter fp_FogPlaneViewDist;
3961 CGparameter fp_FogRangeRecip;
3962 CGparameter fp_LightColor;
3963 CGparameter fp_LightDir;
3964 CGparameter fp_LightPosition;
3965 CGparameter fp_OffsetMapping_Scale;
3966 CGparameter fp_PixelSize;
3967 CGparameter fp_ReflectColor;
3968 CGparameter fp_ReflectFactor;
3969 CGparameter fp_ReflectOffset;
3970 CGparameter fp_RefractColor;
3971 CGparameter fp_Saturation;
3972 CGparameter fp_ScreenCenterRefractReflect;
3973 CGparameter fp_ScreenScaleRefractReflect;
3974 CGparameter fp_ScreenToDepth;
3975 CGparameter fp_ShadowMap_Parameters;
3976 CGparameter fp_ShadowMap_TextureScale;
3977 CGparameter fp_SpecularPower;
3978 CGparameter fp_UserVec1;
3979 CGparameter fp_UserVec2;
3980 CGparameter fp_UserVec3;
3981 CGparameter fp_UserVec4;
3982 CGparameter fp_ViewTintColor;
3983 CGparameter fp_ViewToLight;
3984 CGparameter fp_PixelToScreenTexCoord;
3985 CGparameter fp_ModelToReflectCube;
3989 /// information about each possible shader permutation
3990 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3991 /// currently selected permutation
3992 r_cg_permutation_t *r_cg_permutation;
3993 /// storage for permutations linked in the hash table
3994 memexpandablearray_t r_cg_permutationarray;
3996 #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));}}
3998 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
4000 //unsigned int hashdepth = 0;
4001 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4002 r_cg_permutation_t *p;
4003 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4005 if (p->mode == mode && p->permutation == permutation)
4007 //if (hashdepth > 10)
4008 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4013 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4015 p->permutation = permutation;
4016 p->hashnext = r_cg_permutationhash[mode][hashindex];
4017 r_cg_permutationhash[mode][hashindex] = p;
4018 //if (hashdepth > 10)
4019 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4023 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4026 if (!filename || !filename[0])
4028 if (!strcmp(filename, "cg/default.cg"))
4030 if (!cgshaderstring)
4032 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4034 Con_DPrintf("Loading shaders from file %s...\n", filename);
4036 cgshaderstring = (char *)builtincgshaderstring;
4038 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4039 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4040 return shaderstring;
4042 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4045 if (printfromdisknotice)
4046 Con_DPrintf("from disk %s... ", filename);
4047 return shaderstring;
4049 return shaderstring;
4052 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4054 // TODO: load or create .fp and .vp shader files
4057 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4060 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4061 int vertstrings_count = 0, vertstring_length = 0;
4062 int geomstrings_count = 0, geomstring_length = 0;
4063 int fragstrings_count = 0, fragstring_length = 0;
4065 char *vertexstring, *geometrystring, *fragmentstring;
4066 char *vertstring, *geomstring, *fragstring;
4067 const char *vertstrings_list[32+3];
4068 const char *geomstrings_list[32+3];
4069 const char *fragstrings_list[32+3];
4070 char permutationname[256];
4071 char cachename[256];
4072 CGprofile vertexProfile;
4073 CGprofile fragmentProfile;
4081 permutationname[0] = 0;
4083 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4084 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4085 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4087 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4088 strlcat(cachename, "cg/", sizeof(cachename));
4090 // the first pretext is which type of shader to compile as
4091 // (later these will all be bound together as a program object)
4092 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4093 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4094 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4096 // the second pretext is the mode (for example a light source)
4097 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4098 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4099 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4100 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4101 strlcat(cachename, modeinfo->name, sizeof(cachename));
4103 // now add all the permutation pretexts
4104 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4106 if (permutation & (1<<i))
4108 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4109 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4110 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4111 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4112 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4116 // keep line numbers correct
4117 vertstrings_list[vertstrings_count++] = "\n";
4118 geomstrings_list[geomstrings_count++] = "\n";
4119 fragstrings_list[fragstrings_count++] = "\n";
4123 // replace spaces in the cachename with _ characters
4124 for (i = 0;cachename[i];i++)
4125 if (cachename[i] == ' ')
4128 // now append the shader text itself
4129 vertstrings_list[vertstrings_count++] = vertexstring;
4130 geomstrings_list[geomstrings_count++] = geometrystring;
4131 fragstrings_list[fragstrings_count++] = fragmentstring;
4133 // if any sources were NULL, clear the respective list
4135 vertstrings_count = 0;
4136 if (!geometrystring)
4137 geomstrings_count = 0;
4138 if (!fragmentstring)
4139 fragstrings_count = 0;
4141 vertstring_length = 0;
4142 for (i = 0;i < vertstrings_count;i++)
4143 vertstring_length += strlen(vertstrings_list[i]);
4144 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4145 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4146 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4148 geomstring_length = 0;
4149 for (i = 0;i < geomstrings_count;i++)
4150 geomstring_length += strlen(geomstrings_list[i]);
4151 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4152 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4153 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4155 fragstring_length = 0;
4156 for (i = 0;i < fragstrings_count;i++)
4157 fragstring_length += strlen(fragstrings_list[i]);
4158 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4159 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4160 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4164 //vertexProfile = CG_PROFILE_ARBVP1;
4165 //fragmentProfile = CG_PROFILE_ARBFP1;
4166 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4167 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4168 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4169 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4170 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4173 // try to load the cached shader, or generate one
4174 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4176 // if caching failed, do a dynamic compile for now
4178 if (vertstring[0] && !p->vprogram)
4179 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4181 if (fragstring[0] && !p->fprogram)
4182 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4185 // look up all the uniform variable names we care about, so we don't
4186 // have to look them up every time we set them
4190 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4191 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4192 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4193 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4194 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4195 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4196 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4197 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4198 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4199 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4200 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4201 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4207 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4208 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4209 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4210 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4211 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4212 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4213 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4214 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4215 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4216 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4217 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4218 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4219 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4220 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4221 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4222 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4223 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4224 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4225 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4226 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4227 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4228 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4229 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4230 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4231 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4232 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4233 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4234 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4235 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4236 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4237 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4238 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4239 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4240 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4241 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4242 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4243 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4244 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4245 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4246 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4247 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4248 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4249 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4250 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4251 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4252 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4253 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4254 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4255 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4256 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4257 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4258 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4259 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4260 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4261 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4262 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4263 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4264 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4265 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4266 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4267 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4268 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4269 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4270 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4271 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4272 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4273 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4274 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4275 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4276 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4277 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4278 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4279 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4280 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4281 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4282 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4283 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4284 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4288 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4289 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4291 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4295 Mem_Free(vertstring);
4297 Mem_Free(geomstring);
4299 Mem_Free(fragstring);
4301 Mem_Free(vertexstring);
4303 Mem_Free(geometrystring);
4305 Mem_Free(fragmentstring);
4308 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4310 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4313 if (r_cg_permutation != perm)
4315 r_cg_permutation = perm;
4316 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4318 if (!r_cg_permutation->compiled)
4319 R_CG_CompilePermutation(perm, mode, permutation);
4320 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4322 // remove features until we find a valid permutation
4324 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4326 // reduce i more quickly whenever it would not remove any bits
4327 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4328 if (!(permutation & j))
4331 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4332 if (!r_cg_permutation->compiled)
4333 R_CG_CompilePermutation(perm, mode, permutation);
4334 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4337 if (i >= SHADERPERMUTATION_COUNT)
4339 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4340 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4341 return; // no bit left to clear, entire mode is broken
4347 if (r_cg_permutation->vprogram)
4349 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4350 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4351 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4355 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4356 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4358 if (r_cg_permutation->fprogram)
4360 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4361 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4362 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4366 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4367 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4371 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4372 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4373 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4376 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4378 cgGLSetTextureParameter(param, R_GetTexture(tex));
4379 cgGLEnableTextureParameter(param);
4383 void R_GLSL_Restart_f(void)
4385 unsigned int i, limit;
4386 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4387 Mem_Free(glslshaderstring);
4388 glslshaderstring = NULL;
4389 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4390 Mem_Free(cgshaderstring);
4391 cgshaderstring = NULL;
4392 switch(vid.renderpath)
4394 case RENDERPATH_GL20:
4396 r_glsl_permutation_t *p;
4397 r_glsl_permutation = NULL;
4398 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4399 for (i = 0;i < limit;i++)
4401 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4403 GL_Backend_FreeProgram(p->program);
4404 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4407 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4410 case RENDERPATH_CGGL:
4413 r_cg_permutation_t *p;
4414 r_cg_permutation = NULL;
4415 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4416 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4417 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4418 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4419 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4420 for (i = 0;i < limit;i++)
4422 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4425 cgDestroyProgram(p->vprogram);
4427 cgDestroyProgram(p->fprogram);
4428 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4431 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4435 case RENDERPATH_GL13:
4436 case RENDERPATH_GL11:
4441 void R_GLSL_DumpShader_f(void)
4446 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4449 FS_Print(file, "/* The engine may define the following macros:\n");
4450 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4451 for (i = 0;i < SHADERMODE_COUNT;i++)
4452 FS_Print(file, glslshadermodeinfo[i].pretext);
4453 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4454 FS_Print(file, shaderpermutationinfo[i].pretext);
4455 FS_Print(file, "*/\n");
4456 FS_Print(file, builtinshaderstring);
4458 Con_Printf("glsl/default.glsl written\n");
4461 Con_Printf("failed to write to glsl/default.glsl\n");
4464 file = FS_OpenRealFile("cg/default.cg", "w", false);
4467 FS_Print(file, "/* The engine may define the following macros:\n");
4468 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4469 for (i = 0;i < SHADERMODE_COUNT;i++)
4470 FS_Print(file, cgshadermodeinfo[i].pretext);
4471 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4472 FS_Print(file, shaderpermutationinfo[i].pretext);
4473 FS_Print(file, "*/\n");
4474 FS_Print(file, builtincgshaderstring);
4476 Con_Printf("cg/default.cg written\n");
4479 Con_Printf("failed to write to cg/default.cg\n");
4483 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4486 texturemode = GL_MODULATE;
4487 switch (vid.renderpath)
4489 case RENDERPATH_GL20:
4490 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))));
4491 if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
4492 if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
4494 case RENDERPATH_CGGL:
4497 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))));
4498 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
4499 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
4502 case RENDERPATH_GL13:
4503 R_Mesh_TexBind(0, first );
4504 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4505 R_Mesh_TexBind(1, second);
4507 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4509 case RENDERPATH_GL11:
4510 R_Mesh_TexBind(0, first );
4515 void R_SetupShader_DepthOrShadow(void)
4517 switch (vid.renderpath)
4519 case RENDERPATH_GL20:
4520 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4522 case RENDERPATH_CGGL:
4524 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
4527 case RENDERPATH_GL13:
4528 R_Mesh_TexBind(0, 0);
4529 R_Mesh_TexBind(1, 0);
4531 case RENDERPATH_GL11:
4532 R_Mesh_TexBind(0, 0);
4537 void R_SetupShader_ShowDepth(void)
4539 switch (vid.renderpath)
4541 case RENDERPATH_GL20:
4542 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4544 case RENDERPATH_CGGL:
4546 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
4549 case RENDERPATH_GL13:
4551 case RENDERPATH_GL11:
4556 extern qboolean r_shadow_usingdeferredprepass;
4557 extern cvar_t r_shadow_deferred_8bitrange;
4558 extern rtexture_t *r_shadow_attenuationgradienttexture;
4559 extern rtexture_t *r_shadow_attenuation2dtexture;
4560 extern rtexture_t *r_shadow_attenuation3dtexture;
4561 extern qboolean r_shadow_usingshadowmaprect;
4562 extern qboolean r_shadow_usingshadowmapcube;
4563 extern qboolean r_shadow_usingshadowmap2d;
4564 extern qboolean r_shadow_usingshadowmaportho;
4565 extern float r_shadow_shadowmap_texturescale[2];
4566 extern float r_shadow_shadowmap_parameters[4];
4567 extern qboolean r_shadow_shadowmapvsdct;
4568 extern qboolean r_shadow_shadowmapsampler;
4569 extern int r_shadow_shadowmappcf;
4570 extern rtexture_t *r_shadow_shadowmaprectangletexture;
4571 extern rtexture_t *r_shadow_shadowmap2dtexture;
4572 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
4573 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4574 extern matrix4x4_t r_shadow_shadowmapmatrix;
4575 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4576 extern int r_shadow_prepass_width;
4577 extern int r_shadow_prepass_height;
4578 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4579 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4580 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4581 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4582 extern cvar_t gl_mesh_separatearrays;
4583 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
4585 // a blendfunc allows colormod if:
4586 // a) it can never keep the destination pixel invariant, or
4587 // b) it can keep the destination pixel invariant, and still can do so if colormodded
4588 // this is to prevent unintended side effects from colormod
4591 // IF there is a (s, sa) for which for all (d, da),
4592 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4593 // THEN, for this (s, sa) and all (colormod, d, da):
4594 // s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
4595 // OBVIOUSLY, this means that
4596 // s*colormod * src(s*colormod, d, sa, da) = 0
4597 // dst(s*colormod, d, sa, da) = 1
4599 // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
4601 // main condition to leave dst color invariant:
4602 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4604 // s * 0 + d * dst(s, d, sa, da) == d
4605 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4606 // => colormod is a problem for GL_SRC_COLOR only
4608 // s + d * dst(s, d, sa, da) == d
4610 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4611 // => colormod is never problematic for these
4612 // src == GL_SRC_COLOR:
4613 // s*s + d * dst(s, d, sa, da) == d
4615 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4616 // => colormod is never problematic for these
4617 // src == GL_ONE_MINUS_SRC_COLOR:
4618 // s*(1-s) + d * dst(s, d, sa, da) == d
4619 // => s == 0 or s == 1
4620 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4621 // => colormod is a problem for GL_SRC_COLOR only
4622 // src == GL_DST_COLOR
4623 // s*d + d * dst(s, d, sa, da) == d
4625 // => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4626 // => colormod is always a problem
4629 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4630 // => colormod is never problematic for these
4631 // => BUT, we do not know s! We must assume it is problematic
4632 // then... except in GL_ONE case, where we know all invariant
4634 // src == GL_ONE_MINUS_DST_COLOR
4635 // s*(1-d) + d * dst(s, d, sa, da) == d
4636 // => s == 0 (1-d is impossible to handle for our desired result)
4637 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4638 // => colormod is never problematic for these
4639 // src == GL_SRC_ALPHA
4640 // s*sa + d * dst(s, d, sa, da) == d
4641 // => s == 0, or sa == 0
4642 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4643 // => colormod breaks in the case GL_SRC_COLOR only
4644 // src == GL_ONE_MINUS_SRC_ALPHA
4645 // s*(1-sa) + d * dst(s, d, sa, da) == d
4646 // => s == 0, or sa == 1
4647 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4648 // => colormod breaks in the case GL_SRC_COLOR only
4649 // src == GL_DST_ALPHA
4650 // s*da + d * dst(s, d, sa, da) == d
4652 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4653 // => colormod is never problematic for these
4658 case GL_ONE_MINUS_SRC_COLOR:
4660 case GL_ONE_MINUS_SRC_ALPHA:
4661 if(dst == GL_SRC_COLOR)
4666 case GL_ONE_MINUS_DST_COLOR:
4668 case GL_ONE_MINUS_DST_ALPHA:
4678 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)
4680 // select a permutation of the lighting shader appropriate to this
4681 // combination of texture, entity, light source, and fogging, only use the
4682 // minimum features necessary to avoid wasting rendering time in the
4683 // fragment shader on features that are not being used
4684 unsigned int permutation = 0;
4685 unsigned int mode = 0;
4686 qboolean allow_colormod;
4687 static float dummy_colormod[3] = {1, 1, 1};
4688 float *colormod = rsurface.colormod;
4690 if (rsurfacepass == RSURFPASS_BACKGROUND)
4692 // distorted background
4693 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4694 mode = SHADERMODE_WATER;
4695 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4696 mode = SHADERMODE_REFRACTION;
4699 mode = SHADERMODE_GENERIC;
4700 permutation |= SHADERPERMUTATION_DIFFUSE;
4702 GL_AlphaTest(false);
4703 GL_BlendFunc(GL_ONE, GL_ZERO);
4704 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4706 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4708 if (r_glsl_offsetmapping.integer)
4710 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4711 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4712 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4713 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4714 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4716 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4717 if (r_glsl_offsetmapping_reliefmapping.integer)
4718 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4721 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4722 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4723 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4724 permutation |= SHADERPERMUTATION_ALPHAKILL;
4725 // normalmap (deferred prepass), may use alpha test on diffuse
4726 mode = SHADERMODE_DEFERREDGEOMETRY;
4727 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4728 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4729 GL_AlphaTest(false);
4730 GL_BlendFunc(GL_ONE, GL_ZERO);
4731 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4733 else if (rsurfacepass == RSURFPASS_RTLIGHT)
4735 if (r_glsl_offsetmapping.integer)
4737 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4738 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4739 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4740 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4741 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4743 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4744 if (r_glsl_offsetmapping_reliefmapping.integer)
4745 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4748 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4749 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4751 mode = SHADERMODE_LIGHTSOURCE;
4752 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4753 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4754 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4755 permutation |= SHADERPERMUTATION_CUBEFILTER;
4756 if (diffusescale > 0)
4757 permutation |= SHADERPERMUTATION_DIFFUSE;
4758 if (specularscale > 0)
4760 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4761 if (r_shadow_glossexact.integer)
4762 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4764 if (r_refdef.fogenabled)
4765 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4766 if (rsurface.texture->colormapping)
4767 permutation |= SHADERPERMUTATION_COLORMAPPING;
4768 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
4770 if (r_shadow_usingshadowmaprect)
4771 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4772 if (r_shadow_usingshadowmap2d)
4773 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4774 if (r_shadow_usingshadowmapcube)
4775 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
4776 else if(r_shadow_shadowmapvsdct)
4777 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
4779 if (r_shadow_shadowmapsampler)
4780 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4781 if (r_shadow_shadowmappcf > 1)
4782 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4783 else if (r_shadow_shadowmappcf)
4784 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4786 if (rsurface.texture->reflectmasktexture)
4787 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4788 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4789 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4790 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
4792 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4794 if (r_glsl_offsetmapping.integer)
4796 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4797 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4798 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4799 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4800 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4802 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4803 if (r_glsl_offsetmapping_reliefmapping.integer)
4804 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4807 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4808 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4809 // unshaded geometry (fullbright or ambient model lighting)
4810 mode = SHADERMODE_FLATCOLOR;
4811 ambientscale = diffusescale = specularscale = 0;
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 (rsurface.texture->reflectmasktexture)
4836 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4837 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4838 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4839 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4841 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
4843 if (r_glsl_offsetmapping.integer)
4845 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4846 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4847 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4848 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4849 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4851 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4852 if (r_glsl_offsetmapping_reliefmapping.integer)
4853 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4856 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4857 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4858 // directional model lighting
4859 mode = SHADERMODE_LIGHTDIRECTION;
4860 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4861 permutation |= SHADERPERMUTATION_GLOW;
4862 permutation |= SHADERPERMUTATION_DIFFUSE;
4863 if (specularscale > 0)
4865 permutation |= SHADERPERMUTATION_SPECULAR;
4866 if (r_shadow_glossexact.integer)
4867 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4869 if (r_refdef.fogenabled)
4870 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4871 if (rsurface.texture->colormapping)
4872 permutation |= SHADERPERMUTATION_COLORMAPPING;
4873 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4875 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4876 if (r_shadow_usingshadowmaprect)
4877 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4878 if (r_shadow_usingshadowmap2d)
4879 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4881 if (r_shadow_shadowmapsampler)
4882 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4883 if (r_shadow_shadowmappcf > 1)
4884 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4885 else if (r_shadow_shadowmappcf)
4886 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4888 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4889 permutation |= SHADERPERMUTATION_REFLECTION;
4890 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4891 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4892 if (rsurface.texture->reflectmasktexture)
4893 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4894 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4895 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4896 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4898 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
4900 if (r_glsl_offsetmapping.integer)
4902 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4903 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4904 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4905 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4906 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4908 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4909 if (r_glsl_offsetmapping_reliefmapping.integer)
4910 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4913 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4914 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4915 // ambient model lighting
4916 mode = SHADERMODE_LIGHTDIRECTION;
4917 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4918 permutation |= SHADERPERMUTATION_GLOW;
4919 if (r_refdef.fogenabled)
4920 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4921 if (rsurface.texture->colormapping)
4922 permutation |= SHADERPERMUTATION_COLORMAPPING;
4923 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4925 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4926 if (r_shadow_usingshadowmaprect)
4927 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4928 if (r_shadow_usingshadowmap2d)
4929 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4931 if (r_shadow_shadowmapsampler)
4932 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4933 if (r_shadow_shadowmappcf > 1)
4934 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4935 else if (r_shadow_shadowmappcf)
4936 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4938 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4939 permutation |= SHADERPERMUTATION_REFLECTION;
4940 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4941 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4942 if (rsurface.texture->reflectmasktexture)
4943 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4944 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4945 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4946 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4950 if (r_glsl_offsetmapping.integer)
4952 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4953 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4954 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4955 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4956 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4958 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4959 if (r_glsl_offsetmapping_reliefmapping.integer)
4960 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4963 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4964 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4966 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4967 permutation |= SHADERPERMUTATION_GLOW;
4968 if (r_refdef.fogenabled)
4969 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4970 if (rsurface.texture->colormapping)
4971 permutation |= SHADERPERMUTATION_COLORMAPPING;
4972 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4974 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4975 if (r_shadow_usingshadowmaprect)
4976 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4977 if (r_shadow_usingshadowmap2d)
4978 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4980 if (r_shadow_shadowmapsampler)
4981 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4982 if (r_shadow_shadowmappcf > 1)
4983 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4984 else if (r_shadow_shadowmappcf)
4985 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4987 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4988 permutation |= SHADERPERMUTATION_REFLECTION;
4989 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4990 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4991 if (rsurface.texture->reflectmasktexture)
4992 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4993 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
4995 // deluxemapping (light direction texture)
4996 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
4997 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
4999 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5000 permutation |= SHADERPERMUTATION_DIFFUSE;
5001 if (specularscale > 0)
5003 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5004 if (r_shadow_glossexact.integer)
5005 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5008 else if (r_glsl_deluxemapping.integer >= 2)
5010 // fake deluxemapping (uniform light direction in tangentspace)
5011 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5012 permutation |= SHADERPERMUTATION_DIFFUSE;
5013 if (specularscale > 0)
5015 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5016 if (r_shadow_glossexact.integer)
5017 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5020 else if (rsurface.uselightmaptexture)
5022 // ordinary lightmapping (q1bsp, q3bsp)
5023 mode = SHADERMODE_LIGHTMAP;
5027 // ordinary vertex coloring (q3bsp)
5028 mode = SHADERMODE_VERTEXCOLOR;
5030 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5031 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5032 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5035 colormod = dummy_colormod;
5036 switch(vid.renderpath)
5038 case RENDERPATH_GL20:
5039 if (gl_mesh_separatearrays.integer)
5041 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);
5042 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5043 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5044 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5045 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5046 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5047 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5048 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5052 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);
5053 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5055 R_SetupShader_SetPermutationGLSL(mode, permutation);
5056 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5057 if (mode == SHADERMODE_LIGHTSOURCE)
5059 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5060 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5061 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5062 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5063 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5064 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);
5066 // additive passes are only darkened by fog, not tinted
5067 if (r_glsl_permutation->loc_FogColor >= 0)
5068 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5069 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5073 if (mode == SHADERMODE_FLATCOLOR)
5075 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5077 else if (mode == SHADERMODE_LIGHTDIRECTION)
5079 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) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5080 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5081 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);
5082 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5083 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);
5084 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]);
5085 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]);
5089 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5090 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]);
5091 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);
5092 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5093 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);
5095 // additive passes are only darkened by fog, not tinted
5096 if (r_glsl_permutation->loc_FogColor >= 0)
5098 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5099 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5101 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5103 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);
5104 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]);
5105 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]);
5106 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
5107 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
5108 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5109 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5110 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5112 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5113 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5114 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5115 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]);
5116 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]);
5118 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5119 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5120 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5121 if (r_glsl_permutation->loc_Color_Pants >= 0)
5123 if (rsurface.texture->pantstexture)
5124 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5126 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5128 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5130 if (rsurface.texture->shirttexture)
5131 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5133 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5135 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]);
5136 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5137 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5138 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5139 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5140 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]);
5141 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5143 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5144 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5145 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5146 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5147 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5148 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5149 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5150 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5151 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5152 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5153 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5154 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5155 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5156 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5157 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5158 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5159 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5160 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_white );
5161 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP , r_texture_blanknormalmap );
5162 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5163 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION , r_texture_white );
5164 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION , r_texture_white );
5165 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5166 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5167 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5168 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5169 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5171 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5172 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5173 if (rsurface.rtlight)
5175 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5176 if (r_shadow_usingshadowmapcube)
5177 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5178 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5183 case RENDERPATH_CGGL:
5185 if (gl_mesh_separatearrays.integer)
5187 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);
5188 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5189 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5190 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5191 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5192 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5193 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5194 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5198 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);
5199 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5201 R_SetupShader_SetPermutationCG(mode, permutation);
5202 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5203 if (mode == SHADERMODE_LIGHTSOURCE)
5205 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5206 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5210 if (mode == SHADERMODE_LIGHTDIRECTION)
5212 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
5215 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5216 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5217 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5218 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5219 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
5222 if (mode == SHADERMODE_LIGHTSOURCE)
5224 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5225 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5226 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);CHECKCGERROR
5227 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);CHECKCGERROR
5228 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
5230 // additive passes are only darkened by fog, not tinted
5231 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5232 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5236 if (mode == SHADERMODE_FLATCOLOR)
5238 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0], colormod[1], colormod[2]);CHECKCGERROR
5240 else if (mode == SHADERMODE_LIGHTDIRECTION)
5242 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) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);CHECKCGERROR
5243 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);CHECKCGERROR
5244 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
5245 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5246 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
5247 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
5248 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
5252 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);CHECKCGERROR
5253 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
5254 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
5255 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5256 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
5258 // additive passes are only darkened by fog, not tinted
5259 if (r_cg_permutation->fp_FogColor)
5261 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5262 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5264 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5267 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
5268 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
5269 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
5270 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5271 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5272 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5273 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5274 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5276 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
5277 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
5278 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5279 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5280 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5281 if (r_cg_permutation->fp_Color_Pants)
5283 if (rsurface.texture->pantstexture)
5284 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5286 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5289 if (r_cg_permutation->fp_Color_Shirt)
5291 if (rsurface.texture->shirttexture)
5292 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5294 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5297 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
5298 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5299 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5300 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5301 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5302 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
5303 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5305 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
5306 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
5307 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
5308 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
5309 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
5310 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
5311 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
5312 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
5313 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
5314 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
5315 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
5316 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
5317 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
5318 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
5319 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
5320 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
5321 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
5322 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , r_texture_white );CHECKCGERROR
5323 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , r_texture_blanknormalmap );CHECKCGERROR
5324 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5325 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , r_texture_white );CHECKCGERROR
5326 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , r_texture_white );CHECKCGERROR
5327 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5328 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5329 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
5330 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
5331 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5333 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5334 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5335 if (rsurface.rtlight)
5337 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5338 if (r_shadow_usingshadowmapcube)
5339 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5340 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 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5355 // select a permutation of the lighting shader appropriate to this
5356 // combination of texture, entity, light source, and fogging, only use the
5357 // minimum features necessary to avoid wasting rendering time in the
5358 // fragment shader on features that are not being used
5359 unsigned int permutation = 0;
5360 unsigned int mode = 0;
5361 const float *lightcolorbase = rtlight->currentcolor;
5362 float ambientscale = rtlight->ambientscale;
5363 float diffusescale = rtlight->diffusescale;
5364 float specularscale = rtlight->specularscale;
5365 // this is the location of the light in view space
5366 vec3_t viewlightorigin;
5367 // this transforms from view space (camera) to light space (cubemap)
5368 matrix4x4_t viewtolight;
5369 matrix4x4_t lighttoview;
5370 float viewtolight16f[16];
5371 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5373 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5374 if (rtlight->currentcubemap != r_texture_whitecube)
5375 permutation |= SHADERPERMUTATION_CUBEFILTER;
5376 if (diffusescale > 0)
5377 permutation |= SHADERPERMUTATION_DIFFUSE;
5378 if (specularscale > 0)
5380 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5381 if (r_shadow_glossexact.integer)
5382 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5384 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5386 if (r_shadow_usingshadowmaprect)
5387 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5388 if (r_shadow_usingshadowmap2d)
5389 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5390 if (r_shadow_usingshadowmapcube)
5391 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5392 else if(r_shadow_shadowmapvsdct)
5393 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5395 if (r_shadow_shadowmapsampler)
5396 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5397 if (r_shadow_shadowmappcf > 1)
5398 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5399 else if (r_shadow_shadowmappcf)
5400 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5402 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5403 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5404 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5405 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5406 switch(vid.renderpath)
5408 case RENDERPATH_GL20:
5409 R_SetupShader_SetPermutationGLSL(mode, permutation);
5410 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5411 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
5412 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);
5413 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);
5414 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);
5415 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]);
5416 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]);
5417 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));
5418 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]);
5419 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5421 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5422 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5423 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5424 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5425 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
5426 if (r_shadow_usingshadowmapcube)
5427 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5428 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
5429 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5431 case RENDERPATH_CGGL:
5433 R_SetupShader_SetPermutationCG(mode, permutation);
5434 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
5435 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
5436 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
5437 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
5438 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
5439 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
5440 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
5441 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
5442 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
5443 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5445 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5446 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5447 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5448 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5449 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5450 if (r_shadow_usingshadowmapcube)
5451 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5452 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5453 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5456 case RENDERPATH_GL13:
5457 case RENDERPATH_GL11:
5462 #define SKINFRAME_HASH 1024
5466 int loadsequence; // incremented each level change
5467 memexpandablearray_t array;
5468 skinframe_t *hash[SKINFRAME_HASH];
5471 r_skinframe_t r_skinframe;
5473 void R_SkinFrame_PrepareForPurge(void)
5475 r_skinframe.loadsequence++;
5476 // wrap it without hitting zero
5477 if (r_skinframe.loadsequence >= 200)
5478 r_skinframe.loadsequence = 1;
5481 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5485 // mark the skinframe as used for the purging code
5486 skinframe->loadsequence = r_skinframe.loadsequence;
5489 void R_SkinFrame_Purge(void)
5493 for (i = 0;i < SKINFRAME_HASH;i++)
5495 for (s = r_skinframe.hash[i];s;s = s->next)
5497 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5499 if (s->merged == s->base)
5501 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5502 R_PurgeTexture(s->stain );s->stain = NULL;
5503 R_PurgeTexture(s->merged);s->merged = NULL;
5504 R_PurgeTexture(s->base );s->base = NULL;
5505 R_PurgeTexture(s->pants );s->pants = NULL;
5506 R_PurgeTexture(s->shirt );s->shirt = NULL;
5507 R_PurgeTexture(s->nmap );s->nmap = NULL;
5508 R_PurgeTexture(s->gloss );s->gloss = NULL;
5509 R_PurgeTexture(s->glow );s->glow = NULL;
5510 R_PurgeTexture(s->fog );s->fog = NULL;
5511 R_PurgeTexture(s->reflect);s->reflect = NULL;
5512 s->loadsequence = 0;
5518 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5520 char basename[MAX_QPATH];
5522 Image_StripImageExtension(name, basename, sizeof(basename));
5524 if( last == NULL ) {
5526 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5527 item = r_skinframe.hash[hashindex];
5532 // linearly search through the hash bucket
5533 for( ; item ; item = item->next ) {
5534 if( !strcmp( item->basename, basename ) ) {
5541 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5545 char basename[MAX_QPATH];
5547 Image_StripImageExtension(name, basename, sizeof(basename));
5549 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5550 for (item = r_skinframe.hash[hashindex];item;item = item->next)
5551 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5555 rtexture_t *dyntexture;
5556 // check whether its a dynamic texture
5557 dyntexture = CL_GetDynTexture( basename );
5558 if (!add && !dyntexture)
5560 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5561 memset(item, 0, sizeof(*item));
5562 strlcpy(item->basename, basename, sizeof(item->basename));
5563 item->base = dyntexture; // either NULL or dyntexture handle
5564 item->textureflags = textureflags;
5565 item->comparewidth = comparewidth;
5566 item->compareheight = compareheight;
5567 item->comparecrc = comparecrc;
5568 item->next = r_skinframe.hash[hashindex];
5569 r_skinframe.hash[hashindex] = item;
5571 else if( item->base == NULL )
5573 rtexture_t *dyntexture;
5574 // check whether its a dynamic texture
5575 // 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]
5576 dyntexture = CL_GetDynTexture( basename );
5577 item->base = dyntexture; // either NULL or dyntexture handle
5580 R_SkinFrame_MarkUsed(item);
5584 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5586 unsigned long long avgcolor[5], wsum; \
5594 for(pix = 0; pix < cnt; ++pix) \
5597 for(comp = 0; comp < 3; ++comp) \
5599 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5602 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5604 for(comp = 0; comp < 3; ++comp) \
5605 avgcolor[comp] += getpixel * w; \
5608 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5609 avgcolor[4] += getpixel; \
5611 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
5613 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
5614 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
5615 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
5616 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
5619 extern cvar_t gl_picmip;
5620 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
5623 unsigned char *pixels;
5624 unsigned char *bumppixels;
5625 unsigned char *basepixels = NULL;
5626 int basepixels_width = 0;
5627 int basepixels_height = 0;
5628 skinframe_t *skinframe;
5629 rtexture_t *ddsbase = NULL;
5630 qboolean ddshasalpha = false;
5631 float ddsavgcolor[4];
5632 char basename[MAX_QPATH];
5633 int miplevel = R_PicmipForFlags(textureflags);
5634 int savemiplevel = miplevel;
5637 if (cls.state == ca_dedicated)
5640 // return an existing skinframe if already loaded
5641 // if loading of the first image fails, don't make a new skinframe as it
5642 // would cause all future lookups of this to be missing
5643 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
5644 if (skinframe && skinframe->base)
5647 Image_StripImageExtension(name, basename, sizeof(basename));
5649 // check for DDS texture file first
5650 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
5652 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
5653 if (basepixels == NULL)
5657 // FIXME handle miplevel
5659 if (developer_loading.integer)
5660 Con_Printf("loading skin \"%s\"\n", name);
5662 // we've got some pixels to store, so really allocate this new texture now
5664 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
5665 skinframe->stain = NULL;
5666 skinframe->merged = NULL;
5667 skinframe->base = NULL;
5668 skinframe->pants = NULL;
5669 skinframe->shirt = NULL;
5670 skinframe->nmap = NULL;
5671 skinframe->gloss = NULL;
5672 skinframe->glow = NULL;
5673 skinframe->fog = NULL;
5674 skinframe->reflect = NULL;
5675 skinframe->hasalpha = false;
5679 skinframe->base = ddsbase;
5680 skinframe->hasalpha = ddshasalpha;
5681 VectorCopy(ddsavgcolor, skinframe->avgcolor);
5682 if (r_loadfog && skinframe->hasalpha)
5683 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
5684 //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]);
5688 basepixels_width = image_width;
5689 basepixels_height = image_height;
5690 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5691 if (textureflags & TEXF_ALPHA)
5693 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
5695 if (basepixels[j] < 255)
5697 skinframe->hasalpha = true;
5701 if (r_loadfog && skinframe->hasalpha)
5703 // has transparent pixels
5704 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5705 for (j = 0;j < image_width * image_height * 4;j += 4)
5710 pixels[j+3] = basepixels[j+3];
5712 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5716 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
5717 //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]);
5718 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
5719 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
5720 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
5721 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
5726 mymiplevel = savemiplevel;
5727 if (r_loadnormalmap)
5728 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
5729 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5731 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5732 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5733 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5734 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5737 // _norm is the name used by tenebrae and has been adopted as standard
5738 if (r_loadnormalmap && skinframe->nmap == NULL)
5740 mymiplevel = savemiplevel;
5741 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5743 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5747 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5749 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5750 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
5751 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5753 Mem_Free(bumppixels);
5755 else if (r_shadow_bumpscale_basetexture.value > 0)
5757 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
5758 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
5759 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5762 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
5763 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
5766 // _luma is supported only for tenebrae compatibility
5767 // _glow is the preferred name
5768 mymiplevel = savemiplevel;
5769 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
5771 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5772 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
5773 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
5774 Mem_Free(pixels);pixels = NULL;
5777 mymiplevel = savemiplevel;
5778 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
5780 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5781 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
5782 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
5787 mymiplevel = savemiplevel;
5788 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
5790 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5791 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
5792 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
5797 mymiplevel = savemiplevel;
5798 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
5800 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5801 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
5802 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
5807 mymiplevel = savemiplevel;
5808 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
5810 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5811 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
5812 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
5818 Mem_Free(basepixels);
5823 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
5824 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
5827 unsigned char *temp1, *temp2;
5828 skinframe_t *skinframe;
5830 if (cls.state == ca_dedicated)
5833 // if already loaded just return it, otherwise make a new skinframe
5834 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
5835 if (skinframe && skinframe->base)
5838 skinframe->stain = NULL;
5839 skinframe->merged = NULL;
5840 skinframe->base = NULL;
5841 skinframe->pants = NULL;
5842 skinframe->shirt = NULL;
5843 skinframe->nmap = NULL;
5844 skinframe->gloss = NULL;
5845 skinframe->glow = NULL;
5846 skinframe->fog = NULL;
5847 skinframe->reflect = NULL;
5848 skinframe->hasalpha = false;
5850 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5854 if (developer_loading.integer)
5855 Con_Printf("loading 32bit skin \"%s\"\n", name);
5857 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
5859 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5860 temp2 = temp1 + width * height * 4;
5861 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5862 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
5865 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
5866 if (textureflags & TEXF_ALPHA)
5868 for (i = 3;i < width * height * 4;i += 4)
5870 if (skindata[i] < 255)
5872 skinframe->hasalpha = true;
5876 if (r_loadfog && skinframe->hasalpha)
5878 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
5879 memcpy(fogpixels, skindata, width * height * 4);
5880 for (i = 0;i < width * height * 4;i += 4)
5881 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
5882 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
5883 Mem_Free(fogpixels);
5887 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
5888 //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]);
5893 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
5897 skinframe_t *skinframe;
5899 if (cls.state == ca_dedicated)
5902 // if already loaded just return it, otherwise make a new skinframe
5903 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5904 if (skinframe && skinframe->base)
5907 skinframe->stain = NULL;
5908 skinframe->merged = NULL;
5909 skinframe->base = NULL;
5910 skinframe->pants = NULL;
5911 skinframe->shirt = NULL;
5912 skinframe->nmap = NULL;
5913 skinframe->gloss = NULL;
5914 skinframe->glow = NULL;
5915 skinframe->fog = NULL;
5916 skinframe->reflect = NULL;
5917 skinframe->hasalpha = false;
5919 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5923 if (developer_loading.integer)
5924 Con_Printf("loading quake skin \"%s\"\n", name);
5926 // 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)
5927 skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height);
5928 memcpy(skinframe->qpixels, skindata, width*height);
5929 skinframe->qwidth = width;
5930 skinframe->qheight = height;
5933 for (i = 0;i < width * height;i++)
5934 featuresmask |= palette_featureflags[skindata[i]];
5936 skinframe->hasalpha = false;
5937 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
5938 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
5939 skinframe->qgeneratemerged = true;
5940 skinframe->qgeneratebase = skinframe->qhascolormapping;
5941 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
5943 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
5944 //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]);
5949 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
5953 unsigned char *skindata;
5955 if (!skinframe->qpixels)
5958 if (!skinframe->qhascolormapping)
5959 colormapped = false;
5963 if (!skinframe->qgeneratebase)
5968 if (!skinframe->qgeneratemerged)
5972 width = skinframe->qwidth;
5973 height = skinframe->qheight;
5974 skindata = skinframe->qpixels;
5976 if (skinframe->qgeneratenmap)
5978 unsigned char *temp1, *temp2;
5979 skinframe->qgeneratenmap = false;
5980 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5981 temp2 = temp1 + width * height * 4;
5982 // use either a custom palette or the quake palette
5983 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
5984 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5985 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
5989 if (skinframe->qgenerateglow)
5991 skinframe->qgenerateglow = false;
5992 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
5997 skinframe->qgeneratebase = false;
5998 skinframe->base = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
5999 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6000 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6004 skinframe->qgeneratemerged = false;
6005 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
6008 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6010 Mem_Free(skinframe->qpixels);
6011 skinframe->qpixels = NULL;
6015 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)
6018 skinframe_t *skinframe;
6020 if (cls.state == ca_dedicated)
6023 // if already loaded just return it, otherwise make a new skinframe
6024 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6025 if (skinframe && skinframe->base)
6028 skinframe->stain = NULL;
6029 skinframe->merged = NULL;
6030 skinframe->base = NULL;
6031 skinframe->pants = NULL;
6032 skinframe->shirt = NULL;
6033 skinframe->nmap = NULL;
6034 skinframe->gloss = NULL;
6035 skinframe->glow = NULL;
6036 skinframe->fog = NULL;
6037 skinframe->reflect = NULL;
6038 skinframe->hasalpha = false;
6040 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6044 if (developer_loading.integer)
6045 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6047 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6048 if (textureflags & TEXF_ALPHA)
6050 for (i = 0;i < width * height;i++)
6052 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6054 skinframe->hasalpha = true;
6058 if (r_loadfog && skinframe->hasalpha)
6059 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6062 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6063 //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]);
6068 skinframe_t *R_SkinFrame_LoadMissing(void)
6070 skinframe_t *skinframe;
6072 if (cls.state == ca_dedicated)
6075 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6076 skinframe->stain = NULL;
6077 skinframe->merged = NULL;
6078 skinframe->base = NULL;
6079 skinframe->pants = NULL;
6080 skinframe->shirt = NULL;
6081 skinframe->nmap = NULL;
6082 skinframe->gloss = NULL;
6083 skinframe->glow = NULL;
6084 skinframe->fog = NULL;
6085 skinframe->reflect = NULL;
6086 skinframe->hasalpha = false;
6088 skinframe->avgcolor[0] = rand() / RAND_MAX;
6089 skinframe->avgcolor[1] = rand() / RAND_MAX;
6090 skinframe->avgcolor[2] = rand() / RAND_MAX;
6091 skinframe->avgcolor[3] = 1;
6096 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6097 typedef struct suffixinfo_s
6100 qboolean flipx, flipy, flipdiagonal;
6103 static suffixinfo_t suffix[3][6] =
6106 {"px", false, false, false},
6107 {"nx", false, false, false},
6108 {"py", false, false, false},
6109 {"ny", false, false, false},
6110 {"pz", false, false, false},
6111 {"nz", false, false, false}
6114 {"posx", false, false, false},
6115 {"negx", false, false, false},
6116 {"posy", false, false, false},
6117 {"negy", false, false, false},
6118 {"posz", false, false, false},
6119 {"negz", false, false, false}
6122 {"rt", true, false, true},
6123 {"lf", false, true, true},
6124 {"ft", true, true, false},
6125 {"bk", false, false, false},
6126 {"up", true, false, true},
6127 {"dn", true, false, true}
6131 static int componentorder[4] = {0, 1, 2, 3};
6133 rtexture_t *R_LoadCubemap(const char *basename)
6135 int i, j, cubemapsize;
6136 unsigned char *cubemappixels, *image_buffer;
6137 rtexture_t *cubemaptexture;
6139 // must start 0 so the first loadimagepixels has no requested width/height
6141 cubemappixels = NULL;
6142 cubemaptexture = NULL;
6143 // keep trying different suffix groups (posx, px, rt) until one loads
6144 for (j = 0;j < 3 && !cubemappixels;j++)
6146 // load the 6 images in the suffix group
6147 for (i = 0;i < 6;i++)
6149 // generate an image name based on the base and and suffix
6150 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6152 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6154 // an image loaded, make sure width and height are equal
6155 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6157 // if this is the first image to load successfully, allocate the cubemap memory
6158 if (!cubemappixels && image_width >= 1)
6160 cubemapsize = image_width;
6161 // note this clears to black, so unavailable sides are black
6162 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6164 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6166 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);
6169 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6171 Mem_Free(image_buffer);
6175 // if a cubemap loaded, upload it
6178 if (developer_loading.integer)
6179 Con_Printf("loading cubemap \"%s\"\n", basename);
6181 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6182 Mem_Free(cubemappixels);
6186 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6187 if (developer_loading.integer)
6189 Con_Printf("(tried tried images ");
6190 for (j = 0;j < 3;j++)
6191 for (i = 0;i < 6;i++)
6192 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6193 Con_Print(" and was unable to find any of them).\n");
6196 return cubemaptexture;
6199 rtexture_t *R_GetCubemap(const char *basename)
6202 for (i = 0;i < r_texture_numcubemaps;i++)
6203 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6204 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6205 if (i >= MAX_CUBEMAPS)
6206 return r_texture_whitecube;
6207 r_texture_numcubemaps++;
6208 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6209 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6210 return r_texture_cubemaps[i].texture;
6213 void R_FreeCubemaps(void)
6216 for (i = 0;i < r_texture_numcubemaps;i++)
6218 if (developer_loading.integer)
6219 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6220 if (r_texture_cubemaps[i].texture)
6221 R_FreeTexture(r_texture_cubemaps[i].texture);
6223 r_texture_numcubemaps = 0;
6226 void R_Main_FreeViewCache(void)
6228 if (r_refdef.viewcache.entityvisible)
6229 Mem_Free(r_refdef.viewcache.entityvisible);
6230 if (r_refdef.viewcache.world_pvsbits)
6231 Mem_Free(r_refdef.viewcache.world_pvsbits);
6232 if (r_refdef.viewcache.world_leafvisible)
6233 Mem_Free(r_refdef.viewcache.world_leafvisible);
6234 if (r_refdef.viewcache.world_surfacevisible)
6235 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6236 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6239 void R_Main_ResizeViewCache(void)
6241 int numentities = r_refdef.scene.numentities;
6242 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6243 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6244 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6245 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6246 if (r_refdef.viewcache.maxentities < numentities)
6248 r_refdef.viewcache.maxentities = numentities;
6249 if (r_refdef.viewcache.entityvisible)
6250 Mem_Free(r_refdef.viewcache.entityvisible);
6251 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6253 if (r_refdef.viewcache.world_numclusters != numclusters)
6255 r_refdef.viewcache.world_numclusters = numclusters;
6256 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6257 if (r_refdef.viewcache.world_pvsbits)
6258 Mem_Free(r_refdef.viewcache.world_pvsbits);
6259 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6261 if (r_refdef.viewcache.world_numleafs != numleafs)
6263 r_refdef.viewcache.world_numleafs = numleafs;
6264 if (r_refdef.viewcache.world_leafvisible)
6265 Mem_Free(r_refdef.viewcache.world_leafvisible);
6266 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6268 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6270 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6271 if (r_refdef.viewcache.world_surfacevisible)
6272 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6273 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6277 extern rtexture_t *loadingscreentexture;
6278 void gl_main_start(void)
6280 loadingscreentexture = NULL;
6281 r_texture_blanknormalmap = NULL;
6282 r_texture_white = NULL;
6283 r_texture_grey128 = NULL;
6284 r_texture_black = NULL;
6285 r_texture_whitecube = NULL;
6286 r_texture_normalizationcube = NULL;
6287 r_texture_fogattenuation = NULL;
6288 r_texture_fogheighttexture = NULL;
6289 r_texture_gammaramps = NULL;
6290 r_texture_numcubemaps = 0;
6292 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6293 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6295 switch(vid.renderpath)
6297 case RENDERPATH_GL20:
6298 case RENDERPATH_CGGL:
6299 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6300 Cvar_SetValueQuick(&gl_combine, 1);
6301 Cvar_SetValueQuick(&r_glsl, 1);
6302 r_loadnormalmap = true;
6306 case RENDERPATH_GL13:
6307 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6308 Cvar_SetValueQuick(&gl_combine, 1);
6309 Cvar_SetValueQuick(&r_glsl, 0);
6310 r_loadnormalmap = false;
6311 r_loadgloss = false;
6314 case RENDERPATH_GL11:
6315 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6316 Cvar_SetValueQuick(&gl_combine, 0);
6317 Cvar_SetValueQuick(&r_glsl, 0);
6318 r_loadnormalmap = false;
6319 r_loadgloss = false;
6325 R_FrameData_Reset();
6329 memset(r_queries, 0, sizeof(r_queries));
6331 r_qwskincache = NULL;
6332 r_qwskincache_size = 0;
6334 // set up r_skinframe loading system for textures
6335 memset(&r_skinframe, 0, sizeof(r_skinframe));
6336 r_skinframe.loadsequence = 1;
6337 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6339 r_main_texturepool = R_AllocTexturePool();
6340 R_BuildBlankTextures();
6342 if (vid.support.arb_texture_cube_map)
6345 R_BuildNormalizationCube();
6347 r_texture_fogattenuation = NULL;
6348 r_texture_fogheighttexture = NULL;
6349 r_texture_gammaramps = NULL;
6350 //r_texture_fogintensity = NULL;
6351 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6352 memset(&r_waterstate, 0, sizeof(r_waterstate));
6353 r_glsl_permutation = NULL;
6354 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6355 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6356 glslshaderstring = NULL;
6358 r_cg_permutation = NULL;
6359 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6360 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6361 cgshaderstring = NULL;
6363 memset(&r_svbsp, 0, sizeof (r_svbsp));
6365 r_refdef.fogmasktable_density = 0;
6368 void gl_main_shutdown(void)
6371 R_FrameData_Reset();
6373 R_Main_FreeViewCache();
6376 qglDeleteQueriesARB(r_maxqueries, r_queries);
6380 memset(r_queries, 0, sizeof(r_queries));
6382 r_qwskincache = NULL;
6383 r_qwskincache_size = 0;
6385 // clear out the r_skinframe state
6386 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6387 memset(&r_skinframe, 0, sizeof(r_skinframe));
6390 Mem_Free(r_svbsp.nodes);
6391 memset(&r_svbsp, 0, sizeof (r_svbsp));
6392 R_FreeTexturePool(&r_main_texturepool);
6393 loadingscreentexture = NULL;
6394 r_texture_blanknormalmap = NULL;
6395 r_texture_white = NULL;
6396 r_texture_grey128 = NULL;
6397 r_texture_black = NULL;
6398 r_texture_whitecube = NULL;
6399 r_texture_normalizationcube = NULL;
6400 r_texture_fogattenuation = NULL;
6401 r_texture_fogheighttexture = NULL;
6402 r_texture_gammaramps = NULL;
6403 r_texture_numcubemaps = 0;
6404 //r_texture_fogintensity = NULL;
6405 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6406 memset(&r_waterstate, 0, sizeof(r_waterstate));
6407 r_glsl_permutation = NULL;
6408 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6409 glslshaderstring = NULL;
6411 r_cg_permutation = NULL;
6412 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6413 cgshaderstring = NULL;
6418 extern void CL_ParseEntityLump(char *entitystring);
6419 void gl_main_newmap(void)
6421 // FIXME: move this code to client
6422 char *entities, entname[MAX_QPATH];
6424 Mem_Free(r_qwskincache);
6425 r_qwskincache = NULL;
6426 r_qwskincache_size = 0;
6429 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
6430 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6432 CL_ParseEntityLump(entities);
6436 if (cl.worldmodel->brush.entities)
6437 CL_ParseEntityLump(cl.worldmodel->brush.entities);
6439 R_Main_FreeViewCache();
6441 R_FrameData_Reset();
6444 void GL_Main_Init(void)
6446 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6448 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6449 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6450 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6451 if (gamemode == GAME_NEHAHRA)
6453 Cvar_RegisterVariable (&gl_fogenable);
6454 Cvar_RegisterVariable (&gl_fogdensity);
6455 Cvar_RegisterVariable (&gl_fogred);
6456 Cvar_RegisterVariable (&gl_foggreen);
6457 Cvar_RegisterVariable (&gl_fogblue);
6458 Cvar_RegisterVariable (&gl_fogstart);
6459 Cvar_RegisterVariable (&gl_fogend);
6460 Cvar_RegisterVariable (&gl_skyclip);
6462 Cvar_RegisterVariable(&r_motionblur);
6463 Cvar_RegisterVariable(&r_motionblur_maxblur);
6464 Cvar_RegisterVariable(&r_motionblur_bmin);
6465 Cvar_RegisterVariable(&r_motionblur_vmin);
6466 Cvar_RegisterVariable(&r_motionblur_vmax);
6467 Cvar_RegisterVariable(&r_motionblur_vcoeff);
6468 Cvar_RegisterVariable(&r_motionblur_randomize);
6469 Cvar_RegisterVariable(&r_damageblur);
6470 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6471 Cvar_RegisterVariable(&r_equalize_entities_minambient);
6472 Cvar_RegisterVariable(&r_equalize_entities_by);
6473 Cvar_RegisterVariable(&r_equalize_entities_to);
6474 Cvar_RegisterVariable(&r_depthfirst);
6475 Cvar_RegisterVariable(&r_useinfinitefarclip);
6476 Cvar_RegisterVariable(&r_farclip_base);
6477 Cvar_RegisterVariable(&r_farclip_world);
6478 Cvar_RegisterVariable(&r_nearclip);
6479 Cvar_RegisterVariable(&r_showbboxes);
6480 Cvar_RegisterVariable(&r_showsurfaces);
6481 Cvar_RegisterVariable(&r_showtris);
6482 Cvar_RegisterVariable(&r_shownormals);
6483 Cvar_RegisterVariable(&r_showlighting);
6484 Cvar_RegisterVariable(&r_showshadowvolumes);
6485 Cvar_RegisterVariable(&r_showcollisionbrushes);
6486 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6487 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6488 Cvar_RegisterVariable(&r_showdisabledepthtest);
6489 Cvar_RegisterVariable(&r_drawportals);
6490 Cvar_RegisterVariable(&r_drawentities);
6491 Cvar_RegisterVariable(&r_draw2d);
6492 Cvar_RegisterVariable(&r_drawworld);
6493 Cvar_RegisterVariable(&r_cullentities_trace);
6494 Cvar_RegisterVariable(&r_cullentities_trace_samples);
6495 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6496 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6497 Cvar_RegisterVariable(&r_cullentities_trace_delay);
6498 Cvar_RegisterVariable(&r_drawviewmodel);
6499 Cvar_RegisterVariable(&r_drawexteriormodel);
6500 Cvar_RegisterVariable(&r_speeds);
6501 Cvar_RegisterVariable(&r_fullbrights);
6502 Cvar_RegisterVariable(&r_wateralpha);
6503 Cvar_RegisterVariable(&r_dynamic);
6504 Cvar_RegisterVariable(&r_fullbright);
6505 Cvar_RegisterVariable(&r_shadows);
6506 Cvar_RegisterVariable(&r_shadows_darken);
6507 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6508 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6509 Cvar_RegisterVariable(&r_shadows_throwdistance);
6510 Cvar_RegisterVariable(&r_shadows_throwdirection);
6511 Cvar_RegisterVariable(&r_shadows_focus);
6512 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6513 Cvar_RegisterVariable(&r_q1bsp_skymasking);
6514 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6515 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6516 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6517 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6518 Cvar_RegisterVariable(&r_fog_exp2);
6519 Cvar_RegisterVariable(&r_drawfog);
6520 Cvar_RegisterVariable(&r_transparentdepthmasking);
6521 Cvar_RegisterVariable(&r_texture_dds_load);
6522 Cvar_RegisterVariable(&r_texture_dds_save);
6523 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6524 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6525 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6526 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6527 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6528 Cvar_RegisterVariable(&r_textureunits);
6529 Cvar_RegisterVariable(&gl_combine);
6530 Cvar_RegisterVariable(&r_glsl);
6531 Cvar_RegisterVariable(&r_glsl_deluxemapping);
6532 Cvar_RegisterVariable(&r_glsl_offsetmapping);
6533 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6534 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6535 Cvar_RegisterVariable(&r_glsl_postprocess);
6536 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6537 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6538 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6539 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6540 Cvar_RegisterVariable(&r_water);
6541 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6542 Cvar_RegisterVariable(&r_water_clippingplanebias);
6543 Cvar_RegisterVariable(&r_water_refractdistort);
6544 Cvar_RegisterVariable(&r_water_reflectdistort);
6545 Cvar_RegisterVariable(&r_lerpsprites);
6546 Cvar_RegisterVariable(&r_lerpmodels);
6547 Cvar_RegisterVariable(&r_lerplightstyles);
6548 Cvar_RegisterVariable(&r_waterscroll);
6549 Cvar_RegisterVariable(&r_bloom);
6550 Cvar_RegisterVariable(&r_bloom_colorscale);
6551 Cvar_RegisterVariable(&r_bloom_brighten);
6552 Cvar_RegisterVariable(&r_bloom_blur);
6553 Cvar_RegisterVariable(&r_bloom_resolution);
6554 Cvar_RegisterVariable(&r_bloom_colorexponent);
6555 Cvar_RegisterVariable(&r_bloom_colorsubtract);
6556 Cvar_RegisterVariable(&r_hdr);
6557 Cvar_RegisterVariable(&r_hdr_scenebrightness);
6558 Cvar_RegisterVariable(&r_hdr_glowintensity);
6559 Cvar_RegisterVariable(&r_hdr_range);
6560 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6561 Cvar_RegisterVariable(&developer_texturelogging);
6562 Cvar_RegisterVariable(&gl_lightmaps);
6563 Cvar_RegisterVariable(&r_test);
6564 Cvar_RegisterVariable(&r_glsl_saturation);
6565 Cvar_RegisterVariable(&r_framedatasize);
6566 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
6567 Cvar_SetValue("r_fullbrights", 0);
6568 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
6570 Cvar_RegisterVariable(&r_track_sprites);
6571 Cvar_RegisterVariable(&r_track_sprites_flags);
6572 Cvar_RegisterVariable(&r_track_sprites_scalew);
6573 Cvar_RegisterVariable(&r_track_sprites_scaleh);
6574 Cvar_RegisterVariable(&r_overheadsprites_perspective);
6575 Cvar_RegisterVariable(&r_overheadsprites_pushback);
6578 extern void R_Textures_Init(void);
6579 extern void GL_Draw_Init(void);
6580 extern void GL_Main_Init(void);
6581 extern void R_Shadow_Init(void);
6582 extern void R_Sky_Init(void);
6583 extern void GL_Surf_Init(void);
6584 extern void R_Particles_Init(void);
6585 extern void R_Explosion_Init(void);
6586 extern void gl_backend_init(void);
6587 extern void Sbar_Init(void);
6588 extern void R_LightningBeams_Init(void);
6589 extern void Mod_RenderInit(void);
6590 extern void Font_Init(void);
6592 void Render_Init(void)
6605 R_LightningBeams_Init();
6614 extern char *ENGINE_EXTENSIONS;
6617 gl_renderer = (const char *)qglGetString(GL_RENDERER);
6618 gl_vendor = (const char *)qglGetString(GL_VENDOR);
6619 gl_version = (const char *)qglGetString(GL_VERSION);
6620 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
6624 if (!gl_platformextensions)
6625 gl_platformextensions = "";
6627 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
6628 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
6629 Con_Printf("GL_VERSION: %s\n", gl_version);
6630 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
6631 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
6633 VID_CheckExtensions();
6635 // LordHavoc: report supported extensions
6636 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
6638 // clear to black (loading plaque will be seen over this)
6640 qglClearColor(0,0,0,1);CHECKGLERROR
6641 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
6644 int R_CullBox(const vec3_t mins, const vec3_t maxs)
6648 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
6650 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
6653 p = r_refdef.view.frustum + i;
6658 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6662 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6666 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6670 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6674 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6678 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6682 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6686 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6694 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
6698 for (i = 0;i < numplanes;i++)
6705 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6709 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6713 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6717 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6721 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6725 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6729 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6733 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6741 //==================================================================================
6743 // LordHavoc: this stores temporary data used within the same frame
6745 qboolean r_framedata_failed;
6746 static size_t r_framedata_size;
6747 static size_t r_framedata_current;
6748 static void *r_framedata_base;
6750 void R_FrameData_Reset(void)
6752 if (r_framedata_base)
6753 Mem_Free(r_framedata_base);
6754 r_framedata_base = NULL;
6755 r_framedata_size = 0;
6756 r_framedata_current = 0;
6757 r_framedata_failed = false;
6760 void R_FrameData_NewFrame(void)
6763 if (r_framedata_failed)
6764 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
6765 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
6766 wantedsize = bound(65536, wantedsize, 128*1024*1024);
6767 if (r_framedata_size != wantedsize)
6769 r_framedata_size = wantedsize;
6770 if (r_framedata_base)
6771 Mem_Free(r_framedata_base);
6772 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
6774 r_framedata_current = 0;
6775 r_framedata_failed = false;
6778 void *R_FrameData_Alloc(size_t size)
6782 // align to 16 byte boundary
6783 size = (size + 15) & ~15;
6784 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
6785 r_framedata_current += size;
6788 if (r_framedata_current > r_framedata_size)
6789 r_framedata_failed = true;
6791 // return NULL on everything after a failure
6792 if (r_framedata_failed)
6798 void *R_FrameData_Store(size_t size, void *data)
6800 void *d = R_FrameData_Alloc(size);
6802 memcpy(d, data, size);
6806 //==================================================================================
6808 // LordHavoc: animcache originally written by Echon, rewritten since then
6811 * Animation cache prevents re-generating mesh data for an animated model
6812 * multiple times in one frame for lighting, shadowing, reflections, etc.
6815 void R_AnimCache_Free(void)
6819 void R_AnimCache_ClearCache(void)
6822 entity_render_t *ent;
6824 for (i = 0;i < r_refdef.scene.numentities;i++)
6826 ent = r_refdef.scene.entities[i];
6827 ent->animcache_vertex3f = NULL;
6828 ent->animcache_normal3f = NULL;
6829 ent->animcache_svector3f = NULL;
6830 ent->animcache_tvector3f = NULL;
6831 ent->animcache_vertexposition = NULL;
6832 ent->animcache_vertexmesh = NULL;
6833 ent->animcache_vertexpositionbuffer = NULL;
6834 ent->animcache_vertexmeshbuffer = NULL;
6838 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
6841 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
6842 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
6843 if (!ent->animcache_vertexposition)
6844 ent->animcache_vertexposition = (r_vertexposition_t *)R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
6845 if (ent->animcache_vertexposition)
6847 for (i = 0;i < numvertices;i++)
6848 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
6849 // TODO: upload vertex buffer?
6851 if (ent->animcache_vertexmesh)
6853 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
6854 for (i = 0;i < numvertices;i++)
6855 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
6856 if (ent->animcache_svector3f)
6857 for (i = 0;i < numvertices;i++)
6858 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
6859 if (ent->animcache_tvector3f)
6860 for (i = 0;i < numvertices;i++)
6861 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
6862 if (ent->animcache_normal3f)
6863 for (i = 0;i < numvertices;i++)
6864 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
6865 // TODO: upload vertex buffer?
6869 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
6871 dp_model_t *model = ent->model;
6873 // see if it's already cached this frame
6874 if (ent->animcache_vertex3f)
6876 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
6877 if (wantnormals || wanttangents)
6879 if (ent->animcache_normal3f)
6880 wantnormals = false;
6881 if (ent->animcache_svector3f)
6882 wanttangents = false;
6883 if (wantnormals || wanttangents)
6885 numvertices = model->surfmesh.num_vertices;
6887 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6890 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6891 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6893 if (!r_framedata_failed)
6895 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
6896 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6903 // see if this ent is worth caching
6904 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
6906 // get some memory for this entity and generate mesh data
6907 numvertices = model->surfmesh.num_vertices;
6908 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6910 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6913 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6914 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
6916 if (!r_framedata_failed)
6918 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
6919 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6922 return !r_framedata_failed;
6925 void R_AnimCache_CacheVisibleEntities(void)
6928 qboolean wantnormals = true;
6929 qboolean wanttangents = !r_showsurfaces.integer;
6931 switch(vid.renderpath)
6933 case RENDERPATH_GL20:
6934 case RENDERPATH_CGGL:
6936 case RENDERPATH_GL13:
6937 case RENDERPATH_GL11:
6938 wanttangents = false;
6942 if (r_shownormals.integer)
6943 wanttangents = wantnormals = true;
6945 // TODO: thread this
6946 // NOTE: R_PrepareRTLights() also caches entities
6948 for (i = 0;i < r_refdef.scene.numentities;i++)
6949 if (r_refdef.viewcache.entityvisible[i])
6950 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
6953 //==================================================================================
6955 static void R_View_UpdateEntityLighting (void)
6958 entity_render_t *ent;
6959 vec3_t tempdiffusenormal, avg;
6960 vec_t f, fa, fd, fdd;
6961 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
6963 for (i = 0;i < r_refdef.scene.numentities;i++)
6965 ent = r_refdef.scene.entities[i];
6967 // skip unseen models
6968 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
6972 if (ent->model && ent->model->brush.num_leafs)
6974 // TODO: use modellight for r_ambient settings on world?
6975 VectorSet(ent->modellight_ambient, 0, 0, 0);
6976 VectorSet(ent->modellight_diffuse, 0, 0, 0);
6977 VectorSet(ent->modellight_lightdir, 0, 0, 1);
6981 // fetch the lighting from the worldmodel data
6982 VectorClear(ent->modellight_ambient);
6983 VectorClear(ent->modellight_diffuse);
6984 VectorClear(tempdiffusenormal);
6985 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6988 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
6989 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
6990 if(ent->flags & RENDER_EQUALIZE)
6992 // first fix up ambient lighting...
6993 if(r_equalize_entities_minambient.value > 0)
6995 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
6998 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
6999 if(fa < r_equalize_entities_minambient.value * fd)
7002 // fa'/fd' = minambient
7003 // fa'+0.25*fd' = fa+0.25*fd
7005 // fa' = fd' * minambient
7006 // fd'*(0.25+minambient) = fa+0.25*fd
7008 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7009 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7011 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7012 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
7013 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7014 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7019 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7021 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7022 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7025 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7026 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7027 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7033 VectorSet(ent->modellight_ambient, 1, 1, 1);
7035 // move the light direction into modelspace coordinates for lighting code
7036 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7037 if(VectorLength2(ent->modellight_lightdir) == 0)
7038 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7039 VectorNormalize(ent->modellight_lightdir);
7043 #define MAX_LINEOFSIGHTTRACES 64
7045 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7048 vec3_t boxmins, boxmaxs;
7051 dp_model_t *model = r_refdef.scene.worldmodel;
7053 if (!model || !model->brush.TraceLineOfSight)
7056 // expand the box a little
7057 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7058 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7059 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7060 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7061 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7062 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7064 // return true if eye is inside enlarged box
7065 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7069 VectorCopy(eye, start);
7070 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7071 if (model->brush.TraceLineOfSight(model, start, end))
7074 // try various random positions
7075 for (i = 0;i < numsamples;i++)
7077 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7078 if (model->brush.TraceLineOfSight(model, start, end))
7086 static void R_View_UpdateEntityVisible (void)
7091 entity_render_t *ent;
7093 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7094 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7095 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
7096 : RENDER_EXTERIORMODEL;
7097 if (!r_drawviewmodel.integer)
7098 renderimask |= RENDER_VIEWMODEL;
7099 if (!r_drawexteriormodel.integer)
7100 renderimask |= RENDER_EXTERIORMODEL;
7101 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7103 // worldmodel can check visibility
7104 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7105 for (i = 0;i < r_refdef.scene.numentities;i++)
7107 ent = r_refdef.scene.entities[i];
7108 if (!(ent->flags & renderimask))
7109 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7110 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))
7111 r_refdef.viewcache.entityvisible[i] = true;
7113 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7114 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7116 for (i = 0;i < r_refdef.scene.numentities;i++)
7118 ent = r_refdef.scene.entities[i];
7119 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7121 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7123 continue; // temp entities do pvs only
7124 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7125 ent->last_trace_visibility = realtime;
7126 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7127 r_refdef.viewcache.entityvisible[i] = 0;
7134 // no worldmodel or it can't check visibility
7135 for (i = 0;i < r_refdef.scene.numentities;i++)
7137 ent = r_refdef.scene.entities[i];
7138 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));
7143 /// only used if skyrendermasked, and normally returns false
7144 int R_DrawBrushModelsSky (void)
7147 entity_render_t *ent;
7150 for (i = 0;i < r_refdef.scene.numentities;i++)
7152 if (!r_refdef.viewcache.entityvisible[i])
7154 ent = r_refdef.scene.entities[i];
7155 if (!ent->model || !ent->model->DrawSky)
7157 ent->model->DrawSky(ent);
7163 static void R_DrawNoModel(entity_render_t *ent);
7164 static void R_DrawModels(void)
7167 entity_render_t *ent;
7169 for (i = 0;i < r_refdef.scene.numentities;i++)
7171 if (!r_refdef.viewcache.entityvisible[i])
7173 ent = r_refdef.scene.entities[i];
7174 r_refdef.stats.entities++;
7175 if (ent->model && ent->model->Draw != NULL)
7176 ent->model->Draw(ent);
7182 static void R_DrawModelsDepth(void)
7185 entity_render_t *ent;
7187 for (i = 0;i < r_refdef.scene.numentities;i++)
7189 if (!r_refdef.viewcache.entityvisible[i])
7191 ent = r_refdef.scene.entities[i];
7192 if (ent->model && ent->model->DrawDepth != NULL)
7193 ent->model->DrawDepth(ent);
7197 static void R_DrawModelsDebug(void)
7200 entity_render_t *ent;
7202 for (i = 0;i < r_refdef.scene.numentities;i++)
7204 if (!r_refdef.viewcache.entityvisible[i])
7206 ent = r_refdef.scene.entities[i];
7207 if (ent->model && ent->model->DrawDebug != NULL)
7208 ent->model->DrawDebug(ent);
7212 static void R_DrawModelsAddWaterPlanes(void)
7215 entity_render_t *ent;
7217 for (i = 0;i < r_refdef.scene.numentities;i++)
7219 if (!r_refdef.viewcache.entityvisible[i])
7221 ent = r_refdef.scene.entities[i];
7222 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7223 ent->model->DrawAddWaterPlanes(ent);
7227 static void R_View_SetFrustum(void)
7230 double slopex, slopey;
7231 vec3_t forward, left, up, origin;
7233 // we can't trust r_refdef.view.forward and friends in reflected scenes
7234 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7237 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7238 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7239 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7240 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7241 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7242 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7243 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7244 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7245 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7246 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7247 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7248 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7252 zNear = r_refdef.nearclip;
7253 nudge = 1.0 - 1.0 / (1<<23);
7254 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7255 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7256 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7257 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7258 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7259 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7260 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7261 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7267 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7268 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7269 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7270 r_refdef.view.frustum[0].dist = m[15] - m[12];
7272 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7273 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7274 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7275 r_refdef.view.frustum[1].dist = m[15] + m[12];
7277 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7278 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7279 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7280 r_refdef.view.frustum[2].dist = m[15] - m[13];
7282 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7283 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7284 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7285 r_refdef.view.frustum[3].dist = m[15] + m[13];
7287 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7288 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7289 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7290 r_refdef.view.frustum[4].dist = m[15] - m[14];
7292 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7293 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7294 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7295 r_refdef.view.frustum[5].dist = m[15] + m[14];
7298 if (r_refdef.view.useperspective)
7300 slopex = 1.0 / r_refdef.view.frustum_x;
7301 slopey = 1.0 / r_refdef.view.frustum_y;
7302 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
7303 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
7304 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
7305 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
7306 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7308 // Leaving those out was a mistake, those were in the old code, and they
7309 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7310 // I couldn't reproduce it after adding those normalizations. --blub
7311 VectorNormalize(r_refdef.view.frustum[0].normal);
7312 VectorNormalize(r_refdef.view.frustum[1].normal);
7313 VectorNormalize(r_refdef.view.frustum[2].normal);
7314 VectorNormalize(r_refdef.view.frustum[3].normal);
7316 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7317 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]);
7318 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]);
7319 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]);
7320 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]);
7322 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7323 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7324 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7325 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7326 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7330 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7331 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7332 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7333 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7334 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7335 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7336 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7337 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7338 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7339 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7341 r_refdef.view.numfrustumplanes = 5;
7343 if (r_refdef.view.useclipplane)
7345 r_refdef.view.numfrustumplanes = 6;
7346 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7349 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7350 PlaneClassify(r_refdef.view.frustum + i);
7352 // LordHavoc: note to all quake engine coders, Quake had a special case
7353 // for 90 degrees which assumed a square view (wrong), so I removed it,
7354 // Quake2 has it disabled as well.
7356 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7357 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7358 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7359 //PlaneClassify(&frustum[0]);
7361 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7362 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7363 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7364 //PlaneClassify(&frustum[1]);
7366 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7367 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7368 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7369 //PlaneClassify(&frustum[2]);
7371 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7372 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7373 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7374 //PlaneClassify(&frustum[3]);
7377 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7378 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7379 //PlaneClassify(&frustum[4]);
7382 void R_View_Update(void)
7384 R_Main_ResizeViewCache();
7385 R_View_SetFrustum();
7386 R_View_WorldVisibility(r_refdef.view.useclipplane);
7387 R_View_UpdateEntityVisible();
7388 R_View_UpdateEntityLighting();
7391 void R_SetupView(qboolean allowwaterclippingplane)
7393 const float *customclipplane = NULL;
7395 if (r_refdef.view.useclipplane && allowwaterclippingplane)
7397 // LordHavoc: couldn't figure out how to make this approach the
7398 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7399 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7400 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7401 dist = r_refdef.view.clipplane.dist;
7402 plane[0] = r_refdef.view.clipplane.normal[0];
7403 plane[1] = r_refdef.view.clipplane.normal[1];
7404 plane[2] = r_refdef.view.clipplane.normal[2];
7406 customclipplane = plane;
7409 if (!r_refdef.view.useperspective)
7410 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);
7411 else if (vid.stencil && r_useinfinitefarclip.integer)
7412 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);
7414 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);
7415 R_SetViewport(&r_refdef.view.viewport);
7418 void R_EntityMatrix(const matrix4x4_t *matrix)
7420 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7422 gl_modelmatrixchanged = false;
7423 gl_modelmatrix = *matrix;
7424 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7425 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7426 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7427 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7429 switch(vid.renderpath)
7431 case RENDERPATH_GL20:
7432 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7433 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7434 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7436 case RENDERPATH_CGGL:
7439 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7440 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7441 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7444 case RENDERPATH_GL13:
7445 case RENDERPATH_GL11:
7446 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7452 void R_ResetViewRendering2D(void)
7454 r_viewport_t viewport;
7457 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7458 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);
7459 R_SetViewport(&viewport);
7460 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7461 GL_Color(1, 1, 1, 1);
7462 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7463 GL_BlendFunc(GL_ONE, GL_ZERO);
7464 GL_AlphaTest(false);
7465 GL_ScissorTest(false);
7466 GL_DepthMask(false);
7467 GL_DepthRange(0, 1);
7468 GL_DepthTest(false);
7469 R_EntityMatrix(&identitymatrix);
7470 R_Mesh_ResetTextureState();
7471 GL_PolygonOffset(0, 0);
7472 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7473 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7474 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7475 qglStencilMask(~0);CHECKGLERROR
7476 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7477 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7478 GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7481 void R_ResetViewRendering3D(void)
7486 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7487 GL_Color(1, 1, 1, 1);
7488 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7489 GL_BlendFunc(GL_ONE, GL_ZERO);
7490 GL_AlphaTest(false);
7491 GL_ScissorTest(true);
7493 GL_DepthRange(0, 1);
7495 R_EntityMatrix(&identitymatrix);
7496 R_Mesh_ResetTextureState();
7497 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7498 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7499 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7500 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7501 qglStencilMask(~0);CHECKGLERROR
7502 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7503 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7504 GL_CullFace(r_refdef.view.cullface_back);
7509 R_RenderView_UpdateViewVectors
7512 static void R_RenderView_UpdateViewVectors(void)
7514 // break apart the view matrix into vectors for various purposes
7515 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7516 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7517 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7518 VectorNegate(r_refdef.view.left, r_refdef.view.right);
7519 // make an inverted copy of the view matrix for tracking sprites
7520 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7523 void R_RenderScene(void);
7524 void R_RenderWaterPlanes(void);
7526 static void R_Water_StartFrame(void)
7529 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7530 r_waterstate_waterplane_t *p;
7532 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7535 switch(vid.renderpath)
7537 case RENDERPATH_GL20:
7538 case RENDERPATH_CGGL:
7540 case RENDERPATH_GL13:
7541 case RENDERPATH_GL11:
7545 // set waterwidth and waterheight to the water resolution that will be
7546 // used (often less than the screen resolution for faster rendering)
7547 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7548 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7550 // calculate desired texture sizes
7551 // can't use water if the card does not support the texture size
7552 if (!r_water.integer || r_showsurfaces.integer)
7553 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7554 else if (vid.support.arb_texture_non_power_of_two)
7556 texturewidth = waterwidth;
7557 textureheight = waterheight;
7558 camerawidth = waterwidth;
7559 cameraheight = waterheight;
7563 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
7564 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
7565 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
7566 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
7569 // allocate textures as needed
7570 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7572 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7573 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7575 if (p->texture_refraction)
7576 R_FreeTexture(p->texture_refraction);
7577 p->texture_refraction = NULL;
7578 if (p->texture_reflection)
7579 R_FreeTexture(p->texture_reflection);
7580 p->texture_reflection = NULL;
7581 if (p->texture_camera)
7582 R_FreeTexture(p->texture_camera);
7583 p->texture_camera = NULL;
7585 memset(&r_waterstate, 0, sizeof(r_waterstate));
7586 r_waterstate.texturewidth = texturewidth;
7587 r_waterstate.textureheight = textureheight;
7588 r_waterstate.camerawidth = camerawidth;
7589 r_waterstate.cameraheight = cameraheight;
7592 if (r_waterstate.texturewidth)
7594 r_waterstate.enabled = true;
7596 // when doing a reduced render (HDR) we want to use a smaller area
7597 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7598 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7600 // set up variables that will be used in shader setup
7601 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7602 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7603 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7604 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7607 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7608 r_waterstate.numwaterplanes = 0;
7611 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
7613 int triangleindex, planeindex;
7620 r_waterstate_waterplane_t *p;
7621 texture_t *t = R_GetCurrentTexture(surface->texture);
7622 cam_ent = t->camera_entity;
7623 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7626 // just use the first triangle with a valid normal for any decisions
7627 VectorClear(normal);
7628 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7630 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7631 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7632 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7633 TriangleNormal(vert[0], vert[1], vert[2], normal);
7634 if (VectorLength2(normal) >= 0.001)
7638 VectorCopy(normal, plane.normal);
7639 VectorNormalize(plane.normal);
7640 plane.dist = DotProduct(vert[0], plane.normal);
7641 PlaneClassify(&plane);
7642 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7644 // skip backfaces (except if nocullface is set)
7645 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7647 VectorNegate(plane.normal, plane.normal);
7649 PlaneClassify(&plane);
7653 // find a matching plane if there is one
7654 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7655 if(p->camera_entity == t->camera_entity)
7656 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7658 if (planeindex >= r_waterstate.maxwaterplanes)
7659 return; // nothing we can do, out of planes
7661 // if this triangle does not fit any known plane rendered this frame, add one
7662 if (planeindex >= r_waterstate.numwaterplanes)
7664 // store the new plane
7665 r_waterstate.numwaterplanes++;
7667 // clear materialflags and pvs
7668 p->materialflags = 0;
7669 p->pvsvalid = false;
7670 p->camera_entity = t->camera_entity;
7672 // merge this surface's materialflags into the waterplane
7673 p->materialflags |= t->currentmaterialflags;
7674 if(!(p->materialflags & MATERIALFLAG_CAMERA))
7676 // merge this surface's PVS into the waterplane
7677 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7678 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7679 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7681 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7687 static void R_Water_ProcessPlanes(void)
7689 r_refdef_view_t originalview;
7690 r_refdef_view_t myview;
7692 r_waterstate_waterplane_t *p;
7695 originalview = r_refdef.view;
7697 // make sure enough textures are allocated
7698 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7700 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7702 if (!p->texture_refraction)
7703 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, -1, NULL);
7704 if (!p->texture_refraction)
7707 else if (p->materialflags & MATERIALFLAG_CAMERA)
7709 if (!p->texture_camera)
7710 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, -1, NULL);
7711 if (!p->texture_camera)
7715 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7717 if (!p->texture_reflection)
7718 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, -1, NULL);
7719 if (!p->texture_reflection)
7725 r_refdef.view = originalview;
7726 r_refdef.view.showdebug = false;
7727 r_refdef.view.width = r_waterstate.waterwidth;
7728 r_refdef.view.height = r_waterstate.waterheight;
7729 r_refdef.view.useclipplane = true;
7730 myview = r_refdef.view;
7731 r_waterstate.renderingscene = true;
7732 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7734 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7736 r_refdef.view = myview;
7737 // render reflected scene and copy into texture
7738 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7739 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7740 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7741 r_refdef.view.clipplane = p->plane;
7742 // reverse the cullface settings for this render
7743 r_refdef.view.cullface_front = GL_FRONT;
7744 r_refdef.view.cullface_back = GL_BACK;
7745 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7747 r_refdef.view.usecustompvs = true;
7749 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7751 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7754 R_ResetViewRendering3D();
7755 R_ClearScreen(r_refdef.fogenabled);
7759 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);
7762 // render the normal view scene and copy into texture
7763 // (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)
7764 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7766 r_waterstate.renderingrefraction = true;
7767 r_refdef.view = myview;
7769 r_refdef.view.clipplane = p->plane;
7770 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7771 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7773 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7775 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7776 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7777 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7778 R_RenderView_UpdateViewVectors();
7779 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7781 r_refdef.view.usecustompvs = true;
7782 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);
7786 PlaneClassify(&r_refdef.view.clipplane);
7788 R_ResetViewRendering3D();
7789 R_ClearScreen(r_refdef.fogenabled);
7793 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);
7794 r_waterstate.renderingrefraction = false;
7796 else if (p->materialflags & MATERIALFLAG_CAMERA)
7798 r_refdef.view = myview;
7800 r_refdef.view.clipplane = p->plane;
7801 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7802 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7804 r_refdef.view.width = r_waterstate.camerawidth;
7805 r_refdef.view.height = r_waterstate.cameraheight;
7806 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7807 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7809 if(p->camera_entity)
7811 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7812 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7815 // reverse the cullface settings for this render
7816 r_refdef.view.cullface_front = GL_FRONT;
7817 r_refdef.view.cullface_back = GL_BACK;
7818 // also reverse the view matrix
7819 Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
7820 R_RenderView_UpdateViewVectors();
7821 if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7823 r_refdef.view.usecustompvs = true;
7824 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);
7827 // camera needs no clipplane
7828 r_refdef.view.useclipplane = false;
7830 PlaneClassify(&r_refdef.view.clipplane);
7832 R_ResetViewRendering3D();
7833 R_ClearScreen(r_refdef.fogenabled);
7837 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);
7838 r_waterstate.renderingrefraction = false;
7842 r_waterstate.renderingscene = false;
7843 r_refdef.view = originalview;
7844 R_ResetViewRendering3D();
7845 R_ClearScreen(r_refdef.fogenabled);
7849 r_refdef.view = originalview;
7850 r_waterstate.renderingscene = false;
7851 Cvar_SetValueQuick(&r_water, 0);
7852 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
7856 void R_Bloom_StartFrame(void)
7858 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
7860 switch(vid.renderpath)
7862 case RENDERPATH_GL20:
7863 case RENDERPATH_CGGL:
7865 case RENDERPATH_GL13:
7866 case RENDERPATH_GL11:
7870 // set bloomwidth and bloomheight to the bloom resolution that will be
7871 // used (often less than the screen resolution for faster rendering)
7872 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
7873 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
7874 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
7875 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
7876 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
7878 // calculate desired texture sizes
7879 if (vid.support.arb_texture_non_power_of_two)
7881 screentexturewidth = r_refdef.view.width;
7882 screentextureheight = r_refdef.view.height;
7883 bloomtexturewidth = r_bloomstate.bloomwidth;
7884 bloomtextureheight = r_bloomstate.bloomheight;
7888 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
7889 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
7890 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
7891 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
7894 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))
7896 Cvar_SetValueQuick(&r_hdr, 0);
7897 Cvar_SetValueQuick(&r_bloom, 0);
7898 Cvar_SetValueQuick(&r_motionblur, 0);
7899 Cvar_SetValueQuick(&r_damageblur, 0);
7902 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)))
7903 screentexturewidth = screentextureheight = 0;
7904 if (!r_hdr.integer && !r_bloom.integer)
7905 bloomtexturewidth = bloomtextureheight = 0;
7907 // allocate textures as needed
7908 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
7910 if (r_bloomstate.texture_screen)
7911 R_FreeTexture(r_bloomstate.texture_screen);
7912 r_bloomstate.texture_screen = NULL;
7913 r_bloomstate.screentexturewidth = screentexturewidth;
7914 r_bloomstate.screentextureheight = screentextureheight;
7915 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
7916 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
7918 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
7920 if (r_bloomstate.texture_bloom)
7921 R_FreeTexture(r_bloomstate.texture_bloom);
7922 r_bloomstate.texture_bloom = NULL;
7923 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
7924 r_bloomstate.bloomtextureheight = bloomtextureheight;
7925 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
7926 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7929 // when doing a reduced render (HDR) we want to use a smaller area
7930 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
7931 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
7932 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
7933 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
7934 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
7936 // set up a texcoord array for the full resolution screen image
7937 // (we have to keep this around to copy back during final render)
7938 r_bloomstate.screentexcoord2f[0] = 0;
7939 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7940 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7941 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7942 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7943 r_bloomstate.screentexcoord2f[5] = 0;
7944 r_bloomstate.screentexcoord2f[6] = 0;
7945 r_bloomstate.screentexcoord2f[7] = 0;
7947 // set up a texcoord array for the reduced resolution bloom image
7948 // (which will be additive blended over the screen image)
7949 r_bloomstate.bloomtexcoord2f[0] = 0;
7950 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7951 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7952 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7953 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7954 r_bloomstate.bloomtexcoord2f[5] = 0;
7955 r_bloomstate.bloomtexcoord2f[6] = 0;
7956 r_bloomstate.bloomtexcoord2f[7] = 0;
7958 if (r_hdr.integer || r_bloom.integer)
7960 r_bloomstate.enabled = true;
7961 r_bloomstate.hdr = r_hdr.integer != 0;
7964 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);
7967 void R_Bloom_CopyBloomTexture(float colorscale)
7969 r_refdef.stats.bloom++;
7971 // scale down screen texture to the bloom texture size
7973 R_SetViewport(&r_bloomstate.viewport);
7974 GL_BlendFunc(GL_ONE, GL_ZERO);
7975 GL_Color(colorscale, colorscale, colorscale, 1);
7976 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
7977 // TODO: do boxfilter scale-down in shader?
7978 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
7979 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7980 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7982 // we now have a bloom image in the framebuffer
7983 // copy it into the bloom image texture for later processing
7984 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);
7985 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7988 void R_Bloom_CopyHDRTexture(void)
7990 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);
7991 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
7994 void R_Bloom_MakeTexture(void)
7997 float xoffset, yoffset, r, brighten;
7999 r_refdef.stats.bloom++;
8001 R_ResetViewRendering2D();
8003 // we have a bloom image in the framebuffer
8005 R_SetViewport(&r_bloomstate.viewport);
8007 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8010 r = bound(0, r_bloom_colorexponent.value / x, 1);
8011 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8013 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8014 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8015 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8016 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8018 // copy the vertically blurred bloom view to a texture
8019 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);
8020 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8023 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8024 brighten = r_bloom_brighten.value;
8026 brighten *= r_hdr_range.value;
8027 brighten = sqrt(brighten);
8029 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8030 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8032 for (dir = 0;dir < 2;dir++)
8034 // blend on at multiple vertical offsets to achieve a vertical blur
8035 // TODO: do offset blends using GLSL
8036 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8037 GL_BlendFunc(GL_ONE, GL_ZERO);
8038 for (x = -range;x <= range;x++)
8040 if (!dir){xoffset = 0;yoffset = x;}
8041 else {xoffset = x;yoffset = 0;}
8042 xoffset /= (float)r_bloomstate.bloomtexturewidth;
8043 yoffset /= (float)r_bloomstate.bloomtextureheight;
8044 // compute a texcoord array with the specified x and y offset
8045 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8046 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8047 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8048 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8049 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8050 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8051 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8052 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8053 // this r value looks like a 'dot' particle, fading sharply to
8054 // black at the edges
8055 // (probably not realistic but looks good enough)
8056 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8057 //r = brighten/(range*2+1);
8058 r = brighten / (range * 2 + 1);
8060 r *= (1 - x*x/(float)(range*range));
8061 GL_Color(r, r, r, 1);
8062 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8063 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8064 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8065 GL_BlendFunc(GL_ONE, GL_ONE);
8068 // copy the vertically blurred bloom view to a texture
8069 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);
8070 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8073 // apply subtract last
8074 // (just like it would be in a GLSL shader)
8075 if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
8077 GL_BlendFunc(GL_ONE, GL_ZERO);
8079 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8080 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8081 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8082 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8084 GL_BlendFunc(GL_ONE, GL_ONE);
8085 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
8086 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8087 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
8088 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8089 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8090 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8091 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
8093 // copy the darkened bloom view to a texture
8094 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);
8095 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8099 void R_HDR_RenderBloomTexture(void)
8101 int oldwidth, oldheight;
8102 float oldcolorscale;
8104 oldcolorscale = r_refdef.view.colorscale;
8105 oldwidth = r_refdef.view.width;
8106 oldheight = r_refdef.view.height;
8107 r_refdef.view.width = r_bloomstate.bloomwidth;
8108 r_refdef.view.height = r_bloomstate.bloomheight;
8110 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
8111 // TODO: add exposure compensation features
8112 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8114 r_refdef.view.showdebug = false;
8115 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8117 R_ResetViewRendering3D();
8119 R_ClearScreen(r_refdef.fogenabled);
8120 if (r_timereport_active)
8121 R_TimeReport("HDRclear");
8124 if (r_timereport_active)
8125 R_TimeReport("visibility");
8127 // only do secondary renders with HDR if r_hdr is 2 or higher
8128 r_waterstate.numwaterplanes = 0;
8129 if (r_waterstate.enabled && r_hdr.integer >= 2)
8130 R_RenderWaterPlanes();
8132 r_refdef.view.showdebug = true;
8134 r_waterstate.numwaterplanes = 0;
8136 R_ResetViewRendering2D();
8138 R_Bloom_CopyHDRTexture();
8139 R_Bloom_MakeTexture();
8141 // restore the view settings
8142 r_refdef.view.width = oldwidth;
8143 r_refdef.view.height = oldheight;
8144 r_refdef.view.colorscale = oldcolorscale;
8146 R_ResetViewRendering3D();
8148 R_ClearScreen(r_refdef.fogenabled);
8149 if (r_timereport_active)
8150 R_TimeReport("viewclear");
8153 static void R_BlendView(void)
8155 unsigned int permutation;
8156 float uservecs[4][4];
8158 switch (vid.renderpath)
8160 case RENDERPATH_GL20:
8161 case RENDERPATH_CGGL:
8163 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8164 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8165 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8166 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8167 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8169 if (r_bloomstate.texture_screen)
8171 // make sure the buffer is available
8172 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8174 R_ResetViewRendering2D();
8176 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8178 // declare variables
8180 static float avgspeed;
8182 speed = VectorLength(cl.movement_velocity);
8184 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8185 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8187 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8188 speed = bound(0, speed, 1);
8189 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8191 // calculate values into a standard alpha
8192 cl.motionbluralpha = 1 - exp(-
8194 (r_motionblur.value * speed / 80)
8196 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8199 max(0.0001, cl.time - cl.oldtime) // fps independent
8202 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8203 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8205 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8207 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8208 GL_Color(1, 1, 1, cl.motionbluralpha);
8209 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8210 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8211 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8212 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8216 // copy view into the screen texture
8217 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);
8218 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8220 else if (!r_bloomstate.texture_bloom)
8222 // we may still have to do view tint...
8223 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8225 // apply a color tint to the whole view
8226 R_ResetViewRendering2D();
8227 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8228 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8229 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8230 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8231 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8233 break; // no screen processing, no bloom, skip it
8236 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8238 // render simple bloom effect
8239 // copy the screen and shrink it and darken it for the bloom process
8240 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8241 // make the bloom texture
8242 R_Bloom_MakeTexture();
8245 #if _MSC_VER >= 1400
8246 #define sscanf sscanf_s
8248 memset(uservecs, 0, sizeof(uservecs));
8249 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8250 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8251 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8252 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8254 R_ResetViewRendering2D();
8255 GL_Color(1, 1, 1, 1);
8256 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8257 GL_BlendFunc(GL_ONE, GL_ZERO);
8259 switch(vid.renderpath)
8261 case RENDERPATH_GL20:
8262 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8263 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8264 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8265 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8266 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]);
8267 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8268 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]);
8269 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]);
8270 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]);
8271 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]);
8272 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8273 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8275 case RENDERPATH_CGGL:
8277 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8278 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
8279 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
8280 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
8281 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
8282 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8283 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
8284 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
8285 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
8286 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
8287 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
8288 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8294 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8295 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8297 case RENDERPATH_GL13:
8298 case RENDERPATH_GL11:
8299 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8301 // apply a color tint to the whole view
8302 R_ResetViewRendering2D();
8303 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8304 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8305 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8306 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8307 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8313 matrix4x4_t r_waterscrollmatrix;
8315 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8317 if (r_refdef.fog_density)
8319 r_refdef.fogcolor[0] = r_refdef.fog_red;
8320 r_refdef.fogcolor[1] = r_refdef.fog_green;
8321 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8323 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8324 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8325 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8326 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8330 VectorCopy(r_refdef.fogcolor, fogvec);
8331 // color.rgb *= ContrastBoost * SceneBrightness;
8332 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8333 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8334 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8335 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8340 void R_UpdateVariables(void)
8344 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8346 r_refdef.farclip = r_farclip_base.value;
8347 if (r_refdef.scene.worldmodel)
8348 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8349 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8351 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8352 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8353 r_refdef.polygonfactor = 0;
8354 r_refdef.polygonoffset = 0;
8355 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8356 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8358 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8359 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8360 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8361 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8362 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8363 if (r_showsurfaces.integer)
8365 r_refdef.scene.rtworld = false;
8366 r_refdef.scene.rtworldshadows = false;
8367 r_refdef.scene.rtdlight = false;
8368 r_refdef.scene.rtdlightshadows = false;
8369 r_refdef.lightmapintensity = 0;
8372 if (gamemode == GAME_NEHAHRA)
8374 if (gl_fogenable.integer)
8376 r_refdef.oldgl_fogenable = true;
8377 r_refdef.fog_density = gl_fogdensity.value;
8378 r_refdef.fog_red = gl_fogred.value;
8379 r_refdef.fog_green = gl_foggreen.value;
8380 r_refdef.fog_blue = gl_fogblue.value;
8381 r_refdef.fog_alpha = 1;
8382 r_refdef.fog_start = 0;
8383 r_refdef.fog_end = gl_skyclip.value;
8384 r_refdef.fog_height = 1<<30;
8385 r_refdef.fog_fadedepth = 128;
8387 else if (r_refdef.oldgl_fogenable)
8389 r_refdef.oldgl_fogenable = false;
8390 r_refdef.fog_density = 0;
8391 r_refdef.fog_red = 0;
8392 r_refdef.fog_green = 0;
8393 r_refdef.fog_blue = 0;
8394 r_refdef.fog_alpha = 0;
8395 r_refdef.fog_start = 0;
8396 r_refdef.fog_end = 0;
8397 r_refdef.fog_height = 1<<30;
8398 r_refdef.fog_fadedepth = 128;
8402 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8403 r_refdef.fog_start = max(0, r_refdef.fog_start);
8404 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8406 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8408 if (r_refdef.fog_density && r_drawfog.integer)
8410 r_refdef.fogenabled = true;
8411 // this is the point where the fog reaches 0.9986 alpha, which we
8412 // consider a good enough cutoff point for the texture
8413 // (0.9986 * 256 == 255.6)
8414 if (r_fog_exp2.integer)
8415 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8417 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8418 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8419 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8420 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8421 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8422 R_BuildFogHeightTexture();
8423 // fog color was already set
8424 // update the fog texture
8425 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)
8426 R_BuildFogTexture();
8427 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8428 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8431 r_refdef.fogenabled = false;
8433 switch(vid.renderpath)
8435 case RENDERPATH_GL20:
8436 case RENDERPATH_CGGL:
8437 if(v_glslgamma.integer && !vid_gammatables_trivial)
8439 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8441 // build GLSL gamma texture
8442 #define RAMPWIDTH 256
8443 unsigned short ramp[RAMPWIDTH * 3];
8444 unsigned char rampbgr[RAMPWIDTH][4];
8447 r_texture_gammaramps_serial = vid_gammatables_serial;
8449 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8450 for(i = 0; i < RAMPWIDTH; ++i)
8452 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8453 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8454 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8457 if (r_texture_gammaramps)
8459 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8463 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
8469 // remove GLSL gamma texture
8472 case RENDERPATH_GL13:
8473 case RENDERPATH_GL11:
8478 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8479 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8485 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8486 if( scenetype != r_currentscenetype ) {
8487 // store the old scenetype
8488 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8489 r_currentscenetype = scenetype;
8490 // move in the new scene
8491 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8500 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8502 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8503 if( scenetype == r_currentscenetype ) {
8504 return &r_refdef.scene;
8506 return &r_scenes_store[ scenetype ];
8515 void R_RenderView(void)
8517 if (r_timereport_active)
8518 R_TimeReport("start");
8519 r_textureframe++; // used only by R_GetCurrentTexture
8520 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8522 if (!r_drawentities.integer)
8523 r_refdef.scene.numentities = 0;
8525 R_AnimCache_ClearCache();
8526 R_FrameData_NewFrame();
8528 if (r_refdef.view.isoverlay)
8530 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8531 GL_Clear( GL_DEPTH_BUFFER_BIT );
8532 R_TimeReport("depthclear");
8534 r_refdef.view.showdebug = false;
8536 r_waterstate.enabled = false;
8537 r_waterstate.numwaterplanes = 0;
8545 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8546 return; //Host_Error ("R_RenderView: NULL worldmodel");
8548 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8550 R_RenderView_UpdateViewVectors();
8552 R_Shadow_UpdateWorldLightSelection();
8554 R_Bloom_StartFrame();
8555 R_Water_StartFrame();
8558 if (r_timereport_active)
8559 R_TimeReport("viewsetup");
8561 R_ResetViewRendering3D();
8563 if (r_refdef.view.clear || r_refdef.fogenabled)
8565 R_ClearScreen(r_refdef.fogenabled);
8566 if (r_timereport_active)
8567 R_TimeReport("viewclear");
8569 r_refdef.view.clear = true;
8571 // this produces a bloom texture to be used in R_BlendView() later
8572 if (r_hdr.integer && r_bloomstate.bloomwidth)
8574 R_HDR_RenderBloomTexture();
8575 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8576 r_textureframe++; // used only by R_GetCurrentTexture
8579 r_refdef.view.showdebug = true;
8582 if (r_timereport_active)
8583 R_TimeReport("visibility");
8585 r_waterstate.numwaterplanes = 0;
8586 if (r_waterstate.enabled)
8587 R_RenderWaterPlanes();
8590 r_waterstate.numwaterplanes = 0;
8593 if (r_timereport_active)
8594 R_TimeReport("blendview");
8596 GL_Scissor(0, 0, vid.width, vid.height);
8597 GL_ScissorTest(false);
8601 void R_RenderWaterPlanes(void)
8603 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8605 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8606 if (r_timereport_active)
8607 R_TimeReport("waterworld");
8610 // don't let sound skip if going slow
8611 if (r_refdef.scene.extraupdate)
8614 R_DrawModelsAddWaterPlanes();
8615 if (r_timereport_active)
8616 R_TimeReport("watermodels");
8618 if (r_waterstate.numwaterplanes)
8620 R_Water_ProcessPlanes();
8621 if (r_timereport_active)
8622 R_TimeReport("waterscenes");
8626 extern void R_DrawLightningBeams (void);
8627 extern void VM_CL_AddPolygonsToMeshQueue (void);
8628 extern void R_DrawPortals (void);
8629 extern cvar_t cl_locs_show;
8630 static void R_DrawLocs(void);
8631 static void R_DrawEntityBBoxes(void);
8632 static void R_DrawModelDecals(void);
8633 extern void R_DrawModelShadows(void);
8634 extern void R_DrawModelShadowMaps(void);
8635 extern cvar_t cl_decals_newsystem;
8636 extern qboolean r_shadow_usingdeferredprepass;
8637 void R_RenderScene(void)
8639 qboolean shadowmapping = false;
8641 if (r_timereport_active)
8642 R_TimeReport("beginscene");
8644 r_refdef.stats.renders++;
8648 // don't let sound skip if going slow
8649 if (r_refdef.scene.extraupdate)
8652 R_MeshQueue_BeginScene();
8656 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);
8658 if (r_timereport_active)
8659 R_TimeReport("skystartframe");
8661 if (cl.csqc_vidvars.drawworld)
8663 // don't let sound skip if going slow
8664 if (r_refdef.scene.extraupdate)
8667 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8669 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8670 if (r_timereport_active)
8671 R_TimeReport("worldsky");
8674 if (R_DrawBrushModelsSky() && r_timereport_active)
8675 R_TimeReport("bmodelsky");
8677 if (skyrendermasked && skyrenderlater)
8679 // we have to force off the water clipping plane while rendering sky
8683 if (r_timereport_active)
8684 R_TimeReport("sky");
8688 R_AnimCache_CacheVisibleEntities();
8689 if (r_timereport_active)
8690 R_TimeReport("animation");
8692 R_Shadow_PrepareLights();
8693 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8694 R_Shadow_PrepareModelShadows();
8695 if (r_timereport_active)
8696 R_TimeReport("preparelights");
8698 if (R_Shadow_ShadowMappingEnabled())
8699 shadowmapping = true;
8701 if (r_shadow_usingdeferredprepass)
8702 R_Shadow_DrawPrepass();
8704 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8706 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8707 if (r_timereport_active)
8708 R_TimeReport("worlddepth");
8710 if (r_depthfirst.integer >= 2)
8712 R_DrawModelsDepth();
8713 if (r_timereport_active)
8714 R_TimeReport("modeldepth");
8717 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8719 R_DrawModelShadowMaps();
8720 R_ResetViewRendering3D();
8721 // don't let sound skip if going slow
8722 if (r_refdef.scene.extraupdate)
8726 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8728 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8729 if (r_timereport_active)
8730 R_TimeReport("world");
8733 // don't let sound skip if going slow
8734 if (r_refdef.scene.extraupdate)
8738 if (r_timereport_active)
8739 R_TimeReport("models");
8741 // don't let sound skip if going slow
8742 if (r_refdef.scene.extraupdate)
8745 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8747 R_DrawModelShadows();
8748 R_ResetViewRendering3D();
8749 // don't let sound skip if going slow
8750 if (r_refdef.scene.extraupdate)
8754 if (!r_shadow_usingdeferredprepass)
8756 R_Shadow_DrawLights();
8757 if (r_timereport_active)
8758 R_TimeReport("rtlights");
8761 // don't let sound skip if going slow
8762 if (r_refdef.scene.extraupdate)
8765 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8767 R_DrawModelShadows();
8768 R_ResetViewRendering3D();
8769 // don't let sound skip if going slow
8770 if (r_refdef.scene.extraupdate)
8774 if (cl.csqc_vidvars.drawworld)
8776 if (cl_decals_newsystem.integer)
8778 R_DrawModelDecals();
8779 if (r_timereport_active)
8780 R_TimeReport("modeldecals");
8785 if (r_timereport_active)
8786 R_TimeReport("decals");
8790 if (r_timereport_active)
8791 R_TimeReport("particles");
8794 if (r_timereport_active)
8795 R_TimeReport("explosions");
8797 R_DrawLightningBeams();
8798 if (r_timereport_active)
8799 R_TimeReport("lightning");
8802 VM_CL_AddPolygonsToMeshQueue();
8804 if (r_refdef.view.showdebug)
8806 if (cl_locs_show.integer)
8809 if (r_timereport_active)
8810 R_TimeReport("showlocs");
8813 if (r_drawportals.integer)
8816 if (r_timereport_active)
8817 R_TimeReport("portals");
8820 if (r_showbboxes.value > 0)
8822 R_DrawEntityBBoxes();
8823 if (r_timereport_active)
8824 R_TimeReport("bboxes");
8828 R_MeshQueue_RenderTransparent();
8829 if (r_timereport_active)
8830 R_TimeReport("drawtrans");
8832 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))
8834 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
8835 if (r_timereport_active)
8836 R_TimeReport("worlddebug");
8837 R_DrawModelsDebug();
8838 if (r_timereport_active)
8839 R_TimeReport("modeldebug");
8842 if (cl.csqc_vidvars.drawworld)
8844 R_Shadow_DrawCoronas();
8845 if (r_timereport_active)
8846 R_TimeReport("coronas");
8849 // don't let sound skip if going slow
8850 if (r_refdef.scene.extraupdate)
8853 R_ResetViewRendering2D();
8856 static const unsigned short bboxelements[36] =
8866 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
8869 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
8871 RSurf_ActiveWorldEntity();
8873 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8874 GL_DepthMask(false);
8875 GL_DepthRange(0, 1);
8876 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8877 R_Mesh_ResetTextureState();
8879 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
8880 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
8881 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
8882 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
8883 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
8884 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
8885 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
8886 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
8887 R_FillColors(color4f, 8, cr, cg, cb, ca);
8888 if (r_refdef.fogenabled)
8890 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
8892 f1 = RSurf_FogVertex(v);
8894 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
8895 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
8896 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
8899 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
8900 R_Mesh_ResetTextureState();
8901 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8902 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
8905 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8909 prvm_edict_t *edict;
8910 prvm_prog_t *prog_save = prog;
8912 // this function draws bounding boxes of server entities
8916 GL_CullFace(GL_NONE);
8917 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8921 for (i = 0;i < numsurfaces;i++)
8923 edict = PRVM_EDICT_NUM(surfacelist[i]);
8924 switch ((int)edict->fields.server->solid)
8926 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
8927 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
8928 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
8929 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
8930 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
8931 default: Vector4Set(color, 0, 0, 0, 0.50);break;
8933 color[3] *= r_showbboxes.value;
8934 color[3] = bound(0, color[3], 1);
8935 GL_DepthTest(!r_showdisabledepthtest.integer);
8936 GL_CullFace(r_refdef.view.cullface_front);
8937 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
8943 static void R_DrawEntityBBoxes(void)
8946 prvm_edict_t *edict;
8948 prvm_prog_t *prog_save = prog;
8950 // this function draws bounding boxes of server entities
8956 for (i = 0;i < prog->num_edicts;i++)
8958 edict = PRVM_EDICT_NUM(i);
8959 if (edict->priv.server->free)
8961 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
8962 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
8964 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
8966 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
8967 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
8973 static const int nomodelelement3i[24] =
8985 static const unsigned short nomodelelement3s[24] =
8997 static const float nomodelvertex3f[6*3] =
9007 static const float nomodelcolor4f[6*4] =
9009 0.0f, 0.0f, 0.5f, 1.0f,
9010 0.0f, 0.0f, 0.5f, 1.0f,
9011 0.0f, 0.5f, 0.0f, 1.0f,
9012 0.0f, 0.5f, 0.0f, 1.0f,
9013 0.5f, 0.0f, 0.0f, 1.0f,
9014 0.5f, 0.0f, 0.0f, 1.0f
9017 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9023 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);
9025 // this is only called once per entity so numsurfaces is always 1, and
9026 // surfacelist is always {0}, so this code does not handle batches
9028 if (rsurface.ent_flags & RENDER_ADDITIVE)
9030 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9031 GL_DepthMask(false);
9033 else if (rsurface.colormod[3] < 1)
9035 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9036 GL_DepthMask(false);
9040 GL_BlendFunc(GL_ONE, GL_ZERO);
9043 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9044 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9045 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9046 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9047 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9048 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9049 for (i = 0, c = color4f;i < 6;i++, c += 4)
9051 c[0] *= rsurface.colormod[0];
9052 c[1] *= rsurface.colormod[1];
9053 c[2] *= rsurface.colormod[2];
9054 c[3] *= rsurface.colormod[3];
9056 if (r_refdef.fogenabled)
9058 for (i = 0, c = color4f;i < 6;i++, c += 4)
9060 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9062 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9063 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9064 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9067 R_Mesh_ResetTextureState();
9068 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9069 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9072 void R_DrawNoModel(entity_render_t *ent)
9075 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9076 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9077 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9079 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9082 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9084 vec3_t right1, right2, diff, normal;
9086 VectorSubtract (org2, org1, normal);
9088 // calculate 'right' vector for start
9089 VectorSubtract (r_refdef.view.origin, org1, diff);
9090 CrossProduct (normal, diff, right1);
9091 VectorNormalize (right1);
9093 // calculate 'right' vector for end
9094 VectorSubtract (r_refdef.view.origin, org2, diff);
9095 CrossProduct (normal, diff, right2);
9096 VectorNormalize (right2);
9098 vert[ 0] = org1[0] + width * right1[0];
9099 vert[ 1] = org1[1] + width * right1[1];
9100 vert[ 2] = org1[2] + width * right1[2];
9101 vert[ 3] = org1[0] - width * right1[0];
9102 vert[ 4] = org1[1] - width * right1[1];
9103 vert[ 5] = org1[2] - width * right1[2];
9104 vert[ 6] = org2[0] - width * right2[0];
9105 vert[ 7] = org2[1] - width * right2[1];
9106 vert[ 8] = org2[2] - width * right2[2];
9107 vert[ 9] = org2[0] + width * right2[0];
9108 vert[10] = org2[1] + width * right2[1];
9109 vert[11] = org2[2] + width * right2[2];
9112 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)
9114 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9115 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9116 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9117 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9118 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9119 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9120 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9121 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9122 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9123 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9124 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9125 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9128 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9133 VectorSet(v, x, y, z);
9134 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9135 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9137 if (i == mesh->numvertices)
9139 if (mesh->numvertices < mesh->maxvertices)
9141 VectorCopy(v, vertex3f);
9142 mesh->numvertices++;
9144 return mesh->numvertices;
9150 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9154 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9155 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9156 e = mesh->element3i + mesh->numtriangles * 3;
9157 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9159 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9160 if (mesh->numtriangles < mesh->maxtriangles)
9165 mesh->numtriangles++;
9167 element[1] = element[2];
9171 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9175 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9176 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9177 e = mesh->element3i + mesh->numtriangles * 3;
9178 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9180 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9181 if (mesh->numtriangles < mesh->maxtriangles)
9186 mesh->numtriangles++;
9188 element[1] = element[2];
9192 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9193 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9195 int planenum, planenum2;
9198 mplane_t *plane, *plane2;
9200 double temppoints[2][256*3];
9201 // figure out how large a bounding box we need to properly compute this brush
9203 for (w = 0;w < numplanes;w++)
9204 maxdist = max(maxdist, fabs(planes[w].dist));
9205 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9206 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9207 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9211 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9212 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9214 if (planenum2 == planenum)
9216 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);
9219 if (tempnumpoints < 3)
9221 // generate elements forming a triangle fan for this polygon
9222 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9226 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)
9228 texturelayer_t *layer;
9229 layer = t->currentlayers + t->currentnumlayers++;
9231 layer->depthmask = depthmask;
9232 layer->blendfunc1 = blendfunc1;
9233 layer->blendfunc2 = blendfunc2;
9234 layer->texture = texture;
9235 layer->texmatrix = *matrix;
9236 layer->color[0] = r;
9237 layer->color[1] = g;
9238 layer->color[2] = b;
9239 layer->color[3] = a;
9242 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
9244 if(parms[0] == 0 && parms[1] == 0)
9246 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9247 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
9252 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9255 index = parms[2] + r_refdef.scene.time * parms[3];
9256 index -= floor(index);
9257 switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
9260 case Q3WAVEFUNC_NONE:
9261 case Q3WAVEFUNC_NOISE:
9262 case Q3WAVEFUNC_COUNT:
9265 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9266 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9267 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9268 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9269 case Q3WAVEFUNC_TRIANGLE:
9271 f = index - floor(index);
9282 f = parms[0] + parms[1] * f;
9283 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9284 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
9288 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9293 matrix4x4_t matrix, temp;
9294 switch(tcmod->tcmod)
9298 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9299 matrix = r_waterscrollmatrix;
9301 matrix = identitymatrix;
9303 case Q3TCMOD_ENTITYTRANSLATE:
9304 // this is used in Q3 to allow the gamecode to control texcoord
9305 // scrolling on the entity, which is not supported in darkplaces yet.
9306 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9308 case Q3TCMOD_ROTATE:
9309 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9310 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9311 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9314 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9316 case Q3TCMOD_SCROLL:
9317 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9319 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9320 w = (int) tcmod->parms[0];
9321 h = (int) tcmod->parms[1];
9322 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9324 idx = (int) floor(f * w * h);
9325 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9327 case Q3TCMOD_STRETCH:
9328 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9329 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9331 case Q3TCMOD_TRANSFORM:
9332 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
9333 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
9334 VectorSet(tcmat + 6, 0 , 0 , 1);
9335 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
9336 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9338 case Q3TCMOD_TURBULENT:
9339 // this is handled in the RSurf_PrepareVertices function
9340 matrix = identitymatrix;
9344 Matrix4x4_Concat(texmatrix, &matrix, &temp);
9347 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9349 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9350 char name[MAX_QPATH];
9351 skinframe_t *skinframe;
9352 unsigned char pixels[296*194];
9353 strlcpy(cache->name, skinname, sizeof(cache->name));
9354 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9355 if (developer_loading.integer)
9356 Con_Printf("loading %s\n", name);
9357 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9358 if (!skinframe || !skinframe->base)
9361 fs_offset_t filesize;
9363 f = FS_LoadFile(name, tempmempool, true, &filesize);
9366 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9367 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9371 cache->skinframe = skinframe;
9374 texture_t *R_GetCurrentTexture(texture_t *t)
9377 const entity_render_t *ent = rsurface.entity;
9378 dp_model_t *model = ent->model;
9379 q3shaderinfo_layer_tcmod_t *tcmod;
9381 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9382 return t->currentframe;
9383 t->update_lastrenderframe = r_textureframe;
9384 t->update_lastrenderentity = (void *)ent;
9386 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9387 t->camera_entity = ent->entitynumber;
9389 t->camera_entity = 0;
9391 // switch to an alternate material if this is a q1bsp animated material
9393 texture_t *texture = t;
9394 int s = rsurface.ent_skinnum;
9395 if ((unsigned int)s >= (unsigned int)model->numskins)
9397 if (model->skinscenes)
9399 if (model->skinscenes[s].framecount > 1)
9400 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9402 s = model->skinscenes[s].firstframe;
9405 t = t + s * model->num_surfaces;
9408 // use an alternate animation if the entity's frame is not 0,
9409 // and only if the texture has an alternate animation
9410 if (rsurface.ent_alttextures && t->anim_total[1])
9411 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9413 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9415 texture->currentframe = t;
9418 // update currentskinframe to be a qw skin or animation frame
9419 if (rsurface.ent_qwskin >= 0)
9421 i = rsurface.ent_qwskin;
9422 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9424 r_qwskincache_size = cl.maxclients;
9426 Mem_Free(r_qwskincache);
9427 r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9429 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9430 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9431 t->currentskinframe = r_qwskincache[i].skinframe;
9432 if (t->currentskinframe == NULL)
9433 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9435 else if (t->numskinframes >= 2)
9436 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9437 if (t->backgroundnumskinframes >= 2)
9438 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9440 t->currentmaterialflags = t->basematerialflags;
9441 t->currentalpha = rsurface.colormod[3];
9442 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9443 t->currentalpha *= r_wateralpha.value;
9444 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9445 t->currentalpha *= t->r_water_wateralpha;
9446 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9447 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9448 if (!(rsurface.ent_flags & RENDER_LIGHT))
9449 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9450 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9452 // pick a model lighting mode
9453 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9454 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9456 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9458 if (rsurface.ent_flags & RENDER_ADDITIVE)
9459 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9460 else if (t->currentalpha < 1)
9461 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9462 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9463 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9464 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9465 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9466 if (t->backgroundnumskinframes)
9467 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9468 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9470 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9471 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9474 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9475 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9476 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9478 // there is no tcmod
9479 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9481 t->currenttexmatrix = r_waterscrollmatrix;
9482 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9484 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9486 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9487 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9490 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9491 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9492 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9493 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9495 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9496 if (t->currentskinframe->qpixels)
9497 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9498 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9499 if (!t->basetexture)
9500 t->basetexture = r_texture_notexture;
9501 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9502 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9503 t->nmaptexture = t->currentskinframe->nmap;
9504 if (!t->nmaptexture)
9505 t->nmaptexture = r_texture_blanknormalmap;
9506 t->glosstexture = r_texture_black;
9507 t->glowtexture = t->currentskinframe->glow;
9508 t->fogtexture = t->currentskinframe->fog;
9509 t->reflectmasktexture = t->currentskinframe->reflect;
9510 if (t->backgroundnumskinframes)
9512 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9513 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9514 t->backgroundglosstexture = r_texture_black;
9515 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9516 if (!t->backgroundnmaptexture)
9517 t->backgroundnmaptexture = r_texture_blanknormalmap;
9521 t->backgroundbasetexture = r_texture_white;
9522 t->backgroundnmaptexture = r_texture_blanknormalmap;
9523 t->backgroundglosstexture = r_texture_black;
9524 t->backgroundglowtexture = NULL;
9526 t->specularpower = r_shadow_glossexponent.value;
9527 // TODO: store reference values for these in the texture?
9528 t->specularscale = 0;
9529 if (r_shadow_gloss.integer > 0)
9531 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9533 if (r_shadow_glossintensity.value > 0)
9535 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9536 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9537 t->specularscale = r_shadow_glossintensity.value;
9540 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9542 t->glosstexture = r_texture_white;
9543 t->backgroundglosstexture = r_texture_white;
9544 t->specularscale = r_shadow_gloss2intensity.value;
9545 t->specularpower = r_shadow_gloss2exponent.value;
9548 t->specularscale *= t->specularscalemod;
9549 t->specularpower *= t->specularpowermod;
9551 // lightmaps mode looks bad with dlights using actual texturing, so turn
9552 // off the colormap and glossmap, but leave the normalmap on as it still
9553 // accurately represents the shading involved
9554 if (gl_lightmaps.integer)
9556 t->basetexture = r_texture_grey128;
9557 t->pantstexture = r_texture_black;
9558 t->shirttexture = r_texture_black;
9559 t->nmaptexture = r_texture_blanknormalmap;
9560 t->glosstexture = r_texture_black;
9561 t->glowtexture = NULL;
9562 t->fogtexture = NULL;
9563 t->reflectmasktexture = NULL;
9564 t->backgroundbasetexture = NULL;
9565 t->backgroundnmaptexture = r_texture_blanknormalmap;
9566 t->backgroundglosstexture = r_texture_black;
9567 t->backgroundglowtexture = NULL;
9568 t->specularscale = 0;
9569 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9572 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9573 VectorClear(t->dlightcolor);
9574 t->currentnumlayers = 0;
9575 if (t->currentmaterialflags & MATERIALFLAG_WALL)
9577 int blendfunc1, blendfunc2;
9579 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9581 blendfunc1 = GL_SRC_ALPHA;
9582 blendfunc2 = GL_ONE;
9584 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9586 blendfunc1 = GL_SRC_ALPHA;
9587 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9589 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9591 blendfunc1 = t->customblendfunc[0];
9592 blendfunc2 = t->customblendfunc[1];
9596 blendfunc1 = GL_ONE;
9597 blendfunc2 = GL_ZERO;
9599 // don't colormod evilblend textures
9600 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
9601 VectorSet(t->lightmapcolor, 1, 1, 1);
9602 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9603 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9605 // fullbright is not affected by r_refdef.lightmapintensity
9606 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]);
9607 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9608 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]);
9609 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9610 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]);
9614 vec3_t ambientcolor;
9616 // set the color tint used for lights affecting this surface
9617 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9619 // q3bsp has no lightmap updates, so the lightstylevalue that
9620 // would normally be baked into the lightmap must be
9621 // applied to the color
9622 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9623 if (model->type == mod_brushq3)
9624 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9625 colorscale *= r_refdef.lightmapintensity;
9626 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9627 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9628 // basic lit geometry
9629 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]);
9630 // add pants/shirt if needed
9631 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9632 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]);
9633 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9634 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]);
9635 // now add ambient passes if needed
9636 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9638 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]);
9639 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9640 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]);
9641 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9642 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]);
9645 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9646 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]);
9647 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9649 // if this is opaque use alpha blend which will darken the earlier
9652 // if this is an alpha blended material, all the earlier passes
9653 // were darkened by fog already, so we only need to add the fog
9654 // color ontop through the fog mask texture
9656 // if this is an additive blended material, all the earlier passes
9657 // were darkened by fog already, and we should not add fog color
9658 // (because the background was not darkened, there is no fog color
9659 // that was lost behind it).
9660 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]);
9664 return t->currentframe;
9667 rsurfacestate_t rsurface;
9669 void R_Mesh_ResizeArrays(int newvertices)
9671 unsigned char *base;
9673 if (rsurface.array_size >= newvertices)
9675 if (rsurface.array_base)
9676 Mem_Free(rsurface.array_base);
9677 rsurface.array_size = (newvertices + 1023) & ~1023;
9679 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9680 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9681 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9682 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9683 size += rsurface.array_size * sizeof(float[3]);
9684 size += rsurface.array_size * sizeof(float[3]);
9685 size += rsurface.array_size * sizeof(float[3]);
9686 size += rsurface.array_size * sizeof(float[3]);
9687 size += rsurface.array_size * sizeof(float[3]);
9688 size += rsurface.array_size * sizeof(float[3]);
9689 size += rsurface.array_size * sizeof(float[3]);
9690 size += rsurface.array_size * sizeof(float[3]);
9691 size += rsurface.array_size * sizeof(float[4]);
9692 size += rsurface.array_size * sizeof(float[2]);
9693 size += rsurface.array_size * sizeof(float[2]);
9694 size += rsurface.array_size * sizeof(float[4]);
9695 size += rsurface.array_size * sizeof(int[3]);
9696 size += rsurface.array_size * sizeof(unsigned short[3]);
9697 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
9698 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9699 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9700 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9701 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9702 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9703 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9704 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9705 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9706 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9707 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9708 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9709 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9710 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9711 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9712 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9713 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9714 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
9715 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
9718 void RSurf_ActiveWorldEntity(void)
9720 dp_model_t *model = r_refdef.scene.worldmodel;
9721 //if (rsurface.entity == r_refdef.scene.worldentity)
9723 rsurface.entity = r_refdef.scene.worldentity;
9724 rsurface.skeleton = NULL;
9725 memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
9726 rsurface.ent_skinnum = 0;
9727 rsurface.ent_qwskin = -1;
9728 rsurface.ent_shadertime = 0;
9729 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9730 if (rsurface.array_size < model->surfmesh.num_vertices)
9731 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9732 rsurface.matrix = identitymatrix;
9733 rsurface.inversematrix = identitymatrix;
9734 rsurface.matrixscale = 1;
9735 rsurface.inversematrixscale = 1;
9736 R_EntityMatrix(&identitymatrix);
9737 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9738 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9739 rsurface.fograngerecip = r_refdef.fograngerecip;
9740 rsurface.fogheightfade = r_refdef.fogheightfade;
9741 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9742 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9743 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9744 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9745 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9746 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9747 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9748 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9749 rsurface.colormod[3] = 1;
9750 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);
9751 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9752 rsurface.frameblend[0].lerp = 1;
9753 rsurface.ent_alttextures = false;
9754 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9755 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9756 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9757 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9758 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9759 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9760 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9761 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9762 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9763 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9764 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9765 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9766 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9767 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9768 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9769 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9770 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9771 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9772 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9773 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9774 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9775 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9776 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9777 rsurface.modelelement3i = model->surfmesh.data_element3i;
9778 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9779 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9780 rsurface.modelelement3s = model->surfmesh.data_element3s;
9781 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9782 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9783 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9784 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9785 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9786 rsurface.modelsurfaces = model->data_surfaces;
9787 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9788 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9789 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9790 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9791 rsurface.modelgeneratedvertex = false;
9792 rsurface.batchgeneratedvertex = false;
9793 rsurface.batchfirstvertex = 0;
9794 rsurface.batchnumvertices = 0;
9795 rsurface.batchfirsttriangle = 0;
9796 rsurface.batchnumtriangles = 0;
9797 rsurface.batchvertex3f = NULL;
9798 rsurface.batchvertex3f_vertexbuffer = NULL;
9799 rsurface.batchvertex3f_bufferoffset = 0;
9800 rsurface.batchsvector3f = NULL;
9801 rsurface.batchsvector3f_vertexbuffer = NULL;
9802 rsurface.batchsvector3f_bufferoffset = 0;
9803 rsurface.batchtvector3f = NULL;
9804 rsurface.batchtvector3f_vertexbuffer = NULL;
9805 rsurface.batchtvector3f_bufferoffset = 0;
9806 rsurface.batchnormal3f = NULL;
9807 rsurface.batchnormal3f_vertexbuffer = NULL;
9808 rsurface.batchnormal3f_bufferoffset = 0;
9809 rsurface.batchlightmapcolor4f = NULL;
9810 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9811 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9812 rsurface.batchtexcoordtexture2f = NULL;
9813 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9814 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9815 rsurface.batchtexcoordlightmap2f = NULL;
9816 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9817 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9818 rsurface.batchvertexmesh = NULL;
9819 rsurface.batchvertexmeshbuffer = NULL;
9820 rsurface.batchvertexposition = NULL;
9821 rsurface.batchvertexpositionbuffer = NULL;
9822 rsurface.batchelement3i = NULL;
9823 rsurface.batchelement3i_indexbuffer = NULL;
9824 rsurface.batchelement3i_bufferoffset = 0;
9825 rsurface.batchelement3s = NULL;
9826 rsurface.batchelement3s_indexbuffer = NULL;
9827 rsurface.batchelement3s_bufferoffset = 0;
9828 rsurface.passcolor4f = NULL;
9829 rsurface.passcolor4f_vertexbuffer = NULL;
9830 rsurface.passcolor4f_bufferoffset = 0;
9833 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9835 dp_model_t *model = ent->model;
9836 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9838 rsurface.entity = (entity_render_t *)ent;
9839 rsurface.skeleton = ent->skeleton;
9840 memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
9841 rsurface.ent_skinnum = ent->skinnum;
9842 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;
9843 rsurface.ent_shadertime = ent->shadertime;
9844 rsurface.ent_flags = ent->flags;
9845 if (rsurface.array_size < model->surfmesh.num_vertices)
9846 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9847 rsurface.matrix = ent->matrix;
9848 rsurface.inversematrix = ent->inversematrix;
9849 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9850 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9851 R_EntityMatrix(&rsurface.matrix);
9852 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9853 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9854 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9855 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9856 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9857 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9858 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
9859 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
9860 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
9861 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
9862 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
9863 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
9864 rsurface.colormod[3] = ent->alpha;
9865 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
9866 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
9867 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
9868 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9869 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9870 if (ent->model->brush.submodel && !prepass)
9872 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
9873 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
9875 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
9877 if (ent->animcache_vertex3f && !r_framedata_failed)
9879 rsurface.modelvertex3f = ent->animcache_vertex3f;
9880 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
9881 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
9882 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
9883 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
9884 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
9885 rsurface.modelvertexposition = ent->animcache_vertexposition;
9886 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
9888 else if (wanttangents)
9890 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9891 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
9892 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
9893 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9894 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
9895 rsurface.modelvertexmesh = NULL;
9896 rsurface.modelvertexmeshbuffer = NULL;
9897 rsurface.modelvertexposition = NULL;
9898 rsurface.modelvertexpositionbuffer = NULL;
9900 else if (wantnormals)
9902 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9903 rsurface.modelsvector3f = NULL;
9904 rsurface.modeltvector3f = NULL;
9905 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9906 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
9907 rsurface.modelvertexmesh = NULL;
9908 rsurface.modelvertexmeshbuffer = NULL;
9909 rsurface.modelvertexposition = NULL;
9910 rsurface.modelvertexpositionbuffer = NULL;
9914 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9915 rsurface.modelsvector3f = NULL;
9916 rsurface.modeltvector3f = NULL;
9917 rsurface.modelnormal3f = NULL;
9918 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
9919 rsurface.modelvertexmesh = NULL;
9920 rsurface.modelvertexmeshbuffer = NULL;
9921 rsurface.modelvertexposition = NULL;
9922 rsurface.modelvertexpositionbuffer = NULL;
9924 rsurface.modelvertex3f_vertexbuffer = 0;
9925 rsurface.modelvertex3f_bufferoffset = 0;
9926 rsurface.modelsvector3f_vertexbuffer = 0;
9927 rsurface.modelsvector3f_bufferoffset = 0;
9928 rsurface.modeltvector3f_vertexbuffer = 0;
9929 rsurface.modeltvector3f_bufferoffset = 0;
9930 rsurface.modelnormal3f_vertexbuffer = 0;
9931 rsurface.modelnormal3f_bufferoffset = 0;
9932 rsurface.modelgeneratedvertex = true;
9936 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9937 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9938 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9939 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9940 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9941 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9942 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9943 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9944 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9945 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9946 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9947 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9948 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9949 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9950 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9951 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9952 rsurface.modelgeneratedvertex = false;
9954 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9955 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9956 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9957 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9958 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9959 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9960 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9961 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9962 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9963 rsurface.modelelement3i = model->surfmesh.data_element3i;
9964 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9965 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9966 rsurface.modelelement3s = model->surfmesh.data_element3s;
9967 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9968 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9969 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9970 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9971 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9972 rsurface.modelsurfaces = model->data_surfaces;
9973 rsurface.batchgeneratedvertex = false;
9974 rsurface.batchfirstvertex = 0;
9975 rsurface.batchnumvertices = 0;
9976 rsurface.batchfirsttriangle = 0;
9977 rsurface.batchnumtriangles = 0;
9978 rsurface.batchvertex3f = NULL;
9979 rsurface.batchvertex3f_vertexbuffer = NULL;
9980 rsurface.batchvertex3f_bufferoffset = 0;
9981 rsurface.batchsvector3f = NULL;
9982 rsurface.batchsvector3f_vertexbuffer = NULL;
9983 rsurface.batchsvector3f_bufferoffset = 0;
9984 rsurface.batchtvector3f = NULL;
9985 rsurface.batchtvector3f_vertexbuffer = NULL;
9986 rsurface.batchtvector3f_bufferoffset = 0;
9987 rsurface.batchnormal3f = NULL;
9988 rsurface.batchnormal3f_vertexbuffer = NULL;
9989 rsurface.batchnormal3f_bufferoffset = 0;
9990 rsurface.batchlightmapcolor4f = NULL;
9991 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9992 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9993 rsurface.batchtexcoordtexture2f = NULL;
9994 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9995 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9996 rsurface.batchtexcoordlightmap2f = NULL;
9997 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9998 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9999 rsurface.batchvertexmesh = NULL;
10000 rsurface.batchvertexmeshbuffer = NULL;
10001 rsurface.batchvertexposition = NULL;
10002 rsurface.batchvertexpositionbuffer = NULL;
10003 rsurface.batchelement3i = NULL;
10004 rsurface.batchelement3i_indexbuffer = NULL;
10005 rsurface.batchelement3i_bufferoffset = 0;
10006 rsurface.batchelement3s = NULL;
10007 rsurface.batchelement3s_indexbuffer = NULL;
10008 rsurface.batchelement3s_bufferoffset = 0;
10009 rsurface.passcolor4f = NULL;
10010 rsurface.passcolor4f_vertexbuffer = NULL;
10011 rsurface.passcolor4f_bufferoffset = 0;
10014 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)
10018 rsurface.entity = r_refdef.scene.worldentity;
10019 rsurface.skeleton = NULL;
10020 rsurface.ent_skinnum = 0;
10021 rsurface.ent_qwskin = -1;
10022 rsurface.ent_shadertime = shadertime;
10023 rsurface.ent_flags = entflags;
10024 rsurface.modelnumvertices = numvertices;
10025 rsurface.modelnumtriangles = numtriangles;
10026 if (rsurface.array_size < rsurface.modelnumvertices)
10027 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
10028 rsurface.matrix = *matrix;
10029 rsurface.inversematrix = *inversematrix;
10030 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10031 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10032 R_EntityMatrix(&rsurface.matrix);
10033 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10034 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10035 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10036 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10037 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10038 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10039 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10040 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10041 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10042 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10043 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10044 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10045 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);
10046 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10047 rsurface.frameblend[0].lerp = 1;
10048 rsurface.ent_alttextures = false;
10049 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10050 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10053 rsurface.modelvertex3f = vertex3f;
10054 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10055 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10056 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10058 else if (wantnormals)
10060 rsurface.modelvertex3f = vertex3f;
10061 rsurface.modelsvector3f = NULL;
10062 rsurface.modeltvector3f = NULL;
10063 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10067 rsurface.modelvertex3f = vertex3f;
10068 rsurface.modelsvector3f = NULL;
10069 rsurface.modeltvector3f = NULL;
10070 rsurface.modelnormal3f = NULL;
10072 rsurface.modelvertexmesh = NULL;
10073 rsurface.modelvertexmeshbuffer = NULL;
10074 rsurface.modelvertexposition = NULL;
10075 rsurface.modelvertexpositionbuffer = NULL;
10076 rsurface.modelvertex3f_vertexbuffer = 0;
10077 rsurface.modelvertex3f_bufferoffset = 0;
10078 rsurface.modelsvector3f_vertexbuffer = 0;
10079 rsurface.modelsvector3f_bufferoffset = 0;
10080 rsurface.modeltvector3f_vertexbuffer = 0;
10081 rsurface.modeltvector3f_bufferoffset = 0;
10082 rsurface.modelnormal3f_vertexbuffer = 0;
10083 rsurface.modelnormal3f_bufferoffset = 0;
10084 rsurface.modelgeneratedvertex = true;
10085 rsurface.modellightmapcolor4f = color4f;
10086 rsurface.modellightmapcolor4f_vertexbuffer = 0;
10087 rsurface.modellightmapcolor4f_bufferoffset = 0;
10088 rsurface.modeltexcoordtexture2f = texcoord2f;
10089 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10090 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10091 rsurface.modeltexcoordlightmap2f = NULL;
10092 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10093 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10094 rsurface.modelelement3i = element3i;
10095 rsurface.modelelement3i_indexbuffer = NULL;
10096 rsurface.modelelement3i_bufferoffset = 0;
10097 rsurface.modelelement3s = element3s;
10098 rsurface.modelelement3s_indexbuffer = NULL;
10099 rsurface.modelelement3s_bufferoffset = 0;
10100 rsurface.modellightmapoffsets = NULL;
10101 rsurface.modelsurfaces = NULL;
10102 rsurface.batchgeneratedvertex = false;
10103 rsurface.batchfirstvertex = 0;
10104 rsurface.batchnumvertices = 0;
10105 rsurface.batchfirsttriangle = 0;
10106 rsurface.batchnumtriangles = 0;
10107 rsurface.batchvertex3f = NULL;
10108 rsurface.batchvertex3f_vertexbuffer = NULL;
10109 rsurface.batchvertex3f_bufferoffset = 0;
10110 rsurface.batchsvector3f = NULL;
10111 rsurface.batchsvector3f_vertexbuffer = NULL;
10112 rsurface.batchsvector3f_bufferoffset = 0;
10113 rsurface.batchtvector3f = NULL;
10114 rsurface.batchtvector3f_vertexbuffer = NULL;
10115 rsurface.batchtvector3f_bufferoffset = 0;
10116 rsurface.batchnormal3f = NULL;
10117 rsurface.batchnormal3f_vertexbuffer = NULL;
10118 rsurface.batchnormal3f_bufferoffset = 0;
10119 rsurface.batchlightmapcolor4f = NULL;
10120 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10121 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10122 rsurface.batchtexcoordtexture2f = NULL;
10123 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10124 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10125 rsurface.batchtexcoordlightmap2f = NULL;
10126 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10127 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10128 rsurface.batchvertexmesh = NULL;
10129 rsurface.batchvertexmeshbuffer = NULL;
10130 rsurface.batchvertexposition = NULL;
10131 rsurface.batchvertexpositionbuffer = NULL;
10132 rsurface.batchelement3i = NULL;
10133 rsurface.batchelement3i_indexbuffer = NULL;
10134 rsurface.batchelement3i_bufferoffset = 0;
10135 rsurface.batchelement3s = NULL;
10136 rsurface.batchelement3s_indexbuffer = NULL;
10137 rsurface.batchelement3s_bufferoffset = 0;
10138 rsurface.passcolor4f = NULL;
10139 rsurface.passcolor4f_vertexbuffer = NULL;
10140 rsurface.passcolor4f_bufferoffset = 0;
10142 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10144 if ((wantnormals || wanttangents) && !normal3f)
10146 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10147 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10149 if (wanttangents && !svector3f)
10151 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);
10152 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10153 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10157 // now convert arrays into vertexmesh structs
10158 for (i = 0;i < numvertices;i++)
10160 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
10161 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
10162 if (rsurface.modelsvector3f)
10163 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
10164 if (rsurface.modeltvector3f)
10165 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
10166 if (rsurface.modelnormal3f)
10167 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
10168 if (rsurface.modellightmapcolor4f)
10169 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
10170 if (rsurface.modeltexcoordtexture2f)
10171 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
10172 if (rsurface.modeltexcoordlightmap2f)
10173 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
10177 float RSurf_FogPoint(const float *v)
10179 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10180 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10181 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10182 float FogHeightFade = r_refdef.fogheightfade;
10184 unsigned int fogmasktableindex;
10185 if (r_refdef.fogplaneviewabove)
10186 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10188 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10189 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10190 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10193 float RSurf_FogVertex(const float *v)
10195 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10196 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10197 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10198 float FogHeightFade = rsurface.fogheightfade;
10200 unsigned int fogmasktableindex;
10201 if (r_refdef.fogplaneviewabove)
10202 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10204 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10205 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10206 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10209 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10212 for (i = 0;i < numelements;i++)
10213 outelement3i[i] = inelement3i[i] + adjust;
10216 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10217 extern cvar_t gl_vbo;
10218 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10226 int surfacefirsttriangle;
10227 int surfacenumtriangles;
10228 int surfacefirstvertex;
10229 int surfaceendvertex;
10230 int surfacenumvertices;
10231 int surfaceadjustvertex;
10235 qboolean dynamicvertex;
10239 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10240 float waveparms[4];
10241 q3shaderinfo_deform_t *deform;
10242 const msurface_t *surface, *firstsurface;
10243 r_vertexposition_t *vertexposition;
10244 r_vertexmesh_t *vertexmesh;
10245 if (!texturenumsurfaces)
10247 // find vertex range of this surface batch
10249 firstsurface = texturesurfacelist[0];
10250 firsttriangle = firstsurface->num_firsttriangle;
10252 firstvertex = endvertex = firstsurface->num_firstvertex;
10253 for (i = 0;i < texturenumsurfaces;i++)
10255 surface = texturesurfacelist[i];
10256 if (surface != firstsurface + i)
10258 surfacefirstvertex = surface->num_firstvertex;
10259 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10260 surfacenumtriangles = surface->num_triangles;
10261 if (firstvertex > surfacefirstvertex)
10262 firstvertex = surfacefirstvertex;
10263 if (endvertex < surfaceendvertex)
10264 endvertex = surfaceendvertex;
10265 numtriangles += surfacenumtriangles;
10270 // we now know the vertex range used, and if there are any gaps in it
10271 rsurface.batchfirstvertex = firstvertex;
10272 rsurface.batchnumvertices = endvertex - firstvertex;
10273 rsurface.batchfirsttriangle = firsttriangle;
10274 rsurface.batchnumtriangles = numtriangles;
10276 // this variable holds flags for which properties have been updated that
10277 // may require regenerating vertexmesh or vertexposition arrays...
10280 // check if any dynamic vertex processing must occur
10281 dynamicvertex = false;
10283 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10284 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
10285 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10287 switch (deform->deform)
10290 case Q3DEFORM_PROJECTIONSHADOW:
10291 case Q3DEFORM_TEXT0:
10292 case Q3DEFORM_TEXT1:
10293 case Q3DEFORM_TEXT2:
10294 case Q3DEFORM_TEXT3:
10295 case Q3DEFORM_TEXT4:
10296 case Q3DEFORM_TEXT5:
10297 case Q3DEFORM_TEXT6:
10298 case Q3DEFORM_TEXT7:
10299 case Q3DEFORM_NONE:
10301 case Q3DEFORM_AUTOSPRITE:
10302 dynamicvertex = true;
10303 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10304 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10306 case Q3DEFORM_AUTOSPRITE2:
10307 dynamicvertex = true;
10308 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10309 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10311 case Q3DEFORM_NORMAL:
10312 dynamicvertex = true;
10313 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10314 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10316 case Q3DEFORM_WAVE:
10317 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10318 break; // if wavefunc is a nop, ignore this transform
10319 dynamicvertex = true;
10320 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10321 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10323 case Q3DEFORM_BULGE:
10324 dynamicvertex = true;
10325 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10326 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10328 case Q3DEFORM_MOVE:
10329 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10330 break; // if wavefunc is a nop, ignore this transform
10331 dynamicvertex = true;
10332 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10333 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
10337 switch(rsurface.texture->tcgen.tcgen)
10340 case Q3TCGEN_TEXTURE:
10342 case Q3TCGEN_LIGHTMAP:
10343 dynamicvertex = true;
10344 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
10345 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
10347 case Q3TCGEN_VECTOR:
10348 dynamicvertex = true;
10349 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10350 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10352 case Q3TCGEN_ENVIRONMENT:
10353 dynamicvertex = true;
10354 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
10355 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10358 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10360 dynamicvertex = true;
10361 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10362 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10365 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10367 dynamicvertex = true;
10368 batchneed |= BATCHNEED_NOGAPS;
10369 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
10372 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10374 dynamicvertex = true;
10375 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10376 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
10379 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
10381 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
10382 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
10383 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
10384 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
10385 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
10386 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
10387 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
10390 // when the model data has no vertex buffer (dynamic mesh), we need to
10392 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
10393 batchneed |= BATCHNEED_NOGAPS;
10395 // if needsupdate, we have to do a dynamic vertex batch for sure
10396 if (needsupdate & batchneed)
10397 dynamicvertex = true;
10399 // see if we need to build vertexmesh from arrays
10400 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10401 dynamicvertex = true;
10403 // see if we need to build vertexposition from arrays
10404 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
10405 dynamicvertex = true;
10407 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
10408 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
10409 dynamicvertex = true;
10411 // if there is a chance of animated vertex colors, it's a dynamic batch
10412 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10413 dynamicvertex = true;
10415 rsurface.batchvertex3f = rsurface.modelvertex3f;
10416 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
10417 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10418 rsurface.batchsvector3f = rsurface.modelsvector3f;
10419 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
10420 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10421 rsurface.batchtvector3f = rsurface.modeltvector3f;
10422 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
10423 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10424 rsurface.batchnormal3f = rsurface.modelnormal3f;
10425 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
10426 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10427 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
10428 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
10429 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
10430 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
10431 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
10432 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
10433 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
10434 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
10435 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10436 rsurface.batchvertexposition = rsurface.modelvertexposition;
10437 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
10438 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
10439 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
10440 rsurface.batchelement3i = rsurface.modelelement3i;
10441 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
10442 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
10443 rsurface.batchelement3s = rsurface.modelelement3s;
10444 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
10445 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
10447 // if any dynamic vertex processing has to occur in software, we copy the
10448 // entire surface list together before processing to rebase the vertices
10449 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
10451 // if any gaps exist and we do not have a static vertex buffer, we have to
10452 // copy the surface list together to avoid wasting upload bandwidth on the
10453 // vertices in the gaps.
10455 // if gaps exist and we have a static vertex buffer, we still have to
10456 // combine the index buffer ranges into one dynamic index buffer.
10458 // in all cases we end up with data that can be drawn in one call.
10460 if (!dynamicvertex)
10462 // static vertex data, just set pointers...
10463 rsurface.batchgeneratedvertex = false;
10464 // if there are gaps, we want to build a combined index buffer,
10465 // otherwise use the original static buffer with an appropriate offset
10470 for (i = 0;i < texturenumsurfaces;i++)
10472 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10473 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10474 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
10475 numtriangles += surfacenumtriangles;
10477 rsurface.batchelement3i = rsurface.array_batchelement3i;
10478 rsurface.batchelement3i_indexbuffer = NULL;
10479 rsurface.batchelement3i_bufferoffset = 0;
10480 rsurface.batchelement3s = NULL;
10481 rsurface.batchelement3s_indexbuffer = NULL;
10482 rsurface.batchelement3s_bufferoffset = 0;
10483 if (endvertex <= 65536)
10485 rsurface.batchelement3s = rsurface.array_batchelement3s;
10486 for (i = 0;i < numtriangles*3;i++)
10487 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10489 rsurface.batchfirsttriangle = firsttriangle;
10490 rsurface.batchnumtriangles = numtriangles;
10495 // something needs software processing, do it for real...
10496 // we only directly handle interleaved array data in this case...
10497 rsurface.batchgeneratedvertex = true;
10499 // now copy the vertex data into a combined array and make an index array
10500 // (this is what Quake3 does all the time)
10501 //if (gaps || rsurface.batchfirstvertex)
10503 rsurface.batchvertexposition = NULL;
10504 rsurface.batchvertexpositionbuffer = NULL;
10505 rsurface.batchvertexmesh = NULL;
10506 rsurface.batchvertexmeshbuffer = NULL;
10507 rsurface.batchvertex3f = NULL;
10508 rsurface.batchvertex3f_vertexbuffer = NULL;
10509 rsurface.batchvertex3f_bufferoffset = 0;
10510 rsurface.batchsvector3f = NULL;
10511 rsurface.batchsvector3f_vertexbuffer = NULL;
10512 rsurface.batchsvector3f_bufferoffset = 0;
10513 rsurface.batchtvector3f = NULL;
10514 rsurface.batchtvector3f_vertexbuffer = NULL;
10515 rsurface.batchtvector3f_bufferoffset = 0;
10516 rsurface.batchnormal3f = NULL;
10517 rsurface.batchnormal3f_vertexbuffer = NULL;
10518 rsurface.batchnormal3f_bufferoffset = 0;
10519 rsurface.batchlightmapcolor4f = NULL;
10520 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10521 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10522 rsurface.batchtexcoordtexture2f = NULL;
10523 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10524 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10525 rsurface.batchtexcoordlightmap2f = NULL;
10526 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10527 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10528 rsurface.batchelement3i = rsurface.array_batchelement3i;
10529 rsurface.batchelement3i_indexbuffer = NULL;
10530 rsurface.batchelement3i_bufferoffset = 0;
10531 rsurface.batchelement3s = NULL;
10532 rsurface.batchelement3s_indexbuffer = NULL;
10533 rsurface.batchelement3s_bufferoffset = 0;
10534 // we'll only be setting up certain arrays as needed
10535 if (batchneed & BATCHNEED_VERTEXPOSITION)
10536 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10537 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10538 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10539 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10540 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10541 if (batchneed & BATCHNEED_ARRAY_NORMAL)
10542 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10543 if (batchneed & BATCHNEED_ARRAY_VECTOR)
10545 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10546 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10548 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
10549 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10550 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
10551 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10552 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
10553 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
10556 for (i = 0;i < texturenumsurfaces;i++)
10558 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
10559 surfacenumvertices = texturesurfacelist[i]->num_vertices;
10560 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10561 surfaceadjustvertex = numvertices - surfacefirstvertex;
10562 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10563 // copy only the data requested
10564 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
10565 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
10566 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
10567 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
10568 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
10570 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10571 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10572 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
10573 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10574 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
10576 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10577 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10579 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
10580 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
10581 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
10582 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10583 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
10584 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10586 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
10587 numvertices += surfacenumvertices;
10588 numtriangles += surfacenumtriangles;
10591 // generate a 16bit index array as well if possible
10592 // (in general, dynamic batches fit)
10593 if (numvertices <= 65536)
10595 rsurface.batchelement3s = rsurface.array_batchelement3s;
10596 for (i = 0;i < numtriangles*3;i++)
10597 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10600 // since we've copied everything, the batch now starts at 0
10601 rsurface.batchfirstvertex = 0;
10602 rsurface.batchnumvertices = numvertices;
10603 rsurface.batchfirsttriangle = 0;
10604 rsurface.batchnumtriangles = numtriangles;
10607 // q1bsp surfaces rendered in vertex color mode have to have colors
10608 // calculated based on lightstyles
10609 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10611 // generate color arrays for the surfaces in this list
10615 const int *offsets;
10616 const unsigned char *lm;
10618 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10619 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10620 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10621 for (i = 0;i < texturenumsurfaces;i++)
10623 surface = texturesurfacelist[i];
10624 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
10625 surfacenumvertices = surface->num_vertices;
10626 if (surface->lightmapinfo->samples)
10628 for (j = 0;j < surfacenumvertices;j++)
10630 lm = surface->lightmapinfo->samples + offsets[j];
10631 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
10632 VectorScale(lm, scale, c);
10633 if (surface->lightmapinfo->styles[1] != 255)
10635 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
10637 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
10638 VectorMA(c, scale, lm, c);
10639 if (surface->lightmapinfo->styles[2] != 255)
10642 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
10643 VectorMA(c, scale, lm, c);
10644 if (surface->lightmapinfo->styles[3] != 255)
10647 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
10648 VectorMA(c, scale, lm, c);
10655 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);
10661 for (j = 0;j < surfacenumvertices;j++)
10663 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
10670 // if vertices are deformed (sprite flares and things in maps, possibly
10671 // water waves, bulges and other deformations), modify the copied vertices
10673 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10675 switch (deform->deform)
10678 case Q3DEFORM_PROJECTIONSHADOW:
10679 case Q3DEFORM_TEXT0:
10680 case Q3DEFORM_TEXT1:
10681 case Q3DEFORM_TEXT2:
10682 case Q3DEFORM_TEXT3:
10683 case Q3DEFORM_TEXT4:
10684 case Q3DEFORM_TEXT5:
10685 case Q3DEFORM_TEXT6:
10686 case Q3DEFORM_TEXT7:
10687 case Q3DEFORM_NONE:
10689 case Q3DEFORM_AUTOSPRITE:
10690 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10691 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10692 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10693 VectorNormalize(newforward);
10694 VectorNormalize(newright);
10695 VectorNormalize(newup);
10696 // a single autosprite surface can contain multiple sprites...
10697 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10699 VectorClear(center);
10700 for (i = 0;i < 4;i++)
10701 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10702 VectorScale(center, 0.25f, center);
10703 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
10704 VectorCopy(rsurface.batchsvector3f + 3*j, right);
10705 VectorCopy(rsurface.batchtvector3f + 3*j, up);
10706 for (i = 0;i < 4;i++)
10708 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
10709 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
10712 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10713 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);
10714 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10715 rsurface.batchvertex3f_vertexbuffer = NULL;
10716 rsurface.batchvertex3f_bufferoffset = 0;
10717 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10718 rsurface.batchsvector3f_vertexbuffer = NULL;
10719 rsurface.batchsvector3f_bufferoffset = 0;
10720 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10721 rsurface.batchtvector3f_vertexbuffer = NULL;
10722 rsurface.batchtvector3f_bufferoffset = 0;
10723 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10724 rsurface.batchnormal3f_vertexbuffer = NULL;
10725 rsurface.batchnormal3f_bufferoffset = 0;
10727 case Q3DEFORM_AUTOSPRITE2:
10728 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10729 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10730 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10731 VectorNormalize(newforward);
10732 VectorNormalize(newright);
10733 VectorNormalize(newup);
10735 const float *v1, *v2;
10745 memset(shortest, 0, sizeof(shortest));
10746 // a single autosprite surface can contain multiple sprites...
10747 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10749 VectorClear(center);
10750 for (i = 0;i < 4;i++)
10751 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10752 VectorScale(center, 0.25f, center);
10753 // find the two shortest edges, then use them to define the
10754 // axis vectors for rotating around the central axis
10755 for (i = 0;i < 6;i++)
10757 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
10758 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
10759 l = VectorDistance2(v1, v2);
10760 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10761 if (v1[2] != v2[2])
10762 l += (1.0f / 1024.0f);
10763 if (shortest[0].length2 > l || i == 0)
10765 shortest[1] = shortest[0];
10766 shortest[0].length2 = l;
10767 shortest[0].v1 = v1;
10768 shortest[0].v2 = v2;
10770 else if (shortest[1].length2 > l || i == 1)
10772 shortest[1].length2 = l;
10773 shortest[1].v1 = v1;
10774 shortest[1].v2 = v2;
10777 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10778 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10779 // this calculates the right vector from the shortest edge
10780 // and the up vector from the edge midpoints
10781 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10782 VectorNormalize(right);
10783 VectorSubtract(end, start, up);
10784 VectorNormalize(up);
10785 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10786 VectorSubtract(rsurface.localvieworigin, center, forward);
10787 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10788 VectorNegate(forward, forward);
10789 VectorReflect(forward, 0, up, forward);
10790 VectorNormalize(forward);
10791 CrossProduct(up, forward, newright);
10792 VectorNormalize(newright);
10793 // rotate the quad around the up axis vector, this is made
10794 // especially easy by the fact we know the quad is flat,
10795 // so we only have to subtract the center position and
10796 // measure distance along the right vector, and then
10797 // multiply that by the newright vector and add back the
10799 // we also need to subtract the old position to undo the
10800 // displacement from the center, which we do with a
10801 // DotProduct, the subtraction/addition of center is also
10802 // optimized into DotProducts here
10803 l = DotProduct(right, center);
10804 for (i = 0;i < 4;i++)
10806 v1 = rsurface.batchvertex3f + 3*(j+i);
10807 f = DotProduct(right, v1) - l;
10808 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
10812 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10813 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);
10814 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10815 rsurface.batchvertex3f_vertexbuffer = NULL;
10816 rsurface.batchvertex3f_bufferoffset = 0;
10817 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10818 rsurface.batchsvector3f_vertexbuffer = NULL;
10819 rsurface.batchsvector3f_bufferoffset = 0;
10820 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10821 rsurface.batchtvector3f_vertexbuffer = NULL;
10822 rsurface.batchtvector3f_bufferoffset = 0;
10823 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10824 rsurface.batchnormal3f_vertexbuffer = NULL;
10825 rsurface.batchnormal3f_bufferoffset = 0;
10827 case Q3DEFORM_NORMAL:
10828 // deform the normals to make reflections wavey
10829 for (j = 0;j < rsurface.batchnumvertices;j++)
10832 float *normal = rsurface.array_batchnormal3f + 3*j;
10833 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
10834 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10835 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]);
10836 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]);
10837 VectorNormalize(normal);
10839 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);
10840 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10841 rsurface.batchsvector3f_vertexbuffer = NULL;
10842 rsurface.batchsvector3f_bufferoffset = 0;
10843 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10844 rsurface.batchtvector3f_vertexbuffer = NULL;
10845 rsurface.batchtvector3f_bufferoffset = 0;
10846 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10847 rsurface.batchnormal3f_vertexbuffer = NULL;
10848 rsurface.batchnormal3f_bufferoffset = 0;
10850 case Q3DEFORM_WAVE:
10851 // deform vertex array to make wavey water and flags and such
10852 waveparms[0] = deform->waveparms[0];
10853 waveparms[1] = deform->waveparms[1];
10854 waveparms[2] = deform->waveparms[2];
10855 waveparms[3] = deform->waveparms[3];
10856 if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
10857 break; // if wavefunc is a nop, don't make a dynamic vertex array
10858 // this is how a divisor of vertex influence on deformation
10859 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10860 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10861 for (j = 0;j < rsurface.batchnumvertices;j++)
10863 // if the wavefunc depends on time, evaluate it per-vertex
10866 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
10867 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10869 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10871 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10872 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);
10873 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10874 rsurface.batchvertex3f_vertexbuffer = NULL;
10875 rsurface.batchvertex3f_bufferoffset = 0;
10876 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10877 rsurface.batchsvector3f_vertexbuffer = NULL;
10878 rsurface.batchsvector3f_bufferoffset = 0;
10879 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10880 rsurface.batchtvector3f_vertexbuffer = NULL;
10881 rsurface.batchtvector3f_bufferoffset = 0;
10882 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10883 rsurface.batchnormal3f_vertexbuffer = NULL;
10884 rsurface.batchnormal3f_bufferoffset = 0;
10886 case Q3DEFORM_BULGE:
10887 // deform vertex array to make the surface have moving bulges
10888 for (j = 0;j < rsurface.batchnumvertices;j++)
10890 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
10891 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10893 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10894 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);
10895 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10896 rsurface.batchvertex3f_vertexbuffer = NULL;
10897 rsurface.batchvertex3f_bufferoffset = 0;
10898 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10899 rsurface.batchsvector3f_vertexbuffer = NULL;
10900 rsurface.batchsvector3f_bufferoffset = 0;
10901 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10902 rsurface.batchtvector3f_vertexbuffer = NULL;
10903 rsurface.batchtvector3f_bufferoffset = 0;
10904 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10905 rsurface.batchnormal3f_vertexbuffer = NULL;
10906 rsurface.batchnormal3f_bufferoffset = 0;
10908 case Q3DEFORM_MOVE:
10909 // deform vertex array
10910 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10911 break; // if wavefunc is a nop, don't make a dynamic vertex array
10912 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10913 VectorScale(deform->parms, scale, waveparms);
10914 for (j = 0;j < rsurface.batchnumvertices;j++)
10915 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
10916 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10917 rsurface.batchvertex3f_vertexbuffer = NULL;
10918 rsurface.batchvertex3f_bufferoffset = 0;
10923 // generate texcoords based on the chosen texcoord source
10924 switch(rsurface.texture->tcgen.tcgen)
10927 case Q3TCGEN_TEXTURE:
10929 case Q3TCGEN_LIGHTMAP:
10930 if (rsurface.batchtexcoordlightmap2f)
10931 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
10932 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10933 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10934 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10936 case Q3TCGEN_VECTOR:
10937 for (j = 0;j < rsurface.batchnumvertices;j++)
10939 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
10940 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
10942 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10943 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10944 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10946 case Q3TCGEN_ENVIRONMENT:
10947 // make environment reflections using a spheremap
10948 for (j = 0;j < rsurface.batchnumvertices;j++)
10950 // identical to Q3A's method, but executed in worldspace so
10951 // carried models can be shiny too
10953 float viewer[3], d, reflected[3], worldreflected[3];
10955 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
10956 // VectorNormalize(viewer);
10958 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
10960 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
10961 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
10962 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
10963 // note: this is proportinal to viewer, so we can normalize later
10965 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10966 VectorNormalize(worldreflected);
10968 // note: this sphere map only uses world x and z!
10969 // so positive and negative y will LOOK THE SAME.
10970 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
10971 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
10973 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10974 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10975 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10978 // the only tcmod that needs software vertex processing is turbulent, so
10979 // check for it here and apply the changes if needed
10980 // and we only support that as the first one
10981 // (handling a mixture of turbulent and other tcmods would be problematic
10982 // without punting it entirely to a software path)
10983 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10985 amplitude = rsurface.texture->tcmods[0].parms[1];
10986 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10987 for (j = 0;j < rsurface.batchnumvertices;j++)
10989 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);
10990 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10992 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10993 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10994 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10997 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10999 // convert the modified arrays to vertex structs
11000 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11001 rsurface.batchvertexmeshbuffer = NULL;
11002 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11003 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11004 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11005 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
11006 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11007 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
11008 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
11010 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11012 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
11013 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11016 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11017 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11018 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11019 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11020 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11021 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11022 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11023 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11024 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11027 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11029 // convert the modified arrays to vertex structs
11030 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11031 rsurface.batchvertexpositionbuffer = NULL;
11032 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
11033 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
11035 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
11036 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
11040 void RSurf_DrawBatch(void)
11042 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);
11045 static void RSurf_BindLightmapForBatch(void)
11047 switch(vid.renderpath)
11049 case RENDERPATH_CGGL:
11051 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture );CHECKCGERROR
11052 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, rsurface.deluxemaptexture);CHECKCGERROR
11055 case RENDERPATH_GL20:
11056 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture );
11057 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, rsurface.deluxemaptexture);
11059 case RENDERPATH_GL13:
11060 case RENDERPATH_GL11:
11061 R_Mesh_TexBind(0, rsurface.lightmaptexture);
11066 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11068 // pick the closest matching water plane
11069 int planeindex, vertexindex, bestplaneindex = -1;
11073 r_waterstate_waterplane_t *p;
11075 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11077 if(p->camera_entity != rsurface.texture->camera_entity)
11080 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
11081 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11083 Matrix4x4_Transform(&rsurface.matrix, v, vert);
11084 d += fabs(PlaneDiff(vert, &p->plane));
11086 if (bestd > d || bestplaneindex < 0)
11089 bestplaneindex = planeindex;
11092 return bestplaneindex;
11095 static void RSurf_BindReflectionForBatch(int planeindex)
11097 // pick the closest matching water plane and bind textures
11098 r_waterstate_waterplane_t *bestp = planeindex >= 0 ? r_waterstate.waterplanes + planeindex : NULL;
11099 switch(vid.renderpath)
11101 case RENDERPATH_CGGL:
11103 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
11104 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
11105 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
11108 case RENDERPATH_GL20:
11109 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
11110 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
11111 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
11113 case RENDERPATH_GL13:
11114 case RENDERPATH_GL11:
11119 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11122 for (i = 0;i < rsurface.batchnumvertices;i++)
11123 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11124 rsurface.passcolor4f = rsurface.array_passcolor4f;
11125 rsurface.passcolor4f_vertexbuffer = 0;
11126 rsurface.passcolor4f_bufferoffset = 0;
11129 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11136 if (rsurface.passcolor4f)
11138 // generate color arrays
11139 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)
11141 f = RSurf_FogVertex(v);
11150 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11152 f = RSurf_FogVertex(v);
11159 rsurface.passcolor4f = rsurface.array_passcolor4f;
11160 rsurface.passcolor4f_vertexbuffer = 0;
11161 rsurface.passcolor4f_bufferoffset = 0;
11164 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11171 if (!rsurface.passcolor4f)
11173 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)
11175 f = RSurf_FogVertex(v);
11176 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11177 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11178 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11181 rsurface.passcolor4f = rsurface.array_passcolor4f;
11182 rsurface.passcolor4f_vertexbuffer = 0;
11183 rsurface.passcolor4f_bufferoffset = 0;
11186 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11191 if (!rsurface.passcolor4f)
11193 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11200 rsurface.passcolor4f = rsurface.array_passcolor4f;
11201 rsurface.passcolor4f_vertexbuffer = 0;
11202 rsurface.passcolor4f_bufferoffset = 0;
11205 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11210 if (!rsurface.passcolor4f)
11212 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11214 c2[0] = c[0] + r_refdef.scene.ambient;
11215 c2[1] = c[1] + r_refdef.scene.ambient;
11216 c2[2] = c[2] + r_refdef.scene.ambient;
11219 rsurface.passcolor4f = rsurface.array_passcolor4f;
11220 rsurface.passcolor4f_vertexbuffer = 0;
11221 rsurface.passcolor4f_bufferoffset = 0;
11224 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11227 rsurface.passcolor4f = NULL;
11228 rsurface.passcolor4f_vertexbuffer = 0;
11229 rsurface.passcolor4f_bufferoffset = 0;
11230 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11231 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11232 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11233 GL_Color(r, g, b, a);
11234 RSurf_BindLightmapForBatch();
11238 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11240 // TODO: optimize applyfog && applycolor case
11241 // just apply fog if necessary, and tint the fog color array if necessary
11242 rsurface.passcolor4f = NULL;
11243 rsurface.passcolor4f_vertexbuffer = 0;
11244 rsurface.passcolor4f_bufferoffset = 0;
11245 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11246 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11247 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11248 GL_Color(r, g, b, a);
11252 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11255 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11256 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11257 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11258 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11259 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11260 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11261 GL_Color(r, g, b, a);
11265 static void RSurf_DrawBatch_GL11_ClampColor(void)
11270 if (!rsurface.passcolor4f)
11272 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11274 c2[0] = bound(0.0f, c1[0], 1.0f);
11275 c2[1] = bound(0.0f, c1[1], 1.0f);
11276 c2[2] = bound(0.0f, c1[2], 1.0f);
11277 c2[3] = bound(0.0f, c1[3], 1.0f);
11281 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11289 vec3_t ambientcolor;
11290 vec3_t diffusecolor;
11294 VectorCopy(rsurface.modellight_lightdir, lightdir);
11295 f = 0.5f * r_refdef.lightmapintensity;
11296 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11297 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11298 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11299 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11300 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11301 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11303 if (VectorLength2(diffusecolor) > 0)
11305 // q3-style directional shading
11306 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)
11308 if ((f = DotProduct(n, lightdir)) > 0)
11309 VectorMA(ambientcolor, f, diffusecolor, c);
11311 VectorCopy(ambientcolor, c);
11318 rsurface.passcolor4f = rsurface.array_passcolor4f;
11319 rsurface.passcolor4f_vertexbuffer = 0;
11320 rsurface.passcolor4f_bufferoffset = 0;
11321 *applycolor = false;
11325 *r = ambientcolor[0];
11326 *g = ambientcolor[1];
11327 *b = ambientcolor[2];
11328 rsurface.passcolor4f = NULL;
11329 rsurface.passcolor4f_vertexbuffer = 0;
11330 rsurface.passcolor4f_bufferoffset = 0;
11334 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11336 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
11337 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11338 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11339 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11340 GL_Color(r, g, b, a);
11344 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
11350 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
11352 f = 1 - RSurf_FogVertex(v);
11360 void RSurf_SetupDepthAndCulling(void)
11362 // submodels are biased to avoid z-fighting with world surfaces that they
11363 // may be exactly overlapping (avoids z-fighting artifacts on certain
11364 // doors and things in Quake maps)
11365 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11366 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11367 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11368 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11371 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11373 // transparent sky would be ridiculous
11374 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11376 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11377 skyrenderlater = true;
11378 RSurf_SetupDepthAndCulling();
11379 GL_DepthMask(true);
11380 // LordHavoc: HalfLife maps have freaky skypolys so don't use
11381 // skymasking on them, and Quake3 never did sky masking (unlike
11382 // software Quake and software Quake2), so disable the sky masking
11383 // in Quake3 maps as it causes problems with q3map2 sky tricks,
11384 // and skymasking also looks very bad when noclipping outside the
11385 // level, so don't use it then either.
11386 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11388 R_Mesh_ResetTextureState();
11389 if (skyrendermasked)
11391 R_SetupShader_DepthOrShadow();
11392 // depth-only (masking)
11393 GL_ColorMask(0,0,0,0);
11394 // just to make sure that braindead drivers don't draw
11395 // anything despite that colormask...
11396 GL_BlendFunc(GL_ZERO, GL_ONE);
11397 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11398 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11402 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11404 GL_BlendFunc(GL_ONE, GL_ZERO);
11405 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
11406 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11407 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11410 if (skyrendermasked)
11411 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11413 R_Mesh_ResetTextureState();
11414 GL_Color(1, 1, 1, 1);
11417 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11418 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11419 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11421 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11425 // render screenspace normalmap to texture
11426 GL_DepthMask(true);
11427 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist);
11432 // bind lightmap texture
11434 // water/refraction/reflection/camera surfaces have to be handled specially
11435 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
11437 int start, end, startplaneindex;
11438 for (start = 0;start < texturenumsurfaces;start = end)
11440 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
11441 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
11443 // now that we have a batch using the same planeindex, render it
11444 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11446 // render water or distortion background
11447 GL_DepthMask(true);
11448 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start);
11449 RSurf_BindReflectionForBatch(startplaneindex);
11450 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11451 RSurf_BindLightmapForBatch();
11453 // blend surface on top
11454 GL_DepthMask(false);
11455 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11458 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
11460 // render surface with reflection texture as input
11461 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11462 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11463 RSurf_BindReflectionForBatch(startplaneindex);
11464 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11465 RSurf_BindLightmapForBatch();
11472 // render surface batch normally
11473 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11474 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
11475 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11476 RSurf_BindLightmapForBatch();
11480 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11482 // OpenGL 1.3 path - anything not completely ancient
11483 qboolean applycolor;
11486 const texturelayer_t *layer;
11487 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);
11488 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11490 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11493 int layertexrgbscale;
11494 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11496 if (layerindex == 0)
11497 GL_AlphaTest(true);
11500 GL_AlphaTest(false);
11501 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11504 GL_DepthMask(layer->depthmask && writedepth);
11505 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11506 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11508 layertexrgbscale = 4;
11509 VectorScale(layer->color, 0.25f, layercolor);
11511 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11513 layertexrgbscale = 2;
11514 VectorScale(layer->color, 0.5f, layercolor);
11518 layertexrgbscale = 1;
11519 VectorScale(layer->color, 1.0f, layercolor);
11521 layercolor[3] = layer->color[3];
11522 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11523 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11524 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11525 switch (layer->type)
11527 case TEXTURELAYERTYPE_LITTEXTURE:
11528 // single-pass lightmapped texture with 2x rgbscale
11529 R_Mesh_TexBind(0, r_texture_white);
11530 R_Mesh_TexMatrix(0, NULL);
11531 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11532 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11533 R_Mesh_TexBind(1, layer->texture);
11534 R_Mesh_TexMatrix(1, &layer->texmatrix);
11535 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11536 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11537 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11538 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11539 else if (rsurface.uselightmaptexture)
11540 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11542 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11544 case TEXTURELAYERTYPE_TEXTURE:
11545 // singletexture unlit texture with transparency support
11546 R_Mesh_TexBind(0, layer->texture);
11547 R_Mesh_TexMatrix(0, &layer->texmatrix);
11548 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11549 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11550 R_Mesh_TexBind(1, 0);
11551 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11552 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11554 case TEXTURELAYERTYPE_FOG:
11555 // singletexture fogging
11556 if (layer->texture)
11558 R_Mesh_TexBind(0, layer->texture);
11559 R_Mesh_TexMatrix(0, &layer->texmatrix);
11560 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11561 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11565 R_Mesh_TexBind(0, 0);
11566 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11568 R_Mesh_TexBind(1, 0);
11569 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11570 // generate a color array for the fog pass
11571 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11572 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
11576 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11580 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11582 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11583 GL_AlphaTest(false);
11587 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11589 // OpenGL 1.1 - crusty old voodoo path
11592 const texturelayer_t *layer;
11593 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);
11594 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11596 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11598 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11600 if (layerindex == 0)
11601 GL_AlphaTest(true);
11604 GL_AlphaTest(false);
11605 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11608 GL_DepthMask(layer->depthmask && writedepth);
11609 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11610 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11611 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11612 switch (layer->type)
11614 case TEXTURELAYERTYPE_LITTEXTURE:
11615 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11617 // two-pass lit texture with 2x rgbscale
11618 // first the lightmap pass
11619 R_Mesh_TexBind(0, r_texture_white);
11620 R_Mesh_TexMatrix(0, NULL);
11621 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11622 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11623 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11624 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
11625 else if (rsurface.uselightmaptexture)
11626 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
11628 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
11629 // then apply the texture to it
11630 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11631 R_Mesh_TexBind(0, layer->texture);
11632 R_Mesh_TexMatrix(0, &layer->texmatrix);
11633 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11634 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11635 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);
11639 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11640 R_Mesh_TexBind(0, layer->texture);
11641 R_Mesh_TexMatrix(0, &layer->texmatrix);
11642 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11643 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11644 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11645 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);
11647 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);
11650 case TEXTURELAYERTYPE_TEXTURE:
11651 // singletexture unlit texture with transparency support
11652 R_Mesh_TexBind(0, layer->texture);
11653 R_Mesh_TexMatrix(0, &layer->texmatrix);
11654 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11655 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11656 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);
11658 case TEXTURELAYERTYPE_FOG:
11659 // singletexture fogging
11660 if (layer->texture)
11662 R_Mesh_TexBind(0, layer->texture);
11663 R_Mesh_TexMatrix(0, &layer->texmatrix);
11664 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11665 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11669 R_Mesh_TexBind(0, 0);
11670 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11672 // generate a color array for the fog pass
11673 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11674 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
11678 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11682 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11684 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11685 GL_AlphaTest(false);
11689 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11693 r_vertexgeneric_t *batchvertex;
11696 GL_AlphaTest(false);
11697 R_Mesh_ResetTextureState();
11698 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11700 if(rsurface.texture && rsurface.texture->currentskinframe)
11702 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11703 c[3] *= rsurface.texture->currentalpha;
11713 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11715 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11716 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11717 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11720 // brighten it up (as texture value 127 means "unlit")
11721 c[0] *= 2 * r_refdef.view.colorscale;
11722 c[1] *= 2 * r_refdef.view.colorscale;
11723 c[2] *= 2 * r_refdef.view.colorscale;
11725 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11726 c[3] *= r_wateralpha.value;
11728 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11730 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11731 GL_DepthMask(false);
11733 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11735 GL_BlendFunc(GL_ONE, GL_ONE);
11736 GL_DepthMask(false);
11738 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11740 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11741 GL_DepthMask(false);
11743 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11745 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11746 GL_DepthMask(false);
11750 GL_BlendFunc(GL_ONE, GL_ZERO);
11751 GL_DepthMask(writedepth);
11754 if (r_showsurfaces.integer == 3)
11756 rsurface.passcolor4f = NULL;
11758 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11760 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11762 rsurface.passcolor4f = NULL;
11763 rsurface.passcolor4f_vertexbuffer = 0;
11764 rsurface.passcolor4f_bufferoffset = 0;
11766 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11768 qboolean applycolor = true;
11771 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11773 r_refdef.lightmapintensity = 1;
11774 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
11775 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11779 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11781 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11782 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11783 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11786 if(!rsurface.passcolor4f)
11787 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
11789 RSurf_DrawBatch_GL11_ApplyAmbient();
11790 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
11791 if(r_refdef.fogenabled)
11792 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
11793 RSurf_DrawBatch_GL11_ClampColor();
11795 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
11796 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11799 else if (!r_refdef.view.showdebug)
11801 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11802 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11803 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11805 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11806 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
11808 R_Mesh_PrepareVertices_Generic_Unlock();
11811 else if (r_showsurfaces.integer == 4)
11813 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11814 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11815 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11817 unsigned char c = vi << 3;
11818 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11819 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
11821 R_Mesh_PrepareVertices_Generic_Unlock();
11824 else if (r_showsurfaces.integer == 2)
11827 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11828 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
11829 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
11831 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
11832 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
11833 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
11834 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
11835 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
11836 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
11837 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
11839 R_Mesh_PrepareVertices_Generic_Unlock();
11840 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
11844 int texturesurfaceindex;
11846 const msurface_t *surface;
11847 unsigned char surfacecolor4ub[4];
11848 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11849 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
11851 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11853 surface = texturesurfacelist[texturesurfaceindex];
11854 k = (int)(((size_t)surface) / sizeof(msurface_t));
11855 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
11856 for (j = 0;j < surface->num_vertices;j++)
11858 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11859 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
11863 R_Mesh_PrepareVertices_Generic_Unlock();
11868 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11871 RSurf_SetupDepthAndCulling();
11872 if (r_showsurfaces.integer)
11874 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11877 switch (vid.renderpath)
11879 case RENDERPATH_GL20:
11880 case RENDERPATH_CGGL:
11881 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11883 case RENDERPATH_GL13:
11884 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11886 case RENDERPATH_GL11:
11887 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11893 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11896 RSurf_SetupDepthAndCulling();
11897 if (r_showsurfaces.integer)
11899 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11902 switch (vid.renderpath)
11904 case RENDERPATH_GL20:
11905 case RENDERPATH_CGGL:
11906 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11908 case RENDERPATH_GL13:
11909 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11911 case RENDERPATH_GL11:
11912 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11918 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11921 int texturenumsurfaces, endsurface;
11922 texture_t *texture;
11923 const msurface_t *surface;
11924 #define MAXBATCH_TRANSPARENTSURFACES 256
11925 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11927 // if the model is static it doesn't matter what value we give for
11928 // wantnormals and wanttangents, so this logic uses only rules applicable
11929 // to a model, knowing that they are meaningless otherwise
11930 if (ent == r_refdef.scene.worldentity)
11931 RSurf_ActiveWorldEntity();
11932 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11933 RSurf_ActiveModelEntity(ent, false, false, false);
11936 switch (vid.renderpath)
11938 case RENDERPATH_GL20:
11939 case RENDERPATH_CGGL:
11940 RSurf_ActiveModelEntity(ent, true, true, false);
11942 case RENDERPATH_GL13:
11943 case RENDERPATH_GL11:
11944 RSurf_ActiveModelEntity(ent, true, false, false);
11949 if (r_transparentdepthmasking.integer)
11951 qboolean setup = false;
11952 for (i = 0;i < numsurfaces;i = j)
11955 surface = rsurface.modelsurfaces + surfacelist[i];
11956 texture = surface->texture;
11957 rsurface.texture = R_GetCurrentTexture(texture);
11958 rsurface.lightmaptexture = NULL;
11959 rsurface.deluxemaptexture = NULL;
11960 rsurface.uselightmaptexture = false;
11961 // scan ahead until we find a different texture
11962 endsurface = min(i + 1024, numsurfaces);
11963 texturenumsurfaces = 0;
11964 texturesurfacelist[texturenumsurfaces++] = surface;
11965 for (;j < endsurface;j++)
11967 surface = rsurface.modelsurfaces + surfacelist[j];
11968 if (texture != surface->texture)
11970 texturesurfacelist[texturenumsurfaces++] = surface;
11972 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11974 // render the range of surfaces as depth
11978 GL_ColorMask(0,0,0,0);
11980 GL_DepthTest(true);
11981 GL_BlendFunc(GL_ONE, GL_ZERO);
11982 GL_DepthMask(true);
11983 GL_AlphaTest(false);
11984 R_Mesh_ResetTextureState();
11985 R_SetupShader_DepthOrShadow();
11987 RSurf_SetupDepthAndCulling();
11988 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11989 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11993 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11996 for (i = 0;i < numsurfaces;i = j)
11999 surface = rsurface.modelsurfaces + surfacelist[i];
12000 texture = surface->texture;
12001 rsurface.texture = R_GetCurrentTexture(texture);
12002 rsurface.lightmaptexture = surface->lightmaptexture;
12003 rsurface.deluxemaptexture = surface->deluxemaptexture;
12004 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
12005 // scan ahead until we find a different texture
12006 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12007 texturenumsurfaces = 0;
12008 texturesurfacelist[texturenumsurfaces++] = surface;
12009 for (;j < endsurface;j++)
12011 surface = rsurface.modelsurfaces + surfacelist[j];
12012 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
12014 texturesurfacelist[texturenumsurfaces++] = surface;
12016 // render the range of surfaces
12017 if (ent == r_refdef.scene.worldentity)
12018 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12020 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12022 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12023 GL_AlphaTest(false);
12026 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12028 // transparent surfaces get pushed off into the transparent queue
12029 int surfacelistindex;
12030 const msurface_t *surface;
12031 vec3_t tempcenter, center;
12032 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12034 surface = texturesurfacelist[surfacelistindex];
12035 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12036 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12037 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12038 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12039 if (queueentity->transparent_offset) // transparent offset
12041 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12042 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12043 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12045 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12049 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12051 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12053 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12055 RSurf_SetupDepthAndCulling();
12056 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12057 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12061 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12063 const entity_render_t *queueentity = r_refdef.scene.worldentity;
12066 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12069 if (!rsurface.texture->currentnumlayers)
12071 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12072 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12074 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12076 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12077 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12078 else if (!rsurface.texture->currentnumlayers)
12080 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12082 // in the deferred case, transparent surfaces were queued during prepass
12083 if (!r_shadow_usingdeferredprepass)
12084 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12088 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12089 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12094 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12097 texture_t *texture;
12098 // break the surface list down into batches by texture and use of lightmapping
12099 for (i = 0;i < numsurfaces;i = j)
12102 // texture is the base texture pointer, rsurface.texture is the
12103 // current frame/skin the texture is directing us to use (for example
12104 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12105 // use skin 1 instead)
12106 texture = surfacelist[i]->texture;
12107 rsurface.texture = R_GetCurrentTexture(texture);
12108 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12109 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12110 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12111 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12113 // if this texture is not the kind we want, skip ahead to the next one
12114 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12118 // simply scan ahead until we find a different texture or lightmap state
12119 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12121 // render the range of surfaces
12122 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12126 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12130 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12133 if (!rsurface.texture->currentnumlayers)
12135 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12136 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12138 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12140 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12141 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12142 else if (!rsurface.texture->currentnumlayers)
12144 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12146 // in the deferred case, transparent surfaces were queued during prepass
12147 if (!r_shadow_usingdeferredprepass)
12148 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12152 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12153 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12158 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12161 texture_t *texture;
12162 // break the surface list down into batches by texture and use of lightmapping
12163 for (i = 0;i < numsurfaces;i = j)
12166 // texture is the base texture pointer, rsurface.texture is the
12167 // current frame/skin the texture is directing us to use (for example
12168 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12169 // use skin 1 instead)
12170 texture = surfacelist[i]->texture;
12171 rsurface.texture = R_GetCurrentTexture(texture);
12172 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12173 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12174 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12175 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12177 // if this texture is not the kind we want, skip ahead to the next one
12178 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12182 // simply scan ahead until we find a different texture or lightmap state
12183 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12185 // render the range of surfaces
12186 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12190 float locboxvertex3f[6*4*3] =
12192 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12193 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12194 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12195 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12196 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12197 1,0,0, 0,0,0, 0,1,0, 1,1,0
12200 unsigned short locboxelements[6*2*3] =
12205 12,13,14, 12,14,15,
12206 16,17,18, 16,18,19,
12210 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12213 cl_locnode_t *loc = (cl_locnode_t *)ent;
12215 float vertex3f[6*4*3];
12217 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12218 GL_DepthMask(false);
12219 GL_DepthRange(0, 1);
12220 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12221 GL_DepthTest(true);
12222 GL_CullFace(GL_NONE);
12223 R_EntityMatrix(&identitymatrix);
12225 R_Mesh_ResetTextureState();
12227 i = surfacelist[0];
12228 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12229 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12230 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12231 surfacelist[0] < 0 ? 0.5f : 0.125f);
12233 if (VectorCompare(loc->mins, loc->maxs))
12235 VectorSet(size, 2, 2, 2);
12236 VectorMA(loc->mins, -0.5f, size, mins);
12240 VectorCopy(loc->mins, mins);
12241 VectorSubtract(loc->maxs, loc->mins, size);
12244 for (i = 0;i < 6*4*3;)
12245 for (j = 0;j < 3;j++, i++)
12246 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12248 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
12249 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12250 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
12253 void R_DrawLocs(void)
12256 cl_locnode_t *loc, *nearestloc;
12258 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12259 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12261 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12262 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12266 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12268 if (decalsystem->decals)
12269 Mem_Free(decalsystem->decals);
12270 memset(decalsystem, 0, sizeof(*decalsystem));
12273 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)
12276 tridecal_t *decals;
12279 // expand or initialize the system
12280 if (decalsystem->maxdecals <= decalsystem->numdecals)
12282 decalsystem_t old = *decalsystem;
12283 qboolean useshortelements;
12284 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12285 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12286 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12287 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12288 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12289 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12290 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12291 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12292 if (decalsystem->numdecals)
12293 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12295 Mem_Free(old.decals);
12296 for (i = 0;i < decalsystem->maxdecals*3;i++)
12297 decalsystem->element3i[i] = i;
12298 if (useshortelements)
12299 for (i = 0;i < decalsystem->maxdecals*3;i++)
12300 decalsystem->element3s[i] = i;
12303 // grab a decal and search for another free slot for the next one
12304 decals = decalsystem->decals;
12305 decal = decalsystem->decals + (i = decalsystem->freedecal++);
12306 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12308 decalsystem->freedecal = i;
12309 if (decalsystem->numdecals <= i)
12310 decalsystem->numdecals = i + 1;
12312 // initialize the decal
12314 decal->triangleindex = triangleindex;
12315 decal->surfaceindex = surfaceindex;
12316 decal->decalsequence = decalsequence;
12317 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12318 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12319 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12320 decal->color4ub[0][3] = 255;
12321 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12322 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12323 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12324 decal->color4ub[1][3] = 255;
12325 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12326 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12327 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12328 decal->color4ub[2][3] = 255;
12329 decal->vertex3f[0][0] = v0[0];
12330 decal->vertex3f[0][1] = v0[1];
12331 decal->vertex3f[0][2] = v0[2];
12332 decal->vertex3f[1][0] = v1[0];
12333 decal->vertex3f[1][1] = v1[1];
12334 decal->vertex3f[1][2] = v1[2];
12335 decal->vertex3f[2][0] = v2[0];
12336 decal->vertex3f[2][1] = v2[1];
12337 decal->vertex3f[2][2] = v2[2];
12338 decal->texcoord2f[0][0] = t0[0];
12339 decal->texcoord2f[0][1] = t0[1];
12340 decal->texcoord2f[1][0] = t1[0];
12341 decal->texcoord2f[1][1] = t1[1];
12342 decal->texcoord2f[2][0] = t2[0];
12343 decal->texcoord2f[2][1] = t2[1];
12346 extern cvar_t cl_decals_bias;
12347 extern cvar_t cl_decals_models;
12348 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12349 // baseparms, parms, temps
12350 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
12355 const float *vertex3f;
12357 float points[2][9][3];
12364 e = rsurface.modelelement3i + 3*triangleindex;
12366 vertex3f = rsurface.modelvertex3f;
12368 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12370 index = 3*e[cornerindex];
12371 VectorCopy(vertex3f + index, v[cornerindex]);
12374 //TriangleNormal(v[0], v[1], v[2], normal);
12375 //if (DotProduct(normal, localnormal) < 0.0f)
12377 // clip by each of the box planes formed from the projection matrix
12378 // if anything survives, we emit the decal
12379 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]);
12382 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]);
12385 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]);
12388 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]);
12391 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]);
12394 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]);
12397 // some part of the triangle survived, so we have to accept it...
12400 // dynamic always uses the original triangle
12402 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12404 index = 3*e[cornerindex];
12405 VectorCopy(vertex3f + index, v[cornerindex]);
12408 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12410 // convert vertex positions to texcoords
12411 Matrix4x4_Transform(projection, v[cornerindex], temp);
12412 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12413 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12414 // calculate distance fade from the projection origin
12415 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12416 f = bound(0.0f, f, 1.0f);
12417 c[cornerindex][0] = r * f;
12418 c[cornerindex][1] = g * f;
12419 c[cornerindex][2] = b * f;
12420 c[cornerindex][3] = 1.0f;
12421 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12424 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
12426 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12427 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);
12429 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)
12431 matrix4x4_t projection;
12432 decalsystem_t *decalsystem;
12435 const msurface_t *surface;
12436 const msurface_t *surfaces;
12437 const int *surfacelist;
12438 const texture_t *texture;
12440 int numsurfacelist;
12441 int surfacelistindex;
12444 float localorigin[3];
12445 float localnormal[3];
12446 float localmins[3];
12447 float localmaxs[3];
12450 float planes[6][4];
12453 int bih_triangles_count;
12454 int bih_triangles[256];
12455 int bih_surfaces[256];
12457 decalsystem = &ent->decalsystem;
12458 model = ent->model;
12459 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12461 R_DecalSystem_Reset(&ent->decalsystem);
12465 if (!model->brush.data_nodes && !cl_decals_models.integer)
12467 if (decalsystem->model)
12468 R_DecalSystem_Reset(decalsystem);
12472 if (decalsystem->model != model)
12473 R_DecalSystem_Reset(decalsystem);
12474 decalsystem->model = model;
12476 RSurf_ActiveModelEntity(ent, false, false, false);
12478 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12479 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12480 VectorNormalize(localnormal);
12481 localsize = worldsize*rsurface.inversematrixscale;
12482 localmins[0] = localorigin[0] - localsize;
12483 localmins[1] = localorigin[1] - localsize;
12484 localmins[2] = localorigin[2] - localsize;
12485 localmaxs[0] = localorigin[0] + localsize;
12486 localmaxs[1] = localorigin[1] + localsize;
12487 localmaxs[2] = localorigin[2] + localsize;
12489 //VectorCopy(localnormal, planes[4]);
12490 //VectorVectors(planes[4], planes[2], planes[0]);
12491 AnglesFromVectors(angles, localnormal, NULL, false);
12492 AngleVectors(angles, planes[0], planes[2], planes[4]);
12493 VectorNegate(planes[0], planes[1]);
12494 VectorNegate(planes[2], planes[3]);
12495 VectorNegate(planes[4], planes[5]);
12496 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12497 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12498 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12499 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12500 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12501 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12506 matrix4x4_t forwardprojection;
12507 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12508 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12513 float projectionvector[4][3];
12514 VectorScale(planes[0], ilocalsize, projectionvector[0]);
12515 VectorScale(planes[2], ilocalsize, projectionvector[1]);
12516 VectorScale(planes[4], ilocalsize, projectionvector[2]);
12517 projectionvector[0][0] = planes[0][0] * ilocalsize;
12518 projectionvector[0][1] = planes[1][0] * ilocalsize;
12519 projectionvector[0][2] = planes[2][0] * ilocalsize;
12520 projectionvector[1][0] = planes[0][1] * ilocalsize;
12521 projectionvector[1][1] = planes[1][1] * ilocalsize;
12522 projectionvector[1][2] = planes[2][1] * ilocalsize;
12523 projectionvector[2][0] = planes[0][2] * ilocalsize;
12524 projectionvector[2][1] = planes[1][2] * ilocalsize;
12525 projectionvector[2][2] = planes[2][2] * ilocalsize;
12526 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12527 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12528 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12529 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12533 dynamic = model->surfmesh.isanimated;
12534 numsurfacelist = model->nummodelsurfaces;
12535 surfacelist = model->sortedmodelsurfaces;
12536 surfaces = model->data_surfaces;
12539 bih_triangles_count = -1;
12542 if(model->render_bih.numleafs)
12543 bih = &model->render_bih;
12544 else if(model->collision_bih.numleafs)
12545 bih = &model->collision_bih;
12548 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
12549 if(bih_triangles_count == 0)
12551 if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
12553 if(bih_triangles_count > 0)
12555 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
12557 surfaceindex = bih_surfaces[triangleindex];
12558 surface = surfaces + surfaceindex;
12559 texture = surface->texture;
12560 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12562 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12564 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
12569 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12571 surfaceindex = surfacelist[surfacelistindex];
12572 surface = surfaces + surfaceindex;
12573 // check cull box first because it rejects more than any other check
12574 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12576 // skip transparent surfaces
12577 texture = surface->texture;
12578 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12580 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12582 numtriangles = surface->num_triangles;
12583 for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
12584 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
12589 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12590 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)
12592 int renderentityindex;
12593 float worldmins[3];
12594 float worldmaxs[3];
12595 entity_render_t *ent;
12597 if (!cl_decals_newsystem.integer)
12600 worldmins[0] = worldorigin[0] - worldsize;
12601 worldmins[1] = worldorigin[1] - worldsize;
12602 worldmins[2] = worldorigin[2] - worldsize;
12603 worldmaxs[0] = worldorigin[0] + worldsize;
12604 worldmaxs[1] = worldorigin[1] + worldsize;
12605 worldmaxs[2] = worldorigin[2] + worldsize;
12607 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12609 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12611 ent = r_refdef.scene.entities[renderentityindex];
12612 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12615 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12619 typedef struct r_decalsystem_splatqueue_s
12621 vec3_t worldorigin;
12622 vec3_t worldnormal;
12628 r_decalsystem_splatqueue_t;
12630 int r_decalsystem_numqueued = 0;
12631 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12633 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)
12635 r_decalsystem_splatqueue_t *queue;
12637 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12640 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12641 VectorCopy(worldorigin, queue->worldorigin);
12642 VectorCopy(worldnormal, queue->worldnormal);
12643 Vector4Set(queue->color, r, g, b, a);
12644 Vector4Set(queue->tcrange, s1, t1, s2, t2);
12645 queue->worldsize = worldsize;
12646 queue->decalsequence = cl.decalsequence++;
12649 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12652 r_decalsystem_splatqueue_t *queue;
12654 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12655 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);
12656 r_decalsystem_numqueued = 0;
12659 extern cvar_t cl_decals_max;
12660 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12663 decalsystem_t *decalsystem = &ent->decalsystem;
12670 if (!decalsystem->numdecals)
12673 if (r_showsurfaces.integer)
12676 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12678 R_DecalSystem_Reset(decalsystem);
12682 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12683 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12685 if (decalsystem->lastupdatetime)
12686 frametime = (cl.time - decalsystem->lastupdatetime);
12689 decalsystem->lastupdatetime = cl.time;
12690 decal = decalsystem->decals;
12691 numdecals = decalsystem->numdecals;
12693 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12695 if (decal->color4ub[0][3])
12697 decal->lived += frametime;
12698 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12700 memset(decal, 0, sizeof(*decal));
12701 if (decalsystem->freedecal > i)
12702 decalsystem->freedecal = i;
12706 decal = decalsystem->decals;
12707 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12710 // collapse the array by shuffling the tail decals into the gaps
12713 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12714 decalsystem->freedecal++;
12715 if (decalsystem->freedecal == numdecals)
12717 decal[decalsystem->freedecal] = decal[--numdecals];
12720 decalsystem->numdecals = numdecals;
12722 if (numdecals <= 0)
12724 // if there are no decals left, reset decalsystem
12725 R_DecalSystem_Reset(decalsystem);
12729 extern skinframe_t *decalskinframe;
12730 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12733 decalsystem_t *decalsystem = &ent->decalsystem;
12742 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12745 numdecals = decalsystem->numdecals;
12749 if (r_showsurfaces.integer)
12752 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12754 R_DecalSystem_Reset(decalsystem);
12758 // if the model is static it doesn't matter what value we give for
12759 // wantnormals and wanttangents, so this logic uses only rules applicable
12760 // to a model, knowing that they are meaningless otherwise
12761 if (ent == r_refdef.scene.worldentity)
12762 RSurf_ActiveWorldEntity();
12764 RSurf_ActiveModelEntity(ent, false, false, false);
12766 decalsystem->lastupdatetime = cl.time;
12767 decal = decalsystem->decals;
12769 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12771 // update vertex positions for animated models
12772 v3f = decalsystem->vertex3f;
12773 c4f = decalsystem->color4f;
12774 t2f = decalsystem->texcoord2f;
12775 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12777 if (!decal->color4ub[0][3])
12780 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12783 // update color values for fading decals
12784 if (decal->lived >= cl_decals_time.value)
12786 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12787 alpha *= (1.0f/255.0f);
12790 alpha = 1.0f/255.0f;
12792 c4f[ 0] = decal->color4ub[0][0] * alpha;
12793 c4f[ 1] = decal->color4ub[0][1] * alpha;
12794 c4f[ 2] = decal->color4ub[0][2] * alpha;
12796 c4f[ 4] = decal->color4ub[1][0] * alpha;
12797 c4f[ 5] = decal->color4ub[1][1] * alpha;
12798 c4f[ 6] = decal->color4ub[1][2] * alpha;
12800 c4f[ 8] = decal->color4ub[2][0] * alpha;
12801 c4f[ 9] = decal->color4ub[2][1] * alpha;
12802 c4f[10] = decal->color4ub[2][2] * alpha;
12805 t2f[0] = decal->texcoord2f[0][0];
12806 t2f[1] = decal->texcoord2f[0][1];
12807 t2f[2] = decal->texcoord2f[1][0];
12808 t2f[3] = decal->texcoord2f[1][1];
12809 t2f[4] = decal->texcoord2f[2][0];
12810 t2f[5] = decal->texcoord2f[2][1];
12812 // update vertex positions for animated models
12813 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
12815 e = rsurface.modelelement3i + 3*decal->triangleindex;
12816 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
12817 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
12818 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
12822 VectorCopy(decal->vertex3f[0], v3f);
12823 VectorCopy(decal->vertex3f[1], v3f + 3);
12824 VectorCopy(decal->vertex3f[2], v3f + 6);
12827 if (r_refdef.fogenabled)
12829 alpha = RSurf_FogVertex(v3f);
12830 VectorScale(c4f, alpha, c4f);
12831 alpha = RSurf_FogVertex(v3f + 3);
12832 VectorScale(c4f + 4, alpha, c4f + 4);
12833 alpha = RSurf_FogVertex(v3f + 6);
12834 VectorScale(c4f + 8, alpha, c4f + 8);
12845 r_refdef.stats.drawndecals += numtris;
12847 // now render the decals all at once
12848 // (this assumes they all use one particle font texture!)
12849 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);
12850 R_Mesh_ResetTextureState();
12851 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
12852 GL_DepthMask(false);
12853 GL_DepthRange(0, 1);
12854 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12855 GL_DepthTest(true);
12856 GL_CullFace(GL_NONE);
12857 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12858 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12859 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
12863 static void R_DrawModelDecals(void)
12867 // fade faster when there are too many decals
12868 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12869 for (i = 0;i < r_refdef.scene.numentities;i++)
12870 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12872 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12873 for (i = 0;i < r_refdef.scene.numentities;i++)
12874 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12875 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12877 R_DecalSystem_ApplySplatEntitiesQueue();
12879 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12880 for (i = 0;i < r_refdef.scene.numentities;i++)
12881 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12883 r_refdef.stats.totaldecals += numdecals;
12885 if (r_showsurfaces.integer)
12888 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12890 for (i = 0;i < r_refdef.scene.numentities;i++)
12892 if (!r_refdef.viewcache.entityvisible[i])
12894 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12895 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12899 extern cvar_t mod_collision_bih;
12900 void R_DrawDebugModel(void)
12902 entity_render_t *ent = rsurface.entity;
12903 int i, j, k, l, flagsmask;
12904 const msurface_t *surface;
12905 dp_model_t *model = ent->model;
12908 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12910 R_Mesh_ResetTextureState();
12911 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12912 GL_DepthRange(0, 1);
12913 GL_DepthTest(!r_showdisabledepthtest.integer);
12914 GL_DepthMask(false);
12915 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12917 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12921 qboolean cullbox = ent == r_refdef.scene.worldentity;
12922 const q3mbrush_t *brush;
12923 const bih_t *bih = &model->collision_bih;
12924 const bih_leaf_t *bihleaf;
12925 float vertex3f[3][3];
12926 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12928 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12930 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12932 switch (bihleaf->type)
12935 brush = model->brush.data_brushes + bihleaf->itemindex;
12936 if (brush->colbrushf && brush->colbrushf->numtriangles)
12938 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);
12939 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
12940 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
12943 case BIH_COLLISIONTRIANGLE:
12944 triangleindex = bihleaf->itemindex;
12945 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12946 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12947 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12948 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);
12949 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12950 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12952 case BIH_RENDERTRIANGLE:
12953 triangleindex = bihleaf->itemindex;
12954 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12955 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12956 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12957 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);
12958 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12959 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12965 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12967 if (r_showtris.integer || r_shownormals.integer)
12969 if (r_showdisabledepthtest.integer)
12971 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12972 GL_DepthMask(false);
12976 GL_BlendFunc(GL_ONE, GL_ZERO);
12977 GL_DepthMask(true);
12979 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12981 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12983 rsurface.texture = R_GetCurrentTexture(surface->texture);
12984 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12986 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
12987 if (r_showtris.value > 0)
12989 if (!rsurface.texture->currentlayers->depthmask)
12990 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12991 else if (ent == r_refdef.scene.worldentity)
12992 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12994 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12995 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12996 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
12998 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13001 if (r_shownormals.value < 0)
13003 qglBegin(GL_LINES);
13004 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13006 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13007 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13008 qglVertex3f(v[0], v[1], v[2]);
13009 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13010 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13011 qglVertex3f(v[0], v[1], v[2]);
13016 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13018 qglBegin(GL_LINES);
13019 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13021 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13022 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13023 qglVertex3f(v[0], v[1], v[2]);
13024 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13025 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13026 qglVertex3f(v[0], v[1], v[2]);
13030 qglBegin(GL_LINES);
13031 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13033 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13034 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13035 qglVertex3f(v[0], v[1], v[2]);
13036 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13037 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13038 qglVertex3f(v[0], v[1], v[2]);
13042 qglBegin(GL_LINES);
13043 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13045 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13046 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13047 qglVertex3f(v[0], v[1], v[2]);
13048 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13049 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13050 qglVertex3f(v[0], v[1], v[2]);
13057 rsurface.texture = NULL;
13061 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13062 int r_maxsurfacelist = 0;
13063 const msurface_t **r_surfacelist = NULL;
13064 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13066 int i, j, endj, flagsmask;
13067 dp_model_t *model = r_refdef.scene.worldmodel;
13068 msurface_t *surfaces;
13069 unsigned char *update;
13070 int numsurfacelist = 0;
13074 if (r_maxsurfacelist < model->num_surfaces)
13076 r_maxsurfacelist = model->num_surfaces;
13078 Mem_Free((msurface_t**)r_surfacelist);
13079 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13082 RSurf_ActiveWorldEntity();
13084 surfaces = model->data_surfaces;
13085 update = model->brushq1.lightmapupdateflags;
13087 // update light styles on this submodel
13088 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13090 model_brush_lightstyleinfo_t *style;
13091 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13093 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13095 int *list = style->surfacelist;
13096 style->value = r_refdef.scene.lightstylevalue[style->style];
13097 for (j = 0;j < style->numsurfaces;j++)
13098 update[list[j]] = true;
13103 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13107 R_DrawDebugModel();
13108 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13112 rsurface.lightmaptexture = NULL;
13113 rsurface.deluxemaptexture = NULL;
13114 rsurface.uselightmaptexture = false;
13115 rsurface.texture = NULL;
13116 rsurface.rtlight = NULL;
13117 numsurfacelist = 0;
13118 // add visible surfaces to draw list
13119 for (i = 0;i < model->nummodelsurfaces;i++)
13121 j = model->sortedmodelsurfaces[i];
13122 if (r_refdef.viewcache.world_surfacevisible[j])
13123 r_surfacelist[numsurfacelist++] = surfaces + j;
13125 // update lightmaps if needed
13126 if (model->brushq1.firstrender)
13128 model->brushq1.firstrender = false;
13129 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13131 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13135 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13136 if (r_refdef.viewcache.world_surfacevisible[j])
13138 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13140 // don't do anything if there were no surfaces
13141 if (!numsurfacelist)
13143 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13146 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13147 GL_AlphaTest(false);
13149 // add to stats if desired
13150 if (r_speeds.integer && !skysurfaces && !depthonly)
13152 r_refdef.stats.world_surfaces += numsurfacelist;
13153 for (j = 0;j < numsurfacelist;j++)
13154 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13157 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13160 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13162 int i, j, endj, flagsmask;
13163 dp_model_t *model = ent->model;
13164 msurface_t *surfaces;
13165 unsigned char *update;
13166 int numsurfacelist = 0;
13170 if (r_maxsurfacelist < model->num_surfaces)
13172 r_maxsurfacelist = model->num_surfaces;
13174 Mem_Free((msurface_t **)r_surfacelist);
13175 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13178 // if the model is static it doesn't matter what value we give for
13179 // wantnormals and wanttangents, so this logic uses only rules applicable
13180 // to a model, knowing that they are meaningless otherwise
13181 if (ent == r_refdef.scene.worldentity)
13182 RSurf_ActiveWorldEntity();
13183 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13184 RSurf_ActiveModelEntity(ent, false, false, false);
13186 RSurf_ActiveModelEntity(ent, true, true, true);
13187 else if (depthonly)
13189 switch (vid.renderpath)
13191 case RENDERPATH_GL20:
13192 case RENDERPATH_CGGL:
13193 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
13195 case RENDERPATH_GL13:
13196 case RENDERPATH_GL11:
13197 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
13203 switch (vid.renderpath)
13205 case RENDERPATH_GL20:
13206 case RENDERPATH_CGGL:
13207 RSurf_ActiveModelEntity(ent, true, true, false);
13209 case RENDERPATH_GL13:
13210 case RENDERPATH_GL11:
13211 RSurf_ActiveModelEntity(ent, true, false, false);
13216 surfaces = model->data_surfaces;
13217 update = model->brushq1.lightmapupdateflags;
13219 // update light styles
13220 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13222 model_brush_lightstyleinfo_t *style;
13223 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13225 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13227 int *list = style->surfacelist;
13228 style->value = r_refdef.scene.lightstylevalue[style->style];
13229 for (j = 0;j < style->numsurfaces;j++)
13230 update[list[j]] = true;
13235 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13239 R_DrawDebugModel();
13240 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13244 rsurface.lightmaptexture = NULL;
13245 rsurface.deluxemaptexture = NULL;
13246 rsurface.uselightmaptexture = false;
13247 rsurface.texture = NULL;
13248 rsurface.rtlight = NULL;
13249 numsurfacelist = 0;
13250 // add visible surfaces to draw list
13251 for (i = 0;i < model->nummodelsurfaces;i++)
13252 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13253 // don't do anything if there were no surfaces
13254 if (!numsurfacelist)
13256 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13259 // update lightmaps if needed
13263 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13268 R_BuildLightMap(ent, surfaces + j);
13273 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13275 R_BuildLightMap(ent, surfaces + j);
13276 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13277 GL_AlphaTest(false);
13279 // add to stats if desired
13280 if (r_speeds.integer && !skysurfaces && !depthonly)
13282 r_refdef.stats.entities_surfaces += numsurfacelist;
13283 for (j = 0;j < numsurfacelist;j++)
13284 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13287 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13290 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13292 static texture_t texture;
13293 static msurface_t surface;
13294 const msurface_t *surfacelist = &surface;
13296 // fake enough texture and surface state to render this geometry
13298 texture.update_lastrenderframe = -1; // regenerate this texture
13299 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13300 texture.currentskinframe = skinframe;
13301 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13302 texture.offsetmapping = OFFSETMAPPING_OFF;
13303 texture.offsetscale = 1;
13304 texture.specularscalemod = 1;
13305 texture.specularpowermod = 1;
13307 surface.texture = &texture;
13308 surface.num_triangles = numtriangles;
13309 surface.num_firsttriangle = firsttriangle;
13310 surface.num_vertices = numvertices;
13311 surface.num_firstvertex = firstvertex;
13314 rsurface.texture = R_GetCurrentTexture(surface.texture);
13315 rsurface.lightmaptexture = NULL;
13316 rsurface.deluxemaptexture = NULL;
13317 rsurface.uselightmaptexture = false;
13318 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13321 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)
13323 static msurface_t surface;
13324 const msurface_t *surfacelist = &surface;
13326 // fake enough texture and surface state to render this geometry
13328 surface.texture = texture;
13329 surface.num_triangles = numtriangles;
13330 surface.num_firsttriangle = firsttriangle;
13331 surface.num_vertices = numvertices;
13332 surface.num_firstvertex = firstvertex;
13335 rsurface.texture = R_GetCurrentTexture(surface.texture);
13336 rsurface.lightmaptexture = NULL;
13337 rsurface.deluxemaptexture = NULL;
13338 rsurface.uselightmaptexture = false;
13339 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);