some cleanup of glDelete calls to guard against bugs caused by GL
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4 #include "dpsoftrast.h"
5 #ifdef SUPPORTD3D
6 #include <d3d9.h>
7 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
8 extern D3DCAPS9 vid_d3d9caps;
9 #endif
10
11 // on GLES we have to use some proper #define's
12 #ifndef GL_FRAMEBUFFER
13 #define GL_FRAMEBUFFER                                   0x8D40
14 #define GL_DEPTH_ATTACHMENT                              0x8D00
15 #define GL_COLOR_ATTACHMENT0                             0x8CE0
16 #define GL_INVALID_FRAMEBUFFER_OPERATION                 0x0506
17 #endif
18 #ifndef GL_COLOR_ATTACHMENT1
19 #define GL_COLOR_ATTACHMENT1                             0x8CE1
20 #define GL_COLOR_ATTACHMENT2                             0x8CE2
21 #define GL_COLOR_ATTACHMENT3                             0x8CE3
22 #define GL_COLOR_ATTACHMENT4                             0x8CE4
23 #define GL_COLOR_ATTACHMENT5                             0x8CE5
24 #define GL_COLOR_ATTACHMENT6                             0x8CE6
25 #define GL_COLOR_ATTACHMENT7                             0x8CE7
26 #define GL_COLOR_ATTACHMENT8                             0x8CE8
27 #define GL_COLOR_ATTACHMENT9                             0x8CE9
28 #define GL_COLOR_ATTACHMENT10                            0x8CEA
29 #define GL_COLOR_ATTACHMENT11                            0x8CEB
30 #define GL_COLOR_ATTACHMENT12                            0x8CEC
31 #define GL_COLOR_ATTACHMENT13                            0x8CED
32 #define GL_COLOR_ATTACHMENT14                            0x8CEE
33 #define GL_COLOR_ATTACHMENT15                            0x8CEF
34 #endif
35 #ifndef GL_ARRAY_BUFFER
36 #define GL_ARRAY_BUFFER               0x8892
37 #define GL_ELEMENT_ARRAY_BUFFER       0x8893
38 #endif
39 //#ifndef GL_VERTEX_ARRAY
40 //#define GL_VERTEX_ARRAY                               0x8074
41 //#define GL_COLOR_ARRAY                                0x8076
42 //#define GL_TEXTURE_COORD_ARRAY                        0x8078
43 //#endif
44 #ifndef GL_TEXTURE0
45 #define GL_TEXTURE0                                     0x84C0
46 #define GL_TEXTURE1                                     0x84C1
47 #define GL_TEXTURE2                                     0x84C2
48 #define GL_TEXTURE3                                     0x84C3
49 #define GL_TEXTURE4                                     0x84C4
50 #define GL_TEXTURE5                                     0x84C5
51 #define GL_TEXTURE6                                     0x84C6
52 #define GL_TEXTURE7                                     0x84C7
53 #define GL_TEXTURE8                                     0x84C8
54 #define GL_TEXTURE9                                     0x84C9
55 #define GL_TEXTURE10                            0x84CA
56 #define GL_TEXTURE11                            0x84CB
57 #define GL_TEXTURE12                            0x84CC
58 #define GL_TEXTURE13                            0x84CD
59 #define GL_TEXTURE14                            0x84CE
60 #define GL_TEXTURE15                            0x84CF
61 #define GL_TEXTURE16                            0x84D0
62 #define GL_TEXTURE17                            0x84D1
63 #define GL_TEXTURE18                            0x84D2
64 #define GL_TEXTURE19                            0x84D3
65 #define GL_TEXTURE20                            0x84D4
66 #define GL_TEXTURE21                            0x84D5
67 #define GL_TEXTURE22                            0x84D6
68 #define GL_TEXTURE23                            0x84D7
69 #define GL_TEXTURE24                            0x84D8
70 #define GL_TEXTURE25                            0x84D9
71 #define GL_TEXTURE26                            0x84DA
72 #define GL_TEXTURE27                            0x84DB
73 #define GL_TEXTURE28                            0x84DC
74 #define GL_TEXTURE29                            0x84DD
75 #define GL_TEXTURE30                            0x84DE
76 #define GL_TEXTURE31                            0x84DF
77 #endif
78
79 #ifndef GL_TEXTURE_3D
80 #define GL_TEXTURE_3D                           0x806F
81 #endif
82 #ifndef GL_TEXTURE_CUBE_MAP
83 #define GL_TEXTURE_CUBE_MAP                 0x8513
84 #endif
85 //#ifndef GL_MODELVIEW
86 //#define GL_MODELVIEW                          0x1700
87 //#endif
88 //#ifndef GL_PROJECTION
89 //#define GL_PROJECTION                         0x1701
90 //#endif
91 //#ifndef GL_DECAL
92 //#define GL_DECAL                              0x2101
93 //#endif
94 //#ifndef GL_INTERPOLATE
95 //#define GL_INTERPOLATE                                0x8575
96 //#endif
97
98
99 #define MAX_RENDERTARGETS 4
100
101 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
102 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0", "use glBegin(GL_TRIANGLES);glTexCoord2f();glVertex3f();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
103 cvar_t gl_mesh_prefer_short_elements = {CVAR_SAVE, "gl_mesh_prefer_short_elements", "1", "use GL_UNSIGNED_SHORT element arrays instead of GL_UNSIGNED_INT"};
104 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
105 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
106
107 cvar_t r_render = {0, "r_render", "1", "enables rendering 3D views (you want this on!)"};
108 cvar_t r_renderview = {0, "r_renderview", "1", "enables rendering 3D views (you want this on!)"};
109 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
110 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
111 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
112 cvar_t gl_vbo = {CVAR_SAVE, "gl_vbo", "3", "make use of GL_ARB_vertex_buffer_object extension to store static geometry in video memory for faster rendering, 0 disables VBO allocation or use, 1 enables VBOs for vertex and triangle data, 2 only for vertex data, 3 for vertex data and triangle data of simple meshes (ones with only one surface)"};
113 cvar_t gl_vbo_dynamicvertex = {CVAR_SAVE, "gl_vbo_dynamicvertex", "0", "make use of GL_ARB_vertex_buffer_object extension when rendering dynamic (animated/procedural) geometry such as text and particles"};
114 cvar_t gl_vbo_dynamicindex = {CVAR_SAVE, "gl_vbo_dynamicindex", "0", "make use of GL_ARB_vertex_buffer_object extension when rendering dynamic (animated/procedural) geometry such as text and particles"};
115 cvar_t gl_fbo = {CVAR_SAVE, "gl_fbo", "1", "make use of GL_ARB_framebuffer_object extension to enable shadowmaps and other features using pixel formats different from the framebuffer"};
116
117 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
118 qboolean v_flipped_state = false;
119
120 r_viewport_t gl_viewport;
121 matrix4x4_t gl_modelmatrix;
122 matrix4x4_t gl_viewmatrix;
123 matrix4x4_t gl_modelviewmatrix;
124 matrix4x4_t gl_projectionmatrix;
125 matrix4x4_t gl_modelviewprojectionmatrix;
126 float gl_modelview16f[16];
127 float gl_modelviewprojection16f[16];
128 qboolean gl_modelmatrixchanged;
129
130 int gl_maxdrawrangeelementsvertices;
131 int gl_maxdrawrangeelementsindices;
132
133 #ifdef DEBUGGL
134 int errornumber = 0;
135
136 void GL_PrintError(int errornumber, const char *filename, int linenumber)
137 {
138         switch(errornumber)
139         {
140 #ifdef GL_INVALID_ENUM
141         case GL_INVALID_ENUM:
142                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
143                 break;
144 #endif
145 #ifdef GL_INVALID_VALUE
146         case GL_INVALID_VALUE:
147                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
148                 break;
149 #endif
150 #ifdef GL_INVALID_OPERATION
151         case GL_INVALID_OPERATION:
152                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
153                 break;
154 #endif
155 #ifdef GL_STACK_OVERFLOW
156         case GL_STACK_OVERFLOW:
157                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
158                 break;
159 #endif
160 #ifdef GL_STACK_UNDERFLOW
161         case GL_STACK_UNDERFLOW:
162                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
163                 break;
164 #endif
165 #ifdef GL_OUT_OF_MEMORY
166         case GL_OUT_OF_MEMORY:
167                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
168                 break;
169 #endif
170 #ifdef GL_TABLE_TOO_LARGE
171         case GL_TABLE_TOO_LARGE:
172                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
173                 break;
174 #endif
175 #ifdef GL_INVALID_FRAMEBUFFER_OPERATION
176         case GL_INVALID_FRAMEBUFFER_OPERATION:
177                 Con_Printf("GL_INVALID_FRAMEBUFFER_OPERATION at %s:%i\n", filename, linenumber);
178                 break;
179 #endif
180         default:
181                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
182                 break;
183         }
184 }
185 #endif
186
187 #define BACKENDACTIVECHECK if (!gl_state.active) Sys_Error("GL backend function called when backend is not active");
188
189 void SCR_ScreenShot_f (void);
190
191 typedef struct gltextureunit_s
192 {
193         int pointer_texcoord_components;
194         int pointer_texcoord_gltype;
195         size_t pointer_texcoord_stride;
196         const void *pointer_texcoord_pointer;
197         const r_meshbuffer_t *pointer_texcoord_vertexbuffer;
198         size_t pointer_texcoord_offset;
199
200         rtexture_t *texture;
201         int t2d, t3d, tcubemap;
202         int arrayenabled;
203         int rgbscale, alphascale;
204         int combine;
205         int combinergb, combinealpha;
206         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
207         int texmatrixenabled;
208         matrix4x4_t matrix;
209 }
210 gltextureunit_t;
211
212 typedef struct gl_state_s
213 {
214         int cullface;
215         int cullfaceenable;
216         int blendfunc1;
217         int blendfunc2;
218         qboolean blend;
219         GLboolean depthmask;
220         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
221         int depthtest;
222         int depthfunc;
223         float depthrange[2];
224         float polygonoffset[2];
225         int alphatest;
226         int alphafunc;
227         float alphafuncvalue;
228         qboolean alphatocoverage;
229         int scissortest;
230         unsigned int unit;
231         unsigned int clientunit;
232         gltextureunit_t units[MAX_TEXTUREUNITS];
233         float color4f[4];
234         int lockrange_first;
235         int lockrange_count;
236         int vertexbufferobject;
237         int elementbufferobject;
238         int uniformbufferobject;
239         int framebufferobject;
240         int defaultframebufferobject; // deal with platforms that use a non-zero default fbo
241         qboolean pointer_color_enabled;
242
243         int pointer_vertex_components;
244         int pointer_vertex_gltype;
245         size_t pointer_vertex_stride;
246         const void *pointer_vertex_pointer;
247         const r_meshbuffer_t *pointer_vertex_vertexbuffer;
248         size_t pointer_vertex_offset;
249
250         int pointer_color_components;
251         int pointer_color_gltype;
252         size_t pointer_color_stride;
253         const void *pointer_color_pointer;
254         const r_meshbuffer_t *pointer_color_vertexbuffer;
255         size_t pointer_color_offset;
256
257         void *preparevertices_tempdata;
258         size_t preparevertices_tempdatamaxsize;
259         r_meshbuffer_t *preparevertices_dynamicvertexbuffer;
260         r_vertexgeneric_t *preparevertices_vertexgeneric;
261         r_vertexmesh_t *preparevertices_vertexmesh;
262         int preparevertices_numvertices;
263
264         r_meshbuffer_t *draw_dynamicindexbuffer;
265
266         qboolean usevbo_staticvertex;
267         qboolean usevbo_staticindex;
268         qboolean usevbo_dynamicvertex;
269         qboolean usevbo_dynamicindex;
270
271         memexpandablearray_t meshbufferarray;
272
273         qboolean active;
274
275 #ifdef SUPPORTD3D
276 //      rtexture_t *d3drt_depthtexture;
277 //      rtexture_t *d3drt_colortextures[MAX_RENDERTARGETS];
278         IDirect3DSurface9 *d3drt_depthsurface;
279         IDirect3DSurface9 *d3drt_colorsurfaces[MAX_RENDERTARGETS];
280         IDirect3DSurface9 *d3drt_backbufferdepthsurface;
281         IDirect3DSurface9 *d3drt_backbuffercolorsurface;
282         void *d3dvertexbuffer;
283         void *d3dvertexdata;
284         size_t d3dvertexsize;
285 #endif
286 }
287 gl_state_t;
288
289 static gl_state_t gl_state;
290
291
292 /*
293 note: here's strip order for a terrain row:
294 0--1--2--3--4
295 |\ |\ |\ |\ |
296 | \| \| \| \|
297 A--B--C--D--E
298 clockwise
299
300 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
301
302 *elements++ = i + row;
303 *elements++ = i;
304 *elements++ = i + row + 1;
305 *elements++ = i;
306 *elements++ = i + 1;
307 *elements++ = i + row + 1;
308
309
310 for (y = 0;y < rows - 1;y++)
311 {
312         for (x = 0;x < columns - 1;x++)
313         {
314                 i = y * rows + x;
315                 *elements++ = i + columns;
316                 *elements++ = i;
317                 *elements++ = i + columns + 1;
318                 *elements++ = i;
319                 *elements++ = i + 1;
320                 *elements++ = i + columns + 1;
321         }
322 }
323
324 alternative:
325 0--1--2--3--4
326 | /| /|\ | /|
327 |/ |/ | \|/ |
328 A--B--C--D--E
329 counterclockwise
330
331 for (y = 0;y < rows - 1;y++)
332 {
333         for (x = 0;x < columns - 1;x++)
334         {
335                 i = y * rows + x;
336                 *elements++ = i;
337                 *elements++ = i + columns;
338                 *elements++ = i + columns + 1;
339                 *elements++ = i + columns;
340                 *elements++ = i + columns + 1;
341                 *elements++ = i + 1;
342         }
343 }
344 */
345
346 int polygonelement3i[(POLYGONELEMENTS_MAXPOINTS-2)*3];
347 unsigned short polygonelement3s[(POLYGONELEMENTS_MAXPOINTS-2)*3];
348 int quadelement3i[QUADELEMENTS_MAXQUADS*6];
349 unsigned short quadelement3s[QUADELEMENTS_MAXQUADS*6];
350
351 static void GL_VBOStats_f(void)
352 {
353         GL_Mesh_ListVBOs(true);
354 }
355
356 static void GL_Backend_ResetState(void);
357
358 static void R_Mesh_InitVertexDeclarations(void);
359 static void R_Mesh_DestroyVertexDeclarations(void);
360
361 static void R_Mesh_SetUseVBO(void)
362 {
363         switch(vid.renderpath)
364         {
365         case RENDERPATH_GL11:
366         case RENDERPATH_GL13:
367         case RENDERPATH_GL20:
368         case RENDERPATH_GLES1:
369                 gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
370                 gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && (gl_vbo.integer == 1 || gl_vbo.integer == 3)) || vid.forcevbo;
371                 gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer) || vid.forcevbo;
372                 gl_state.usevbo_dynamicindex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicindex.integer) || vid.forcevbo;
373                 break;
374         case RENDERPATH_D3D9:
375                 gl_state.usevbo_staticvertex = gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
376                 gl_state.usevbo_dynamicvertex = gl_state.usevbo_dynamicindex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer && gl_vbo_dynamicindex.integer) || vid.forcevbo;
377                 break;
378         case RENDERPATH_D3D10:
379                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
380                 break;
381         case RENDERPATH_D3D11:
382                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
383                 break;
384         case RENDERPATH_SOFT:
385                 gl_state.usevbo_staticvertex = false;
386                 gl_state.usevbo_staticindex = false;
387                 gl_state.usevbo_dynamicvertex = false;
388                 gl_state.usevbo_dynamicindex = false;
389                 break;
390         case RENDERPATH_GLES2:
391                 gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
392                 gl_state.usevbo_staticindex = false;
393                 gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer) || vid.forcevbo;
394                 gl_state.usevbo_dynamicindex = false;
395                 break;
396         }
397 }
398
399 static void gl_backend_start(void)
400 {
401         memset(&gl_state, 0, sizeof(gl_state));
402
403         R_Mesh_InitVertexDeclarations();
404
405         R_Mesh_SetUseVBO();
406         Mem_ExpandableArray_NewArray(&gl_state.meshbufferarray, r_main_mempool, sizeof(r_meshbuffer_t), 128);
407
408         Con_DPrintf("OpenGL backend started.\n");
409
410         CHECKGLERROR
411
412         GL_Backend_ResetState();
413
414         switch(vid.renderpath)
415         {
416         case RENDERPATH_GL11:
417         case RENDERPATH_GL13:
418         case RENDERPATH_GL20:
419         case RENDERPATH_GLES1:
420         case RENDERPATH_GLES2:
421                 // fetch current fbo here (default fbo is not 0 on some GLES devices)
422                 if (vid.support.ext_framebuffer_object)
423                         qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &gl_state.defaultframebufferobject);
424                 break;
425         case RENDERPATH_D3D9:
426 #ifdef SUPPORTD3D
427                 IDirect3DDevice9_GetDepthStencilSurface(vid_d3d9dev, &gl_state.d3drt_backbufferdepthsurface);
428                 IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &gl_state.d3drt_backbuffercolorsurface);
429 #endif
430                 break;
431         case RENDERPATH_D3D10:
432                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
433                 break;
434         case RENDERPATH_D3D11:
435                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
436                 break;
437         case RENDERPATH_SOFT:
438                 break;
439         }
440 }
441
442 static void gl_backend_shutdown(void)
443 {
444         Con_DPrint("OpenGL Backend shutting down\n");
445
446         switch(vid.renderpath)
447         {
448         case RENDERPATH_GL11:
449         case RENDERPATH_GL13:
450         case RENDERPATH_GL20:
451         case RENDERPATH_SOFT:
452         case RENDERPATH_GLES1:
453         case RENDERPATH_GLES2:
454                 break;
455         case RENDERPATH_D3D9:
456 #ifdef SUPPORTD3D
457                 IDirect3DSurface9_Release(gl_state.d3drt_backbufferdepthsurface);
458                 IDirect3DSurface9_Release(gl_state.d3drt_backbuffercolorsurface);
459 #endif
460                 break;
461         case RENDERPATH_D3D10:
462                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
463                 break;
464         case RENDERPATH_D3D11:
465                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
466                 break;
467         }
468
469         if (gl_state.preparevertices_tempdata)
470                 Mem_Free(gl_state.preparevertices_tempdata);
471
472         Mem_ExpandableArray_FreeArray(&gl_state.meshbufferarray);
473
474         R_Mesh_DestroyVertexDeclarations();
475
476         memset(&gl_state, 0, sizeof(gl_state));
477 }
478
479 static void gl_backend_newmap(void)
480 {
481 }
482
483 static void gl_backend_devicelost(void)
484 {
485         int i, endindex;
486         r_meshbuffer_t *buffer;
487 #ifdef SUPPORTD3D
488         gl_state.d3dvertexbuffer = NULL;
489 #endif
490         switch(vid.renderpath)
491         {
492         case RENDERPATH_GL11:
493         case RENDERPATH_GL13:
494         case RENDERPATH_GL20:
495         case RENDERPATH_SOFT:
496         case RENDERPATH_GLES1:
497         case RENDERPATH_GLES2:
498                 break;
499         case RENDERPATH_D3D9:
500 #ifdef SUPPORTD3D
501                 IDirect3DSurface9_Release(gl_state.d3drt_backbufferdepthsurface);
502                 IDirect3DSurface9_Release(gl_state.d3drt_backbuffercolorsurface);
503 #endif
504                 break;
505         case RENDERPATH_D3D10:
506                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
507                 break;
508         case RENDERPATH_D3D11:
509                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
510                 break;
511         }
512         endindex = Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
513         for (i = 0;i < endindex;i++)
514         {
515                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
516                 if (!buffer || !buffer->isdynamic)
517                         continue;
518                 switch(vid.renderpath)
519                 {
520                 case RENDERPATH_GL11:
521                 case RENDERPATH_GL13:
522                 case RENDERPATH_GL20:
523                 case RENDERPATH_SOFT:
524                 case RENDERPATH_GLES1:
525                 case RENDERPATH_GLES2:
526                         break;
527                 case RENDERPATH_D3D9:
528 #ifdef SUPPORTD3D
529                         if (buffer->devicebuffer)
530                         {
531                                 if (buffer->isindexbuffer)
532                                         IDirect3DIndexBuffer9_Release((IDirect3DIndexBuffer9*)buffer->devicebuffer);
533                                 else
534                                         IDirect3DVertexBuffer9_Release((IDirect3DVertexBuffer9*)buffer->devicebuffer);
535                                 buffer->devicebuffer = NULL;
536                         }
537 #endif
538                         break;
539                 case RENDERPATH_D3D10:
540                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
541                         break;
542                 case RENDERPATH_D3D11:
543                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
544                         break;
545                 }
546         }
547 }
548
549 static void gl_backend_devicerestored(void)
550 {
551         switch(vid.renderpath)
552         {
553         case RENDERPATH_GL11:
554         case RENDERPATH_GL13:
555         case RENDERPATH_GL20:
556         case RENDERPATH_SOFT:
557         case RENDERPATH_GLES1:
558         case RENDERPATH_GLES2:
559                 break;
560         case RENDERPATH_D3D9:
561 #ifdef SUPPORTD3D
562                 IDirect3DDevice9_GetDepthStencilSurface(vid_d3d9dev, &gl_state.d3drt_backbufferdepthsurface);
563                 IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &gl_state.d3drt_backbuffercolorsurface);
564 #endif
565                 break;
566         case RENDERPATH_D3D10:
567                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
568                 break;
569         case RENDERPATH_D3D11:
570                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
571                 break;
572         }
573 }
574
575 void gl_backend_init(void)
576 {
577         int i;
578
579         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
580         {
581                 polygonelement3s[i * 3 + 0] = 0;
582                 polygonelement3s[i * 3 + 1] = i + 1;
583                 polygonelement3s[i * 3 + 2] = i + 2;
584         }
585         // elements for rendering a series of quads as triangles
586         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
587         {
588                 quadelement3s[i * 6 + 0] = i * 4;
589                 quadelement3s[i * 6 + 1] = i * 4 + 1;
590                 quadelement3s[i * 6 + 2] = i * 4 + 2;
591                 quadelement3s[i * 6 + 3] = i * 4;
592                 quadelement3s[i * 6 + 4] = i * 4 + 2;
593                 quadelement3s[i * 6 + 5] = i * 4 + 3;
594         }
595
596         for (i = 0;i < (POLYGONELEMENTS_MAXPOINTS - 2)*3;i++)
597                 polygonelement3i[i] = polygonelement3s[i];
598         for (i = 0;i < QUADELEMENTS_MAXQUADS*6;i++)
599                 quadelement3i[i] = quadelement3s[i];
600
601         Cvar_RegisterVariable(&r_render);
602         Cvar_RegisterVariable(&r_renderview);
603         Cvar_RegisterVariable(&r_waterwarp);
604         Cvar_RegisterVariable(&gl_polyblend);
605         Cvar_RegisterVariable(&v_flipped);
606         Cvar_RegisterVariable(&gl_dither);
607         Cvar_RegisterVariable(&gl_vbo);
608         Cvar_RegisterVariable(&gl_vbo_dynamicvertex);
609         Cvar_RegisterVariable(&gl_vbo_dynamicindex);
610         Cvar_RegisterVariable(&gl_paranoid);
611         Cvar_RegisterVariable(&gl_printcheckerror);
612
613         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
614         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
615         Cvar_RegisterVariable(&gl_mesh_prefer_short_elements);
616
617         Cmd_AddCommand("gl_vbostats", GL_VBOStats_f, "prints a list of all buffer objects (vertex data and triangle elements) and total video memory used by them");
618
619         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, gl_backend_devicelost, gl_backend_devicerestored);
620 }
621
622 void GL_SetMirrorState(qboolean state);
623
624 void R_Viewport_TransformToScreen(const r_viewport_t *v, const vec4_t in, vec4_t out)
625 {
626         vec4_t temp;
627         float iw;
628         Matrix4x4_Transform4 (&v->viewmatrix, in, temp);
629         Matrix4x4_Transform4 (&v->projectmatrix, temp, out);
630         iw = 1.0f / out[3];
631         out[0] = v->x + (out[0] * iw + 1.0f) * v->width * 0.5f;
632
633         // for an odd reason, inverting this is wrong for R_Shadow_ScissorForBBox (we then get badly scissored lights)
634         //out[1] = v->y + v->height - (out[1] * iw + 1.0f) * v->height * 0.5f;
635         out[1] = v->y + (out[1] * iw + 1.0f) * v->height * 0.5f;
636
637         out[2] = v->z + (out[2] * iw + 1.0f) * v->depth * 0.5f;
638 }
639
640 void GL_Finish(void)
641 {
642         switch(vid.renderpath)
643         {
644         case RENDERPATH_GL11:
645         case RENDERPATH_GL13:
646         case RENDERPATH_GL20:
647         case RENDERPATH_GLES1:
648         case RENDERPATH_GLES2:
649                 qglFinish();
650                 break;
651         case RENDERPATH_D3D9:
652                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
653                 break;
654         case RENDERPATH_D3D10:
655                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
656                 break;
657         case RENDERPATH_D3D11:
658                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
659                 break;
660         case RENDERPATH_SOFT:
661                 DPSOFTRAST_Finish();
662                 break;
663         }
664 }
665
666 static int bboxedges[12][2] =
667 {
668         // top
669         {0, 1}, // +X
670         {0, 2}, // +Y
671         {1, 3}, // Y, +X
672         {2, 3}, // X, +Y
673         // bottom
674         {4, 5}, // +X
675         {4, 6}, // +Y
676         {5, 7}, // Y, +X
677         {6, 7}, // X, +Y
678         // verticals
679         {0, 4}, // +Z
680         {1, 5}, // X, +Z
681         {2, 6}, // Y, +Z
682         {3, 7}, // XY, +Z
683 };
684
685 qboolean R_ScissorForBBox(const float *mins, const float *maxs, int *scissor)
686 {
687         int i, ix1, iy1, ix2, iy2;
688         float x1, y1, x2, y2;
689         vec4_t v, v2;
690         float vertex[20][3];
691         int j, k;
692         vec4_t plane4f;
693         int numvertices;
694         float corner[8][4];
695         float dist[8];
696         int sign[8];
697         float f;
698
699         scissor[0] = r_refdef.view.viewport.x;
700         scissor[1] = r_refdef.view.viewport.y;
701         scissor[2] = r_refdef.view.viewport.width;
702         scissor[3] = r_refdef.view.viewport.height;
703
704         // if view is inside the box, just say yes it's visible
705         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
706                 return false;
707
708         // transform all corners that are infront of the nearclip plane
709         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
710         plane4f[3] = r_refdef.view.frustum[4].dist;
711         numvertices = 0;
712         for (i = 0;i < 8;i++)
713         {
714                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
715                 dist[i] = DotProduct4(corner[i], plane4f);
716                 sign[i] = dist[i] > 0;
717                 if (!sign[i])
718                 {
719                         VectorCopy(corner[i], vertex[numvertices]);
720                         numvertices++;
721                 }
722         }
723         // if some points are behind the nearclip, add clipped edge points to make
724         // sure that the scissor boundary is complete
725         if (numvertices > 0 && numvertices < 8)
726         {
727                 // add clipped edge points
728                 for (i = 0;i < 12;i++)
729                 {
730                         j = bboxedges[i][0];
731                         k = bboxedges[i][1];
732                         if (sign[j] != sign[k])
733                         {
734                                 f = dist[j] / (dist[j] - dist[k]);
735                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
736                                 numvertices++;
737                         }
738                 }
739         }
740
741         // if we have no points to check, it is behind the view plane
742         if (!numvertices)
743                 return true;
744
745         // if we have some points to transform, check what screen area is covered
746         x1 = y1 = x2 = y2 = 0;
747         v[3] = 1.0f;
748         //Con_Printf("%i vertices to transform...\n", numvertices);
749         for (i = 0;i < numvertices;i++)
750         {
751                 VectorCopy(vertex[i], v);
752                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
753                 //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
754                 if (i)
755                 {
756                         if (x1 > v2[0]) x1 = v2[0];
757                         if (x2 < v2[0]) x2 = v2[0];
758                         if (y1 > v2[1]) y1 = v2[1];
759                         if (y2 < v2[1]) y2 = v2[1];
760                 }
761                 else
762                 {
763                         x1 = x2 = v2[0];
764                         y1 = y2 = v2[1];
765                 }
766         }
767
768         // now convert the scissor rectangle to integer screen coordinates
769         ix1 = (int)(x1 - 1.0f);
770         //iy1 = vid.height - (int)(y2 - 1.0f);
771         //iy1 = r_refdef.view.viewport.width + 2 * r_refdef.view.viewport.x - (int)(y2 - 1.0f);
772         iy1 = (int)(y1 - 1.0f);
773         ix2 = (int)(x2 + 1.0f);
774         //iy2 = vid.height - (int)(y1 + 1.0f);
775         //iy2 = r_refdef.view.viewport.height + 2 * r_refdef.view.viewport.y - (int)(y1 + 1.0f);
776         iy2 = (int)(y2 + 1.0f);
777         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
778
779         // clamp it to the screen
780         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
781         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
782         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
783         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
784
785         // if it is inside out, it's not visible
786         if (ix2 <= ix1 || iy2 <= iy1)
787                 return true;
788
789         // the light area is visible, set up the scissor rectangle
790         scissor[0] = ix1;
791         scissor[1] = iy1;
792         scissor[2] = ix2 - ix1;
793         scissor[3] = iy2 - iy1;
794
795         // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
796         switch(vid.renderpath)
797         {
798         case RENDERPATH_D3D9:
799         case RENDERPATH_D3D10:
800         case RENDERPATH_D3D11:
801                 scissor[1] = vid.height - scissor[1] - scissor[3];
802                 break;
803         case RENDERPATH_GL11:
804         case RENDERPATH_GL13:
805         case RENDERPATH_GL20:
806         case RENDERPATH_SOFT:
807         case RENDERPATH_GLES1:
808         case RENDERPATH_GLES2:
809                 break;
810         }
811
812         return false;
813 }
814
815
816 static void R_Viewport_ApplyNearClipPlaneFloatGL(const r_viewport_t *v, float *m, float normalx, float normaly, float normalz, float dist)
817 {
818         float q[4];
819         float d;
820         float clipPlane[4], v3[3], v4[3];
821         float normal[3];
822
823         // This is inspired by Oblique Depth Projection from http://www.terathon.com/code/oblique.php
824
825         VectorSet(normal, normalx, normaly, normalz);
826         Matrix4x4_Transform3x3(&v->viewmatrix, normal, clipPlane);
827         VectorScale(normal, -dist, v3);
828         Matrix4x4_Transform(&v->viewmatrix, v3, v4);
829         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
830         clipPlane[3] = -DotProduct(v4, clipPlane);
831
832 #if 0
833 {
834         // testing code for comparing results
835         float clipPlane2[4];
836         VectorCopy4(clipPlane, clipPlane2);
837         R_EntityMatrix(&identitymatrix);
838         VectorSet(q, normal[0], normal[1], normal[2], -dist);
839         qglClipPlane(GL_CLIP_PLANE0, q);
840         qglGetClipPlane(GL_CLIP_PLANE0, q);
841         VectorCopy4(q, clipPlane);
842 }
843 #endif
844
845         // Calculate the clip-space corner point opposite the clipping plane
846         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
847         // transform it into camera space by multiplying it
848         // by the inverse of the projection matrix
849         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + m[8]) / m[0];
850         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + m[9]) / m[5];
851         q[2] = -1.0f;
852         q[3] = (1.0f + m[10]) / m[14];
853
854         // Calculate the scaled plane vector
855         d = 2.0f / DotProduct4(clipPlane, q);
856
857         // Replace the third row of the projection matrix
858         m[2] = clipPlane[0] * d;
859         m[6] = clipPlane[1] * d;
860         m[10] = clipPlane[2] * d + 1.0f;
861         m[14] = clipPlane[3] * d;
862 }
863
864 void R_Viewport_InitOrtho(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float x1, float y1, float x2, float y2, float nearclip, float farclip, const float *nearplane)
865 {
866         float left = x1, right = x2, bottom = y2, top = y1, zNear = nearclip, zFar = farclip;
867         float m[16];
868         memset(v, 0, sizeof(*v));
869         v->type = R_VIEWPORTTYPE_ORTHO;
870         v->cameramatrix = *cameramatrix;
871         v->x = x;
872         v->y = y;
873         v->z = 0;
874         v->width = width;
875         v->height = height;
876         v->depth = 1;
877         memset(m, 0, sizeof(m));
878         m[0]  = 2/(right - left);
879         m[5]  = 2/(top - bottom);
880         m[10] = -2/(zFar - zNear);
881         m[12] = - (right + left)/(right - left);
882         m[13] = - (top + bottom)/(top - bottom);
883         m[14] = - (zFar + zNear)/(zFar - zNear);
884         m[15] = 1;
885         switch(vid.renderpath)
886         {
887         case RENDERPATH_GL11:
888         case RENDERPATH_GL13:
889         case RENDERPATH_GL20:
890         case RENDERPATH_SOFT:
891         case RENDERPATH_GLES1:
892         case RENDERPATH_GLES2:
893                 break;
894         case RENDERPATH_D3D9:
895         case RENDERPATH_D3D10:
896         case RENDERPATH_D3D11:
897                 m[10] = -1/(zFar - zNear);
898                 m[14] = -zNear/(zFar-zNear);
899                 break;
900         }
901         v->screentodepth[0] = -farclip / (farclip - nearclip);
902         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
903
904         Matrix4x4_Invert_Full(&v->viewmatrix, &v->cameramatrix);
905
906         if (nearplane)
907                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
908
909         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
910
911 #if 0
912         {
913                 vec4_t test1;
914                 vec4_t test2;
915                 Vector4Set(test1, (x1+x2)*0.5f, (y1+y2)*0.5f, 0.0f, 1.0f);
916                 R_Viewport_TransformToScreen(v, test1, test2);
917                 Con_Printf("%f %f %f -> %f %f %f\n", test1[0], test1[1], test1[2], test2[0], test2[1], test2[2]);
918         }
919 #endif
920 }
921
922 void R_Viewport_InitPerspective(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float frustumx, float frustumy, float nearclip, float farclip, const float *nearplane)
923 {
924         matrix4x4_t tempmatrix, basematrix;
925         float m[16];
926         memset(v, 0, sizeof(*v));
927
928         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
929         v->cameramatrix = *cameramatrix;
930         v->x = x;
931         v->y = y;
932         v->z = 0;
933         v->width = width;
934         v->height = height;
935         v->depth = 1;
936         memset(m, 0, sizeof(m));
937         m[0]  = 1.0 / frustumx;
938         m[5]  = 1.0 / frustumy;
939         m[10] = -(farclip + nearclip) / (farclip - nearclip);
940         m[11] = -1;
941         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
942         v->screentodepth[0] = -farclip / (farclip - nearclip);
943         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
944
945         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
946         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
947         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
948         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
949
950         if (nearplane)
951                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
952
953         if(v_flipped.integer)
954         {
955                 m[0] = -m[0];
956                 m[4] = -m[4];
957                 m[8] = -m[8];
958                 m[12] = -m[12];
959         }
960
961         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
962 }
963
964 void R_Viewport_InitPerspectiveInfinite(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float frustumx, float frustumy, float nearclip, const float *nearplane)
965 {
966         matrix4x4_t tempmatrix, basematrix;
967         const float nudge = 1.0 - 1.0 / (1<<23);
968         float m[16];
969         memset(v, 0, sizeof(*v));
970
971         v->type = R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP;
972         v->cameramatrix = *cameramatrix;
973         v->x = x;
974         v->y = y;
975         v->z = 0;
976         v->width = width;
977         v->height = height;
978         v->depth = 1;
979         memset(m, 0, sizeof(m));
980         m[ 0] = 1.0 / frustumx;
981         m[ 5] = 1.0 / frustumy;
982         m[10] = -nudge;
983         m[11] = -1;
984         m[14] = -2 * nearclip * nudge;
985         v->screentodepth[0] = (m[10] + 1) * 0.5 - 1;
986         v->screentodepth[1] = m[14] * -0.5;
987
988         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
989         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
990         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
991         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
992
993         if (nearplane)
994                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
995
996         if(v_flipped.integer)
997         {
998                 m[0] = -m[0];
999                 m[4] = -m[4];
1000                 m[8] = -m[8];
1001                 m[12] = -m[12];
1002         }
1003
1004         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1005 }
1006
1007 float cubeviewmatrix[6][16] =
1008 {
1009     // standard cubemap projections
1010     { // +X
1011          0, 0,-1, 0,
1012          0,-1, 0, 0,
1013         -1, 0, 0, 0,
1014          0, 0, 0, 1,
1015     },
1016     { // -X
1017          0, 0, 1, 0,
1018          0,-1, 0, 0,
1019          1, 0, 0, 0,
1020          0, 0, 0, 1,
1021     },
1022     { // +Y
1023          1, 0, 0, 0,
1024          0, 0,-1, 0,
1025          0, 1, 0, 0,
1026          0, 0, 0, 1,
1027     },
1028     { // -Y
1029          1, 0, 0, 0,
1030          0, 0, 1, 0,
1031          0,-1, 0, 0,
1032          0, 0, 0, 1,
1033     },
1034     { // +Z
1035          1, 0, 0, 0,
1036          0,-1, 0, 0,
1037          0, 0,-1, 0,
1038          0, 0, 0, 1,
1039     },
1040     { // -Z
1041         -1, 0, 0, 0,
1042          0,-1, 0, 0,
1043          0, 0, 1, 0,
1044          0, 0, 0, 1,
1045     },
1046 };
1047 float rectviewmatrix[6][16] =
1048 {
1049     // sign-preserving cubemap projections
1050     { // +X
1051          0, 0,-1, 0,
1052          0, 1, 0, 0,
1053          1, 0, 0, 0,
1054          0, 0, 0, 1,
1055     },
1056     { // -X
1057          0, 0, 1, 0,
1058          0, 1, 0, 0,
1059          1, 0, 0, 0,
1060          0, 0, 0, 1,
1061     },
1062     { // +Y
1063          1, 0, 0, 0,
1064          0, 0,-1, 0,
1065          0, 1, 0, 0,
1066          0, 0, 0, 1,
1067     },
1068     { // -Y
1069          1, 0, 0, 0,
1070          0, 0, 1, 0,
1071          0, 1, 0, 0,
1072          0, 0, 0, 1,
1073     },
1074     { // +Z
1075          1, 0, 0, 0,
1076          0, 1, 0, 0,
1077          0, 0,-1, 0,
1078          0, 0, 0, 1,
1079     },
1080     { // -Z
1081          1, 0, 0, 0,
1082          0, 1, 0, 0,
1083          0, 0, 1, 0,
1084          0, 0, 0, 1,
1085     },
1086 };
1087
1088 void R_Viewport_InitCubeSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, float nearclip, float farclip, const float *nearplane)
1089 {
1090         matrix4x4_t tempmatrix, basematrix;
1091         float m[16];
1092         memset(v, 0, sizeof(*v));
1093         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
1094         v->cameramatrix = *cameramatrix;
1095         v->width = size;
1096         v->height = size;
1097         v->depth = 1;
1098         memset(m, 0, sizeof(m));
1099         m[0] = m[5] = 1.0f;
1100         m[10] = -(farclip + nearclip) / (farclip - nearclip);
1101         m[11] = -1;
1102         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
1103
1104         Matrix4x4_FromArrayFloatGL(&basematrix, cubeviewmatrix[side]);
1105         Matrix4x4_Invert_Simple(&tempmatrix, &v->cameramatrix);
1106         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
1107
1108         if (nearplane)
1109                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
1110
1111         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1112 }
1113
1114 void R_Viewport_InitRectSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, int border, float nearclip, float farclip, const float *nearplane)
1115 {
1116         matrix4x4_t tempmatrix, basematrix;
1117         float m[16];
1118         memset(v, 0, sizeof(*v));
1119         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
1120         v->cameramatrix = *cameramatrix;
1121         v->x = (side & 1) * size;
1122         v->y = (side >> 1) * size;
1123         v->width = size;
1124         v->height = size;
1125         v->depth = 1;
1126         memset(m, 0, sizeof(m));
1127         m[0] = m[5] = 1.0f * ((float)size - border) / size;
1128         m[10] = -(farclip + nearclip) / (farclip - nearclip);
1129         m[11] = -1;
1130         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
1131
1132         Matrix4x4_FromArrayFloatGL(&basematrix, rectviewmatrix[side]);
1133         Matrix4x4_Invert_Simple(&tempmatrix, &v->cameramatrix);
1134         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
1135
1136         switch(vid.renderpath)
1137         {
1138         case RENDERPATH_GL20:
1139         case RENDERPATH_GL13:
1140         case RENDERPATH_GL11:
1141         case RENDERPATH_SOFT:
1142         case RENDERPATH_GLES1:
1143         case RENDERPATH_GLES2:
1144                 break;
1145         case RENDERPATH_D3D9:
1146                 m[5] *= -1;
1147                 break;
1148         case RENDERPATH_D3D10:
1149                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1150                 break;
1151         case RENDERPATH_D3D11:
1152                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1153                 break;
1154         }
1155
1156         if (nearplane)
1157                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
1158
1159         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1160 }
1161
1162 void R_SetViewport(const r_viewport_t *v)
1163 {
1164         float m[16];
1165         gl_viewport = *v;
1166
1167         // FIXME: v_flipped_state is evil, this probably breaks somewhere
1168         GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
1169
1170         // copy over the matrices to our state
1171         gl_viewmatrix = v->viewmatrix;
1172         gl_projectionmatrix = v->projectmatrix;
1173
1174         switch(vid.renderpath)
1175         {
1176         case RENDERPATH_GL13:
1177         case RENDERPATH_GL11:
1178         case RENDERPATH_GLES1:
1179 #ifdef GL_PROJECTION
1180                 CHECKGLERROR
1181                 qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
1182                 // Load the projection matrix into OpenGL
1183                 qglMatrixMode(GL_PROJECTION);CHECKGLERROR
1184                 Matrix4x4_ToArrayFloatGL(&gl_projectionmatrix, m);
1185                 qglLoadMatrixf(m);CHECKGLERROR
1186                 qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1187 #endif
1188                 break;
1189         case RENDERPATH_D3D9:
1190 #ifdef SUPPORTD3D
1191                 {
1192                         D3DVIEWPORT9 d3dviewport;
1193                         d3dviewport.X = gl_viewport.x;
1194                         d3dviewport.Y = gl_viewport.y;
1195                         d3dviewport.Width = gl_viewport.width;
1196                         d3dviewport.Height = gl_viewport.height;
1197                         d3dviewport.MinZ = gl_state.depthrange[0];
1198                         d3dviewport.MaxZ = gl_state.depthrange[1];
1199                         IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
1200                 }
1201 #endif
1202                 break;
1203         case RENDERPATH_D3D10:
1204                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1205                 break;
1206         case RENDERPATH_D3D11:
1207                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1208                 break;
1209         case RENDERPATH_SOFT:
1210                 DPSOFTRAST_Viewport(v->x, v->y, v->width, v->height);
1211                 break;
1212         case RENDERPATH_GL20:
1213         case RENDERPATH_GLES2:
1214                 CHECKGLERROR
1215                 qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
1216                 break;
1217         }
1218
1219         // force an update of the derived matrices
1220         gl_modelmatrixchanged = true;
1221         R_EntityMatrix(&gl_modelmatrix);
1222 }
1223
1224 void R_GetViewport(r_viewport_t *v)
1225 {
1226         *v = gl_viewport;
1227 }
1228
1229 static void GL_BindVBO(int bufferobject)
1230 {
1231         if (gl_state.vertexbufferobject != bufferobject)
1232         {
1233                 gl_state.vertexbufferobject = bufferobject;
1234                 CHECKGLERROR
1235                 qglBindBufferARB(GL_ARRAY_BUFFER, bufferobject);CHECKGLERROR
1236         }
1237 }
1238
1239 static void GL_BindEBO(int bufferobject)
1240 {
1241         if (gl_state.elementbufferobject != bufferobject)
1242         {
1243                 gl_state.elementbufferobject = bufferobject;
1244                 CHECKGLERROR
1245                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, bufferobject);CHECKGLERROR
1246         }
1247 }
1248
1249 static void GL_BindUBO(int bufferobject)
1250 {
1251         if (gl_state.uniformbufferobject != bufferobject)
1252         {
1253                 gl_state.uniformbufferobject = bufferobject;
1254                 CHECKGLERROR
1255                 qglBindBufferARB(GL_UNIFORM_BUFFER, bufferobject);CHECKGLERROR
1256         }
1257 }
1258
1259 static const GLuint drawbuffers[4] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
1260 int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1261 {
1262         switch(vid.renderpath)
1263         {
1264         case RENDERPATH_GL11:
1265         case RENDERPATH_GL13:
1266         case RENDERPATH_GL20:
1267         case RENDERPATH_GLES1:
1268         case RENDERPATH_GLES2:
1269                 if (vid.support.arb_framebuffer_object)
1270                 {
1271                         int temp;
1272                         GLuint status;
1273                         qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1274                         R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1275                         // GL_ARB_framebuffer_object (GL3-class hardware) - depth stencil attachment
1276 #ifdef USE_GLES2
1277                         // FIXME: separate stencil attachment on GLES
1278                         if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1279 #else
1280                         if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, depthtexture->glisdepthstencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1281 #endif
1282                         if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, depthtexture->glisdepthstencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1283                         if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1284                         if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1285                         if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1286                         if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1287                         if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1288                         if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1289                         if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1290                         if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1291
1292 #ifndef USE_GLES2
1293                         if (colortexture4 && qglDrawBuffersARB)
1294                         {
1295                                 qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1296                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1297                         }
1298                         else if (colortexture3 && qglDrawBuffersARB)
1299                         {
1300                                 qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1301                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1302                         }
1303                         else if (colortexture2 && qglDrawBuffersARB)
1304                         {
1305                                 qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1306                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1307                         }
1308                         else if (colortexture && qglDrawBuffer)
1309                         {
1310                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1311                                 qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1312                         }
1313                         else if (qglDrawBuffer)
1314                         {
1315                                 qglDrawBuffer(GL_NONE);CHECKGLERROR
1316                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1317                         }
1318 #endif
1319                         status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1320                         if (status != GL_FRAMEBUFFER_COMPLETE)
1321                         {
1322                                 Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1323                                 gl_state.framebufferobject = 0; // GL unbinds it for us
1324                                 qglDeleteFramebuffers(1, (GLuint*)&temp);
1325                                 temp = 0;
1326                         }
1327                         return temp;
1328                 }
1329                 else if (vid.support.ext_framebuffer_object)
1330                 {
1331                         int temp;
1332                         GLuint status;
1333                         qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1334                         R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1335                         // GL_EXT_framebuffer_object (GL2-class hardware) - no depth stencil attachment, let it break stencil
1336                         if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1337                         if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1338                         if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1339                         if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1340                         if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1341                         if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1342                         if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1343                         if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1344                         if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1345                         if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1346
1347 #ifndef USE_GLES2
1348                         if (colortexture4 && qglDrawBuffersARB)
1349                         {
1350                                 qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1351                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1352                         }
1353                         else if (colortexture3 && qglDrawBuffersARB)
1354                         {
1355                                 qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1356                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1357                         }
1358                         else if (colortexture2 && qglDrawBuffersARB)
1359                         {
1360                                 qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1361                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1362                         }
1363                         else if (colortexture && qglDrawBuffer)
1364                         {
1365                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1366                                 qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1367                         }
1368                         else if (qglDrawBuffer)
1369                         {
1370                                 qglDrawBuffer(GL_NONE);CHECKGLERROR
1371                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1372                         }
1373 #endif
1374                         status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1375                         if (status != GL_FRAMEBUFFER_COMPLETE)
1376                         {
1377                                 Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1378                                 gl_state.framebufferobject = 0; // GL unbinds it for us
1379                                 qglDeleteFramebuffers(1, (GLuint*)&temp);
1380                                 temp = 0;
1381                         }
1382                         return temp;
1383                 }
1384                 return 0;
1385         case RENDERPATH_D3D9:
1386         case RENDERPATH_D3D10:
1387         case RENDERPATH_D3D11:
1388                 return 1;
1389         case RENDERPATH_SOFT:
1390                 return 1;
1391         }
1392         return 0;
1393 }
1394
1395 void R_Mesh_DestroyFramebufferObject(int fbo)
1396 {
1397         switch(vid.renderpath)
1398         {
1399         case RENDERPATH_GL11:
1400         case RENDERPATH_GL13:
1401         case RENDERPATH_GL20:
1402         case RENDERPATH_GLES1:
1403         case RENDERPATH_GLES2:
1404                 if (fbo)
1405                 {
1406                         // GL clears the binding if we delete something bound
1407                         if (gl_state.framebufferobject == fbo)
1408                                 gl_state.framebufferobject = 0;
1409                         qglDeleteFramebuffers(1, (GLuint*)&fbo);
1410                 }
1411                 break;
1412         case RENDERPATH_D3D9:
1413         case RENDERPATH_D3D10:
1414         case RENDERPATH_D3D11:
1415                 break;
1416         case RENDERPATH_SOFT:
1417                 break;
1418         }
1419 }
1420
1421 #ifdef SUPPORTD3D
1422 void R_Mesh_SetRenderTargetsD3D9(IDirect3DSurface9 *depthsurface, IDirect3DSurface9 *colorsurface0, IDirect3DSurface9 *colorsurface1, IDirect3DSurface9 *colorsurface2, IDirect3DSurface9 *colorsurface3)
1423 {
1424         gl_state.framebufferobject = depthsurface != gl_state.d3drt_backbufferdepthsurface || colorsurface0 != gl_state.d3drt_backbuffercolorsurface;
1425         if (gl_state.d3drt_depthsurface != depthsurface)
1426         {
1427                 gl_state.d3drt_depthsurface = depthsurface;
1428                 IDirect3DDevice9_SetDepthStencilSurface(vid_d3d9dev, gl_state.d3drt_depthsurface);
1429         }
1430         if (gl_state.d3drt_colorsurfaces[0] != colorsurface0)
1431         {
1432                 gl_state.d3drt_colorsurfaces[0] = colorsurface0;
1433                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 0, gl_state.d3drt_colorsurfaces[0]);
1434         }
1435         if (gl_state.d3drt_colorsurfaces[1] != colorsurface1)
1436         {
1437                 gl_state.d3drt_colorsurfaces[1] = colorsurface1;
1438                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 1, gl_state.d3drt_colorsurfaces[1]);
1439         }
1440         if (gl_state.d3drt_colorsurfaces[2] != colorsurface2)
1441         {
1442                 gl_state.d3drt_colorsurfaces[2] = colorsurface2;
1443                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 2, gl_state.d3drt_colorsurfaces[2]);
1444         }
1445         if (gl_state.d3drt_colorsurfaces[3] != colorsurface3)
1446         {
1447                 gl_state.d3drt_colorsurfaces[3] = colorsurface3;
1448                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 3, gl_state.d3drt_colorsurfaces[3]);
1449         }
1450 }
1451 #endif
1452
1453 void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1454 {
1455         unsigned int i;
1456         unsigned int j;
1457         rtexture_t *textures[5];
1458         Vector4Set(textures, colortexture, colortexture2, colortexture3, colortexture4);
1459         textures[4] = depthtexture;
1460         // unbind any matching textures immediately, otherwise D3D will complain about a bound texture being used as a render target
1461         for (j = 0;j < 5;j++)
1462                 if (textures[j])
1463                         for (i = 0;i < vid.teximageunits;i++)
1464                                 if (gl_state.units[i].texture == textures[j])
1465                                         R_Mesh_TexBind(i, NULL);
1466         // set up framebuffer object or render targets for the active rendering API
1467         switch(vid.renderpath)
1468         {
1469         case RENDERPATH_GL11:
1470         case RENDERPATH_GL13:
1471         case RENDERPATH_GL20:
1472         case RENDERPATH_GLES1:
1473         case RENDERPATH_GLES2:
1474                 if (gl_state.framebufferobject != fbo)
1475                 {
1476                         gl_state.framebufferobject = fbo;
1477                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject ? gl_state.framebufferobject : gl_state.defaultframebufferobject);
1478                 }
1479                 break;
1480         case RENDERPATH_D3D9:
1481 #ifdef SUPPORTD3D
1482                 // set up the new render targets, a NULL depthtexture intentionally binds nothing
1483                 // TODO: optimize: keep surface pointer around in rtexture_t until texture is freed or lost
1484                 if (fbo)
1485                 {
1486                         IDirect3DSurface9 *surfaces[5];
1487                         for (i = 0;i < 5;i++)
1488                         {
1489                                 surfaces[i] = NULL;
1490                                 if (textures[i])
1491                                 {
1492                                         if (textures[i]->d3dsurface)
1493                                                 surfaces[i] = (IDirect3DSurface9 *)textures[i]->d3dsurface;
1494                                         else
1495                                                 IDirect3DTexture9_GetSurfaceLevel((IDirect3DTexture9 *)textures[i]->d3dtexture, 0, &surfaces[i]);
1496                                 }
1497                         }
1498                         // set the render targets for real
1499                         R_Mesh_SetRenderTargetsD3D9(surfaces[4], surfaces[0], surfaces[1], surfaces[2], surfaces[3]);
1500                         // release the texture surface levels (they won't be lost while bound...)
1501                         for (i = 0;i < 5;i++)
1502                                 if (textures[i] && !textures[i]->d3dsurface)
1503                                         IDirect3DSurface9_Release(surfaces[i]);
1504                 }
1505                 else
1506                         R_Mesh_SetRenderTargetsD3D9(gl_state.d3drt_backbufferdepthsurface, gl_state.d3drt_backbuffercolorsurface, NULL, NULL, NULL);
1507 #endif
1508                 break;
1509         case RENDERPATH_D3D10:
1510                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1511                 break;
1512         case RENDERPATH_D3D11:
1513                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1514                 break;
1515         case RENDERPATH_SOFT:
1516                 if (fbo)
1517                 {
1518                         int width, height;
1519                         unsigned int *pointers[5];
1520                         memset(pointers, 0, sizeof(pointers));
1521                         for (i = 0;i < 5;i++)
1522                                 pointers[i] = textures[i] ? (unsigned int *)DPSOFTRAST_Texture_GetPixelPointer(textures[i]->texnum, 0) : NULL;
1523                         width = DPSOFTRAST_Texture_GetWidth(textures[0] ? textures[0]->texnum : textures[4]->texnum, 0);
1524                         height = DPSOFTRAST_Texture_GetHeight(textures[0] ? textures[0]->texnum : textures[4]->texnum, 0);
1525                         DPSOFTRAST_SetRenderTargets(width, height, pointers[4], pointers[0], pointers[1], pointers[2], pointers[3]);
1526                 }
1527                 else
1528                         DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
1529                 break;
1530         }
1531 }
1532
1533 #ifdef SUPPORTD3D
1534 static int d3dcmpforglfunc(int f)
1535 {
1536         switch(f)
1537         {
1538         case GL_NEVER: return D3DCMP_NEVER;
1539         case GL_LESS: return D3DCMP_LESS;
1540         case GL_EQUAL: return D3DCMP_EQUAL;
1541         case GL_LEQUAL: return D3DCMP_LESSEQUAL;
1542         case GL_GREATER: return D3DCMP_GREATER;
1543         case GL_NOTEQUAL: return D3DCMP_NOTEQUAL;
1544         case GL_GEQUAL: return D3DCMP_GREATEREQUAL;
1545         case GL_ALWAYS: return D3DCMP_ALWAYS;
1546         default: Con_DPrintf("Unknown GL_DepthFunc\n");return D3DCMP_ALWAYS;
1547         }
1548 }
1549
1550 static int d3dstencilopforglfunc(int f)
1551 {
1552         switch(f)
1553         {
1554         case GL_KEEP: return D3DSTENCILOP_KEEP;
1555         case GL_INCR: return D3DSTENCILOP_INCR; // note: GL_INCR is clamped, D3DSTENCILOP_INCR wraps
1556         case GL_DECR: return D3DSTENCILOP_DECR; // note: GL_DECR is clamped, D3DSTENCILOP_DECR wraps
1557         default: Con_DPrintf("Unknown GL_StencilFunc\n");return D3DSTENCILOP_KEEP;
1558         }
1559 }
1560 #endif
1561
1562 static void GL_Backend_ResetState(void)
1563 {
1564         unsigned int i;
1565         gl_state.active = true;
1566         gl_state.depthtest = true;
1567         gl_state.alphatest = false;
1568         gl_state.alphafunc = GL_GEQUAL;
1569         gl_state.alphafuncvalue = 0.5f;
1570         gl_state.alphatocoverage = false;
1571         gl_state.blendfunc1 = GL_ONE;
1572         gl_state.blendfunc2 = GL_ZERO;
1573         gl_state.blend = false;
1574         gl_state.depthmask = GL_TRUE;
1575         gl_state.colormask = 15;
1576         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
1577         gl_state.lockrange_first = 0;
1578         gl_state.lockrange_count = 0;
1579         gl_state.cullface = GL_FRONT;
1580         gl_state.cullfaceenable = false;
1581         gl_state.polygonoffset[0] = 0;
1582         gl_state.polygonoffset[1] = 0;
1583         gl_state.framebufferobject = 0;
1584         gl_state.depthfunc = GL_LEQUAL;
1585
1586         switch(vid.renderpath)
1587         {
1588         case RENDERPATH_D3D9:
1589 #ifdef SUPPORTD3D
1590                 {
1591                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, gl_state.colormask);
1592                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
1593                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
1594                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
1595                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
1596                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
1597                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
1598                 }
1599 #endif
1600                 break;
1601         case RENDERPATH_D3D10:
1602                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1603                 break;
1604         case RENDERPATH_D3D11:
1605                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1606                 break;
1607         case RENDERPATH_GL11:
1608         case RENDERPATH_GL13:
1609         case RENDERPATH_GLES1:
1610 #ifdef GL_ALPHA_TEST
1611                 CHECKGLERROR
1612
1613                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1614                 qglAlphaFunc(gl_state.alphafunc, gl_state.alphafuncvalue);CHECKGLERROR
1615                 qglDisable(GL_ALPHA_TEST);CHECKGLERROR
1616                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1617                 qglDisable(GL_BLEND);CHECKGLERROR
1618                 qglCullFace(gl_state.cullface);CHECKGLERROR
1619                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1620                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1621                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1622                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1623                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1624
1625                 if (vid.support.arb_vertex_buffer_object)
1626                 {
1627                         qglBindBufferARB(GL_ARRAY_BUFFER, 0);
1628                         qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0);
1629                 }
1630
1631                 if (vid.support.ext_framebuffer_object)
1632                 {
1633                         //qglBindRenderbuffer(GL_RENDERBUFFER, 0);
1634                         qglBindFramebuffer(GL_FRAMEBUFFER, 0);
1635                 }
1636
1637                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
1638                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1639
1640                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
1641                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1642                 qglColor4f(1, 1, 1, 1);CHECKGLERROR
1643
1644                 if (vid.support.ext_framebuffer_object)
1645                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject);
1646
1647                 gl_state.unit = MAX_TEXTUREUNITS;
1648                 gl_state.clientunit = MAX_TEXTUREUNITS;
1649                 for (i = 0;i < vid.texunits;i++)
1650                 {
1651                         GL_ActiveTexture(i);
1652                         GL_ClientActiveTexture(i);
1653                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1654                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1655                         if (vid.support.ext_texture_3d)
1656                         {
1657                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1658                                 qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1659                         }
1660                         if (vid.support.arb_texture_cube_map)
1661                         {
1662                                 qglDisable(GL_TEXTURE_CUBE_MAP);CHECKGLERROR
1663                                 qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1664                         }
1665                         GL_BindVBO(0);
1666                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
1667                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1668                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
1669                         qglLoadIdentity();CHECKGLERROR
1670                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1671                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1672                 }
1673                 CHECKGLERROR
1674 #endif
1675                 break;
1676         case RENDERPATH_SOFT:
1677                 DPSOFTRAST_ColorMask(1,1,1,1);
1678                 DPSOFTRAST_BlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);
1679                 DPSOFTRAST_CullFace(gl_state.cullface);
1680                 DPSOFTRAST_DepthFunc(gl_state.depthfunc);
1681                 DPSOFTRAST_DepthMask(gl_state.depthmask);
1682                 DPSOFTRAST_PolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1683                 DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
1684                 DPSOFTRAST_Viewport(0, 0, vid.width, vid.height);
1685                 break;
1686         case RENDERPATH_GL20:
1687         case RENDERPATH_GLES2:
1688                 CHECKGLERROR
1689                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1690                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1691                 qglDisable(GL_BLEND);CHECKGLERROR
1692                 qglCullFace(gl_state.cullface);CHECKGLERROR
1693                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1694                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1695                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1696                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1697                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1698                 if (vid.support.arb_vertex_buffer_object)
1699                 {
1700                         qglBindBufferARB(GL_ARRAY_BUFFER, 0);
1701                         qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0);
1702                 }
1703                 if (vid.support.ext_framebuffer_object)
1704                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.defaultframebufferobject);
1705                 qglEnableVertexAttribArray(GLSLATTRIB_POSITION);
1706                 qglVertexAttribPointer(GLSLATTRIB_POSITION, 3, GL_FLOAT, false, sizeof(float[3]), NULL);CHECKGLERROR
1707                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);
1708                 qglVertexAttribPointer(GLSLATTRIB_COLOR, 4, GL_FLOAT, false, sizeof(float[4]), NULL);CHECKGLERROR
1709                 qglVertexAttrib4f(GLSLATTRIB_COLOR, 1, 1, 1, 1);
1710                 gl_state.unit = MAX_TEXTUREUNITS;
1711                 gl_state.clientunit = MAX_TEXTUREUNITS;
1712                 for (i = 0;i < vid.teximageunits;i++)
1713                 {
1714                         GL_ActiveTexture(i);
1715                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1716                         if (vid.support.ext_texture_3d)
1717                         {
1718                                 qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1719                         }
1720                         if (vid.support.arb_texture_cube_map)
1721                         {
1722                                 qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1723                         }
1724                 }
1725                 for (i = 0;i < vid.texarrayunits;i++)
1726                 {
1727                         GL_BindVBO(0);
1728                         qglVertexAttribPointer(i+GLSLATTRIB_TEXCOORD0, 2, GL_FLOAT, false, sizeof(float[2]), NULL);CHECKGLERROR
1729                         qglDisableVertexAttribArray(i+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
1730                 }
1731                 CHECKGLERROR
1732                 break;
1733         }
1734 }
1735
1736 void GL_ActiveTexture(unsigned int num)
1737 {
1738         if (gl_state.unit != num)
1739         {
1740                 gl_state.unit = num;
1741                 switch(vid.renderpath)
1742                 {
1743                 case RENDERPATH_GL11:
1744                 case RENDERPATH_GL13:
1745                 case RENDERPATH_GL20:
1746                 case RENDERPATH_GLES1:
1747                 case RENDERPATH_GLES2:
1748                         if (qglActiveTexture)
1749                         {
1750                                 CHECKGLERROR
1751                                 qglActiveTexture(GL_TEXTURE0 + gl_state.unit);
1752                                 CHECKGLERROR
1753                         }
1754                         break;
1755                 case RENDERPATH_D3D9:
1756                 case RENDERPATH_D3D10:
1757                 case RENDERPATH_D3D11:
1758                         break;
1759                 case RENDERPATH_SOFT:
1760                         break;
1761                 }
1762         }
1763 }
1764
1765 void GL_ClientActiveTexture(unsigned int num)
1766 {
1767         if (gl_state.clientunit != num)
1768         {
1769                 gl_state.clientunit = num;
1770                 switch(vid.renderpath)
1771                 {
1772                 case RENDERPATH_GL11:
1773                 case RENDERPATH_GL13:
1774                 case RENDERPATH_GLES1:
1775                         if (qglActiveTexture)
1776                         {
1777                                 CHECKGLERROR
1778                                 qglClientActiveTexture(GL_TEXTURE0 + gl_state.clientunit);
1779                                 CHECKGLERROR
1780                         }
1781                         break;
1782                 case RENDERPATH_D3D9:
1783                 case RENDERPATH_D3D10:
1784                 case RENDERPATH_D3D11:
1785                         break;
1786                 case RENDERPATH_SOFT:
1787                         break;
1788                 case RENDERPATH_GL20:
1789                 case RENDERPATH_GLES2:
1790                         break;
1791                 }
1792         }
1793 }
1794
1795 void GL_BlendFunc(int blendfunc1, int blendfunc2)
1796 {
1797         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
1798         {
1799                 qboolean blendenable;
1800                 gl_state.blendfunc1 = blendfunc1;
1801                 gl_state.blendfunc2 = blendfunc2;
1802                 blendenable = (gl_state.blendfunc1 != GL_ONE || gl_state.blendfunc2 != GL_ZERO);
1803                 switch(vid.renderpath)
1804                 {
1805                 case RENDERPATH_GL11:
1806                 case RENDERPATH_GL13:
1807                 case RENDERPATH_GL20:
1808                 case RENDERPATH_GLES1:
1809                 case RENDERPATH_GLES2:
1810                         CHECKGLERROR
1811                         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1812                         if (gl_state.blend != blendenable)
1813                         {
1814                                 gl_state.blend = blendenable;
1815                                 if (!gl_state.blend)
1816                                 {
1817                                         qglDisable(GL_BLEND);CHECKGLERROR
1818                                 }
1819                                 else
1820                                 {
1821                                         qglEnable(GL_BLEND);CHECKGLERROR
1822                                 }
1823                         }
1824                         break;
1825                 case RENDERPATH_D3D9:
1826 #ifdef SUPPORTD3D
1827                         {
1828                                 int i;
1829                                 int glblendfunc[2];
1830                                 D3DBLEND d3dblendfunc[2];
1831                                 glblendfunc[0] = gl_state.blendfunc1;
1832                                 glblendfunc[1] = gl_state.blendfunc2;
1833                                 for (i = 0;i < 2;i++)
1834                                 {
1835                                         switch(glblendfunc[i])
1836                                         {
1837                                         case GL_ZERO: d3dblendfunc[i] = D3DBLEND_ZERO;break;
1838                                         case GL_ONE: d3dblendfunc[i] = D3DBLEND_ONE;break;
1839                                         case GL_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_SRCCOLOR;break;
1840                                         case GL_ONE_MINUS_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_INVSRCCOLOR;break;
1841                                         case GL_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_SRCALPHA;break;
1842                                         case GL_ONE_MINUS_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_INVSRCALPHA;break;
1843                                         case GL_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_DESTALPHA;break;
1844                                         case GL_ONE_MINUS_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_INVDESTALPHA;break;
1845                                         case GL_DST_COLOR: d3dblendfunc[i] = D3DBLEND_DESTCOLOR;break;
1846                                         case GL_ONE_MINUS_DST_COLOR: d3dblendfunc[i] = D3DBLEND_INVDESTCOLOR;break;
1847                                         }
1848                                 }
1849                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SRCBLEND, d3dblendfunc[0]);
1850                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DESTBLEND, d3dblendfunc[1]);
1851                                 if (gl_state.blend != blendenable)
1852                                 {
1853                                         gl_state.blend = blendenable;
1854                                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHABLENDENABLE, gl_state.blend);
1855                                 }
1856                         }
1857 #endif
1858                         break;
1859                 case RENDERPATH_D3D10:
1860                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1861                         break;
1862                 case RENDERPATH_D3D11:
1863                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1864                         break;
1865                 case RENDERPATH_SOFT:
1866                         DPSOFTRAST_BlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);
1867                         break;
1868                 }
1869         }
1870 }
1871
1872 void GL_DepthMask(int state)
1873 {
1874         if (gl_state.depthmask != state)
1875         {
1876                 gl_state.depthmask = state;
1877                 switch(vid.renderpath)
1878                 {
1879                 case RENDERPATH_GL11:
1880                 case RENDERPATH_GL13:
1881                 case RENDERPATH_GL20:
1882                 case RENDERPATH_GLES1:
1883                 case RENDERPATH_GLES2:
1884                         CHECKGLERROR
1885                         qglDepthMask(gl_state.depthmask);CHECKGLERROR
1886                         break;
1887                 case RENDERPATH_D3D9:
1888 #ifdef SUPPORTD3D
1889                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
1890 #endif
1891                         break;
1892                 case RENDERPATH_D3D10:
1893                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1894                         break;
1895                 case RENDERPATH_D3D11:
1896                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1897                         break;
1898                 case RENDERPATH_SOFT:
1899                         DPSOFTRAST_DepthMask(gl_state.depthmask);
1900                         break;
1901                 }
1902         }
1903 }
1904
1905 void GL_DepthTest(int state)
1906 {
1907         if (gl_state.depthtest != state)
1908         {
1909                 gl_state.depthtest = state;
1910                 switch(vid.renderpath)
1911                 {
1912                 case RENDERPATH_GL11:
1913                 case RENDERPATH_GL13:
1914                 case RENDERPATH_GL20:
1915                 case RENDERPATH_GLES1:
1916                 case RENDERPATH_GLES2:
1917                         CHECKGLERROR
1918                         if (gl_state.depthtest)
1919                         {
1920                                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1921                         }
1922                         else
1923                         {
1924                                 qglDisable(GL_DEPTH_TEST);CHECKGLERROR
1925                         }
1926                         break;
1927                 case RENDERPATH_D3D9:
1928 #ifdef SUPPORTD3D
1929                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
1930 #endif
1931                         break;
1932                 case RENDERPATH_D3D10:
1933                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1934                         break;
1935                 case RENDERPATH_D3D11:
1936                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1937                         break;
1938                 case RENDERPATH_SOFT:
1939                         DPSOFTRAST_DepthTest(gl_state.depthtest);
1940                         break;
1941                 }
1942         }
1943 }
1944
1945 void GL_DepthFunc(int state)
1946 {
1947         if (gl_state.depthfunc != state)
1948         {
1949                 gl_state.depthfunc = state;
1950                 switch(vid.renderpath)
1951                 {
1952                 case RENDERPATH_GL11:
1953                 case RENDERPATH_GL13:
1954                 case RENDERPATH_GL20:
1955                 case RENDERPATH_GLES1:
1956                 case RENDERPATH_GLES2:
1957                         CHECKGLERROR
1958                         qglDepthFunc(gl_state.depthfunc);CHECKGLERROR
1959                         break;
1960                 case RENDERPATH_D3D9:
1961 #ifdef SUPPORTD3D
1962                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
1963 #endif
1964                         break;
1965                 case RENDERPATH_D3D10:
1966                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1967                         break;
1968                 case RENDERPATH_D3D11:
1969                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1970                         break;
1971                 case RENDERPATH_SOFT:
1972                         DPSOFTRAST_DepthFunc(gl_state.depthfunc);
1973                         break;
1974                 }
1975         }
1976 }
1977
1978 void GL_DepthRange(float nearfrac, float farfrac)
1979 {
1980         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
1981         {
1982                 gl_state.depthrange[0] = nearfrac;
1983                 gl_state.depthrange[1] = farfrac;
1984                 switch(vid.renderpath)
1985                 {
1986                 case RENDERPATH_GL11:
1987                 case RENDERPATH_GL13:
1988                 case RENDERPATH_GL20:
1989                 case RENDERPATH_GLES1:
1990                 case RENDERPATH_GLES2:
1991 #ifdef USE_GLES2
1992                         qglDepthRangef(gl_state.depthrange[0], gl_state.depthrange[1]);
1993 #else
1994                         qglDepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
1995 #endif
1996                         break;
1997                 case RENDERPATH_D3D9:
1998 #ifdef SUPPORTD3D
1999                         {
2000                                 D3DVIEWPORT9 d3dviewport;
2001                                 d3dviewport.X = gl_viewport.x;
2002                                 d3dviewport.Y = gl_viewport.y;
2003                                 d3dviewport.Width = gl_viewport.width;
2004                                 d3dviewport.Height = gl_viewport.height;
2005                                 d3dviewport.MinZ = gl_state.depthrange[0];
2006                                 d3dviewport.MaxZ = gl_state.depthrange[1];
2007                                 IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
2008                         }
2009 #endif
2010                         break;
2011                 case RENDERPATH_D3D10:
2012                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2013                         break;
2014                 case RENDERPATH_D3D11:
2015                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2016                         break;
2017                 case RENDERPATH_SOFT:
2018                         DPSOFTRAST_DepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
2019                         break;
2020                 }
2021         }
2022 }
2023
2024 void R_SetStencilSeparate(qboolean enable, int writemask, int frontfail, int frontzfail, int frontzpass, int backfail, int backzfail, int backzpass, int frontcompare, int backcompare, int comparereference, int comparemask)
2025 {
2026         switch (vid.renderpath)
2027         {
2028         case RENDERPATH_GL11:
2029         case RENDERPATH_GL13:
2030         case RENDERPATH_GL20:
2031         case RENDERPATH_GLES1:
2032         case RENDERPATH_GLES2:
2033                 CHECKGLERROR
2034                 if (enable)
2035                 {
2036                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
2037                 }
2038                 else
2039                 {
2040                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2041                 }
2042                 if (vid.support.ati_separate_stencil)
2043                 {
2044                         qglStencilMask(writemask);CHECKGLERROR
2045                         qglStencilOpSeparate(GL_FRONT, frontfail, frontzfail, frontzpass);CHECKGLERROR
2046                         qglStencilOpSeparate(GL_BACK, backfail, backzfail, backzpass);CHECKGLERROR
2047                         qglStencilFuncSeparate(GL_FRONT, frontcompare, comparereference, comparereference);CHECKGLERROR
2048                         qglStencilFuncSeparate(GL_BACK, backcompare, comparereference, comparereference);CHECKGLERROR
2049                 }
2050                 else if (vid.support.ext_stencil_two_side)
2051                 {
2052 #ifdef GL_STENCIL_TEST_TWO_SIDE_EXT
2053                         qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
2054                         qglActiveStencilFaceEXT(GL_FRONT);CHECKGLERROR
2055                         qglStencilMask(writemask);CHECKGLERROR
2056                         qglStencilOp(frontfail, frontzfail, frontzpass);CHECKGLERROR
2057                         qglStencilFunc(frontcompare, comparereference, comparemask);CHECKGLERROR
2058                         qglActiveStencilFaceEXT(GL_BACK);CHECKGLERROR
2059                         qglStencilMask(writemask);CHECKGLERROR
2060                         qglStencilOp(backfail, backzfail, backzpass);CHECKGLERROR
2061                         qglStencilFunc(backcompare, comparereference, comparemask);CHECKGLERROR
2062 #endif
2063                 }
2064                 break;
2065         case RENDERPATH_D3D9:
2066 #ifdef SUPPORTD3D
2067                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
2068                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
2069                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
2070                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(frontfail));
2071                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(frontzfail));
2072                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(frontzpass));
2073                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, d3dcmpforglfunc(frontcompare));
2074                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFAIL, d3dstencilopforglfunc(backfail));
2075                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILZFAIL, d3dstencilopforglfunc(backzfail));
2076                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILPASS, d3dstencilopforglfunc(backzpass));
2077                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFUNC, d3dcmpforglfunc(backcompare));
2078                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
2079                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
2080 #endif
2081                 break;
2082         case RENDERPATH_D3D10:
2083                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2084                 break;
2085         case RENDERPATH_D3D11:
2086                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2087                 break;
2088         case RENDERPATH_SOFT:
2089                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2090                 break;
2091         }
2092 }
2093
2094 void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask)
2095 {
2096         switch (vid.renderpath)
2097         {
2098         case RENDERPATH_GL11:
2099         case RENDERPATH_GL13:
2100         case RENDERPATH_GL20:
2101         case RENDERPATH_GLES1:
2102         case RENDERPATH_GLES2:
2103                 CHECKGLERROR
2104                 if (enable)
2105                 {
2106                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
2107                 }
2108                 else
2109                 {
2110                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2111                 }
2112                 if (vid.support.ext_stencil_two_side)
2113                 {
2114 #ifdef GL_STENCIL_TEST_TWO_SIDE_EXT
2115                         qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
2116 #endif
2117                 }
2118                 qglStencilMask(writemask);CHECKGLERROR
2119                 qglStencilOp(fail, zfail, zpass);CHECKGLERROR
2120                 qglStencilFunc(compare, comparereference, comparemask);CHECKGLERROR
2121                 CHECKGLERROR
2122                 break;
2123         case RENDERPATH_D3D9:
2124 #ifdef SUPPORTD3D
2125                 if (vid.support.ati_separate_stencil)
2126                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
2127                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
2128                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
2129                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(fail));
2130                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(zfail));
2131                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(zpass));
2132                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, d3dcmpforglfunc(compare));
2133                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
2134                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
2135 #endif
2136                 break;
2137         case RENDERPATH_D3D10:
2138                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2139                 break;
2140         case RENDERPATH_D3D11:
2141                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2142                 break;
2143         case RENDERPATH_SOFT:
2144                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2145                 break;
2146         }
2147 }
2148
2149 void GL_PolygonOffset(float planeoffset, float depthoffset)
2150 {
2151         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
2152         {
2153                 gl_state.polygonoffset[0] = planeoffset;
2154                 gl_state.polygonoffset[1] = depthoffset;
2155                 switch(vid.renderpath)
2156                 {
2157                 case RENDERPATH_GL11:
2158                 case RENDERPATH_GL13:
2159                 case RENDERPATH_GL20:
2160                 case RENDERPATH_GLES1:
2161                 case RENDERPATH_GLES2:
2162                         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
2163                         break;
2164                 case RENDERPATH_D3D9:
2165 #ifdef SUPPORTD3D
2166                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
2167                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
2168 #endif
2169                         break;
2170                 case RENDERPATH_D3D10:
2171                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2172                         break;
2173                 case RENDERPATH_D3D11:
2174                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2175                         break;
2176                 case RENDERPATH_SOFT:
2177                         DPSOFTRAST_PolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
2178                         break;
2179                 }
2180         }
2181 }
2182
2183 void GL_SetMirrorState(qboolean state)
2184 {
2185         if (v_flipped_state != state)
2186         {
2187                 v_flipped_state = state;
2188                 if (gl_state.cullface == GL_BACK)
2189                         gl_state.cullface = GL_FRONT;
2190                 else if (gl_state.cullface == GL_FRONT)
2191                         gl_state.cullface = GL_BACK;
2192                 else
2193                         return;
2194                 switch(vid.renderpath)
2195                 {
2196                 case RENDERPATH_GL11:
2197                 case RENDERPATH_GL13:
2198                 case RENDERPATH_GL20:
2199                 case RENDERPATH_GLES1:
2200                 case RENDERPATH_GLES2:
2201                         qglCullFace(gl_state.cullface);CHECKGLERROR
2202                         break;
2203                 case RENDERPATH_D3D9:
2204 #ifdef SUPPORTD3D
2205                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, gl_state.cullface == GL_FRONT ? D3DCULL_CCW : D3DCULL_CW);
2206 #endif
2207                         break;
2208                 case RENDERPATH_D3D10:
2209                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2210                         break;
2211                 case RENDERPATH_D3D11:
2212                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2213                         break;
2214                 case RENDERPATH_SOFT:
2215                         DPSOFTRAST_CullFace(gl_state.cullface);
2216                         break;
2217                 }
2218         }
2219 }
2220
2221 void GL_CullFace(int state)
2222 {
2223         if(v_flipped_state)
2224         {
2225                 if(state == GL_FRONT)
2226                         state = GL_BACK;
2227                 else if(state == GL_BACK)
2228                         state = GL_FRONT;
2229         }
2230
2231         switch(vid.renderpath)
2232         {
2233         case RENDERPATH_GL11:
2234         case RENDERPATH_GL13:
2235         case RENDERPATH_GL20:
2236         case RENDERPATH_GLES1:
2237         case RENDERPATH_GLES2:
2238                 CHECKGLERROR
2239
2240                 if (state != GL_NONE)
2241                 {
2242                         if (!gl_state.cullfaceenable)
2243                         {
2244                                 gl_state.cullfaceenable = true;
2245                                 qglEnable(GL_CULL_FACE);CHECKGLERROR
2246                         }
2247                         if (gl_state.cullface != state)
2248                         {
2249                                 gl_state.cullface = state;
2250                                 qglCullFace(gl_state.cullface);CHECKGLERROR
2251                         }
2252                 }
2253                 else
2254                 {
2255                         if (gl_state.cullfaceenable)
2256                         {
2257                                 gl_state.cullfaceenable = false;
2258                                 qglDisable(GL_CULL_FACE);CHECKGLERROR
2259                         }
2260                 }
2261                 break;
2262         case RENDERPATH_D3D9:
2263 #ifdef SUPPORTD3D
2264                 if (gl_state.cullface != state)
2265                 {
2266                         gl_state.cullface = state;
2267                         switch(gl_state.cullface)
2268                         {
2269                         case GL_NONE:
2270                                 gl_state.cullfaceenable = false;
2271                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
2272                                 break;
2273                         case GL_FRONT:
2274                                 gl_state.cullfaceenable = true;
2275                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CCW);
2276                                 break;
2277                         case GL_BACK:
2278                                 gl_state.cullfaceenable = true;
2279                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CW);
2280                                 break;
2281                         }
2282                 }
2283 #endif
2284                 break;
2285         case RENDERPATH_D3D10:
2286                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2287                 break;
2288         case RENDERPATH_D3D11:
2289                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2290                 break;
2291         case RENDERPATH_SOFT:
2292                 if (gl_state.cullface != state)
2293                 {
2294                         gl_state.cullface = state;
2295                         gl_state.cullfaceenable = state != GL_NONE ? true : false;
2296                         DPSOFTRAST_CullFace(gl_state.cullface);
2297                 }
2298                 break;
2299         }
2300 }
2301
2302 void GL_AlphaTest(int state)
2303 {
2304         if (gl_state.alphatest != state)
2305         {
2306                 gl_state.alphatest = state;
2307                 switch(vid.renderpath)
2308                 {
2309                 case RENDERPATH_GL11:
2310                 case RENDERPATH_GL13:
2311                 case RENDERPATH_GLES1:
2312 #ifdef GL_ALPHA_TEST
2313                         // only fixed function uses alpha test, other paths use pixel kill capability in shaders
2314                         CHECKGLERROR
2315                         if (gl_state.alphatest)
2316                         {
2317                                 qglEnable(GL_ALPHA_TEST);CHECKGLERROR
2318                         }
2319                         else
2320                         {
2321                                 qglDisable(GL_ALPHA_TEST);CHECKGLERROR
2322                         }
2323 #endif
2324                         break;
2325                 case RENDERPATH_D3D9:
2326                 case RENDERPATH_D3D10:
2327                 case RENDERPATH_D3D11:
2328                 case RENDERPATH_SOFT:
2329                 case RENDERPATH_GL20:
2330                 case RENDERPATH_GLES2:
2331                         break;
2332                 }
2333         }
2334 }
2335
2336 void GL_AlphaToCoverage(qboolean state)
2337 {
2338         if (gl_state.alphatocoverage != state)
2339         {
2340                 gl_state.alphatocoverage = state;
2341                 switch(vid.renderpath)
2342                 {
2343                 case RENDERPATH_GL11:
2344                 case RENDERPATH_GL13:
2345                 case RENDERPATH_GLES1:
2346                 case RENDERPATH_GLES2:
2347                 case RENDERPATH_D3D9:
2348                 case RENDERPATH_D3D10:
2349                 case RENDERPATH_D3D11:
2350                 case RENDERPATH_SOFT:
2351                         break;
2352                 case RENDERPATH_GL20:
2353 #ifdef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
2354                         // alpha to coverage turns the alpha value of the pixel into 0%, 25%, 50%, 75% or 100% by masking the multisample fragments accordingly
2355                         CHECKGLERROR
2356                         if (gl_state.alphatocoverage)
2357                         {
2358                                 qglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
2359 //                              qglEnable(GL_MULTISAMPLE_ARB);CHECKGLERROR
2360                         }
2361                         else
2362                         {
2363                                 qglDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
2364 //                              qglDisable(GL_MULTISAMPLE_ARB);CHECKGLERROR
2365                         }
2366 #endif
2367                         break;
2368                 }
2369         }
2370 }
2371
2372 void GL_ColorMask(int r, int g, int b, int a)
2373 {
2374         // NOTE: this matches D3DCOLORWRITEENABLE_RED, GREEN, BLUE, ALPHA
2375         int state = (r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0);
2376         if (gl_state.colormask != state)
2377         {
2378                 gl_state.colormask = state;
2379                 switch(vid.renderpath)
2380                 {
2381                 case RENDERPATH_GL11:
2382                 case RENDERPATH_GL13:
2383                 case RENDERPATH_GL20:
2384                 case RENDERPATH_GLES1:
2385                 case RENDERPATH_GLES2:
2386                         CHECKGLERROR
2387                         qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
2388                         break;
2389                 case RENDERPATH_D3D9:
2390 #ifdef SUPPORTD3D
2391                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, state);
2392 #endif
2393                         break;
2394                 case RENDERPATH_D3D10:
2395                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2396                         break;
2397                 case RENDERPATH_D3D11:
2398                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2399                         break;
2400                 case RENDERPATH_SOFT:
2401                         DPSOFTRAST_ColorMask(r, g, b, a);
2402                         break;
2403                 }
2404         }
2405 }
2406
2407 void GL_Color(float cr, float cg, float cb, float ca)
2408 {
2409         if (gl_state.pointer_color_enabled || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
2410         {
2411                 gl_state.color4f[0] = cr;
2412                 gl_state.color4f[1] = cg;
2413                 gl_state.color4f[2] = cb;
2414                 gl_state.color4f[3] = ca;
2415                 switch(vid.renderpath)
2416                 {
2417                 case RENDERPATH_GL11:
2418                 case RENDERPATH_GL13:
2419                 case RENDERPATH_GLES1:
2420                         CHECKGLERROR
2421                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
2422                         CHECKGLERROR
2423                         break;
2424                 case RENDERPATH_D3D9:
2425                 case RENDERPATH_D3D10:
2426                 case RENDERPATH_D3D11:
2427                         // no equivalent in D3D
2428                         break;
2429                 case RENDERPATH_SOFT:
2430                         DPSOFTRAST_Color4f(cr, cg, cb, ca);
2431                         break;
2432                 case RENDERPATH_GL20:
2433                 case RENDERPATH_GLES2:
2434                         qglVertexAttrib4f(GLSLATTRIB_COLOR, cr, cg, cb, ca);
2435                         break;
2436                 }
2437         }
2438 }
2439
2440 void GL_Scissor (int x, int y, int width, int height)
2441 {
2442         switch(vid.renderpath)
2443         {
2444         case RENDERPATH_GL11:
2445         case RENDERPATH_GL13:
2446         case RENDERPATH_GL20:
2447         case RENDERPATH_GLES1:
2448         case RENDERPATH_GLES2:
2449                 CHECKGLERROR
2450                 qglScissor(x, y,width,height);
2451                 CHECKGLERROR
2452                 break;
2453         case RENDERPATH_D3D9:
2454 #ifdef SUPPORTD3D
2455                 {
2456                         RECT d3drect;
2457                         d3drect.left = x;
2458                         d3drect.top = y;
2459                         d3drect.right = x + width;
2460                         d3drect.bottom = y + height;
2461                         IDirect3DDevice9_SetScissorRect(vid_d3d9dev, &d3drect);
2462                 }
2463 #endif
2464                 break;
2465         case RENDERPATH_D3D10:
2466                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2467                 break;
2468         case RENDERPATH_D3D11:
2469                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2470                 break;
2471         case RENDERPATH_SOFT:
2472                 DPSOFTRAST_Scissor(x, y, width, height);
2473                 break;
2474         }
2475 }
2476
2477 void GL_ScissorTest(int state)
2478 {
2479         if (gl_state.scissortest != state)
2480         {
2481                 gl_state.scissortest = state;
2482                 switch(vid.renderpath)
2483                 {
2484                 case RENDERPATH_GL11:
2485                 case RENDERPATH_GL13:
2486                 case RENDERPATH_GL20:
2487                 case RENDERPATH_GLES1:
2488                 case RENDERPATH_GLES2:
2489                         CHECKGLERROR
2490                         if(gl_state.scissortest)
2491                                 qglEnable(GL_SCISSOR_TEST);
2492                         else
2493                                 qglDisable(GL_SCISSOR_TEST);
2494                         CHECKGLERROR
2495                         break;
2496                 case RENDERPATH_D3D9:
2497 #ifdef SUPPORTD3D
2498                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SCISSORTESTENABLE, gl_state.scissortest);
2499 #endif
2500                         break;
2501                 case RENDERPATH_D3D10:
2502                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2503                         break;
2504                 case RENDERPATH_D3D11:
2505                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2506                         break;
2507                 case RENDERPATH_SOFT:
2508                         DPSOFTRAST_ScissorTest(gl_state.scissortest);
2509                         break;
2510                 }
2511         }
2512 }
2513
2514 void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue)
2515 {
2516         static const float blackcolor[4] = {0, 0, 0, 0};
2517         // prevent warnings when trying to clear a buffer that does not exist
2518         if (!colorvalue)
2519                 colorvalue = blackcolor;
2520         if (!vid.stencil)
2521         {
2522                 mask &= ~GL_STENCIL_BUFFER_BIT;
2523                 stencilvalue = 0;
2524         }
2525         switch(vid.renderpath)
2526         {
2527         case RENDERPATH_GL11:
2528         case RENDERPATH_GL13:
2529         case RENDERPATH_GL20:
2530         case RENDERPATH_GLES1:
2531         case RENDERPATH_GLES2:
2532                 CHECKGLERROR
2533                 if (mask & GL_COLOR_BUFFER_BIT)
2534                 {
2535                         qglClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);CHECKGLERROR
2536                 }
2537                 if (mask & GL_DEPTH_BUFFER_BIT)
2538                 {
2539 #ifdef USE_GLES2
2540                         qglClearDepthf(depthvalue);CHECKGLERROR
2541 #else
2542                         qglClearDepth(depthvalue);CHECKGLERROR
2543 #endif
2544                 }
2545                 if (mask & GL_STENCIL_BUFFER_BIT)
2546                 {
2547                         qglClearStencil(stencilvalue);CHECKGLERROR
2548                 }
2549                 qglClear(mask);CHECKGLERROR
2550                 break;
2551         case RENDERPATH_D3D9:
2552 #ifdef SUPPORTD3D
2553                 IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, ((mask & GL_COLOR_BUFFER_BIT) ? D3DCLEAR_TARGET : 0) | ((mask & GL_STENCIL_BUFFER_BIT) ? D3DCLEAR_STENCIL : 0) | ((mask & GL_DEPTH_BUFFER_BIT) ? D3DCLEAR_ZBUFFER : 0), D3DCOLOR_COLORVALUE(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]), depthvalue, stencilvalue);
2554 #endif
2555                 break;
2556         case RENDERPATH_D3D10:
2557                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2558                 break;
2559         case RENDERPATH_D3D11:
2560                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2561                 break;
2562         case RENDERPATH_SOFT:
2563                 if (mask & GL_COLOR_BUFFER_BIT)
2564                         DPSOFTRAST_ClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);
2565                 if (mask & GL_DEPTH_BUFFER_BIT)
2566                         DPSOFTRAST_ClearDepth(depthvalue);
2567                 break;
2568         }
2569 }
2570
2571 void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels)
2572 {
2573         switch(vid.renderpath)
2574         {
2575         case RENDERPATH_GL11:
2576         case RENDERPATH_GL13:
2577         case RENDERPATH_GL20:
2578         case RENDERPATH_GLES1:
2579         case RENDERPATH_GLES2:
2580                 CHECKGLERROR
2581                 qglReadPixels(x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
2582                 break;
2583         case RENDERPATH_D3D9:
2584 #ifdef SUPPORTD3D
2585                 {
2586                         // LordHavoc: we can't directly download the backbuffer because it may be
2587                         // multisampled, and it may not be lockable, so we blit it to a lockable
2588                         // surface of the same dimensions (but without multisample) to resolve the
2589                         // multisample buffer to a normal image, and then lock that...
2590                         IDirect3DSurface9 *stretchsurface = NULL;
2591                         if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, TRUE, &stretchsurface, NULL)))
2592                         {
2593                                 D3DLOCKED_RECT lockedrect;
2594                                 if (!FAILED(IDirect3DDevice9_StretchRect(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, NULL, stretchsurface, NULL, D3DTEXF_POINT)))
2595                                 {
2596                                         if (!FAILED(IDirect3DSurface9_LockRect(stretchsurface, &lockedrect, NULL, D3DLOCK_READONLY)))
2597                                         {
2598                                                 int line;
2599                                                 unsigned char *row = (unsigned char *)lockedrect.pBits + x * 4 + lockedrect.Pitch * (vid.height - 1 - y);
2600                                                 for (line = 0;line < height;line++, row -= lockedrect.Pitch)
2601                                                         memcpy(outpixels + line * width * 4, row, width * 4);
2602                                                 IDirect3DSurface9_UnlockRect(stretchsurface);
2603                                         }
2604                                 }
2605                                 IDirect3DSurface9_Release(stretchsurface);
2606                         }
2607                         // code scraps
2608                         //IDirect3DSurface9 *syssurface = NULL;
2609                         //if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &stretchsurface, NULL)))
2610                         //if (!FAILED(IDirect3DDevice9_CreateOffscreenPlainSurface(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &syssurface, NULL)))
2611                         //IDirect3DDevice9_GetRenderTargetData(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, syssurface);
2612                         //if (!FAILED(IDirect3DDevice9_GetFrontBufferData(vid_d3d9dev, 0, syssurface)))
2613                         //if (!FAILED(IDirect3DSurface9_LockRect(syssurface, &lockedrect, NULL, D3DLOCK_READONLY)))
2614                         //IDirect3DSurface9_UnlockRect(syssurface);
2615                         //IDirect3DSurface9_Release(syssurface);
2616                 }
2617 #endif
2618                 break;
2619         case RENDERPATH_D3D10:
2620                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2621                 break;
2622         case RENDERPATH_D3D11:
2623                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2624                 break;
2625         case RENDERPATH_SOFT:
2626                 DPSOFTRAST_GetPixelsBGRA(x, y, width, height, outpixels);
2627                 break;
2628         }
2629 }
2630
2631 // called at beginning of frame
2632 void R_Mesh_Start(void)
2633 {
2634         BACKENDACTIVECHECK
2635         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
2636         R_Mesh_SetUseVBO();
2637         if (gl_printcheckerror.integer && !gl_paranoid.integer)
2638         {
2639                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
2640                 Cvar_SetValueQuick(&gl_paranoid, 1);
2641         }
2642 }
2643
2644 static qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
2645 {
2646         int shaderobject;
2647         int shadercompiled;
2648         char compilelog[MAX_INPUTLINE];
2649         shaderobject = qglCreateShader(shadertypeenum);CHECKGLERROR
2650         if (!shaderobject)
2651                 return false;
2652         qglShaderSource(shaderobject, numstrings, strings, NULL);CHECKGLERROR
2653         qglCompileShader(shaderobject);CHECKGLERROR
2654         qglGetShaderiv(shaderobject, GL_COMPILE_STATUS, &shadercompiled);CHECKGLERROR
2655         qglGetShaderInfoLog(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
2656         if (compilelog[0] && ((strstr(compilelog, "error") || strstr(compilelog, "ERROR") || strstr(compilelog, "Error")) || ((strstr(compilelog, "WARNING") || strstr(compilelog, "warning") || strstr(compilelog, "Warning")) && developer.integer) || developer_extra.integer))
2657         {
2658                 int i, j, pretextlines = 0;
2659                 for (i = 0;i < numstrings - 1;i++)
2660                         for (j = 0;strings[i][j];j++)
2661                                 if (strings[i][j] == '\n')
2662                                         pretextlines++;
2663                 Con_Printf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
2664         }
2665         if (!shadercompiled)
2666         {
2667                 qglDeleteShader(shaderobject);CHECKGLERROR
2668                 return false;
2669         }
2670         qglAttachShader(programobject, shaderobject);CHECKGLERROR
2671         qglDeleteShader(shaderobject);CHECKGLERROR
2672         return true;
2673 }
2674
2675 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int geometrystrings_count, const char **geometrystrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
2676 {
2677         GLint programlinked;
2678         GLuint programobject = 0;
2679         char linklog[MAX_INPUTLINE];
2680         CHECKGLERROR
2681
2682         programobject = qglCreateProgram();CHECKGLERROR
2683         if (!programobject)
2684                 return 0;
2685
2686         qglBindAttribLocation(programobject, GLSLATTRIB_POSITION , "Attrib_Position" );
2687         qglBindAttribLocation(programobject, GLSLATTRIB_COLOR    , "Attrib_Color"    );
2688         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD0, "Attrib_TexCoord0");
2689         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD1, "Attrib_TexCoord1");
2690         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD2, "Attrib_TexCoord2");
2691         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD3, "Attrib_TexCoord3");
2692         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD4, "Attrib_TexCoord4");
2693         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD5, "Attrib_TexCoord5");
2694         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD6, "Attrib_SkeletalIndex");
2695         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD7, "Attrib_SkeletalWeight");
2696 #ifndef USE_GLES2
2697         if(vid.support.gl20shaders130)
2698                 qglBindFragDataLocation(programobject, 0, "dp_FragColor");
2699 #endif
2700
2701         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER, "vertex", vertexstrings_count, vertexstrings_list))
2702                 goto cleanup;
2703
2704 #ifdef GL_GEOMETRY_SHADER
2705         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER, "geometry", geometrystrings_count, geometrystrings_list))
2706                 goto cleanup;
2707 #endif
2708
2709         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER, "fragment", fragmentstrings_count, fragmentstrings_list))
2710                 goto cleanup;
2711
2712         qglLinkProgram(programobject);CHECKGLERROR
2713         qglGetProgramiv(programobject, GL_LINK_STATUS, &programlinked);CHECKGLERROR
2714         qglGetProgramInfoLog(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
2715         if (linklog[0])
2716         {
2717                 if (strstr(linklog, "error") || strstr(linklog, "ERROR") || strstr(linklog, "Error") || strstr(linklog, "WARNING") || strstr(linklog, "warning") || strstr(linklog, "Warning") || developer_extra.integer)
2718                         Con_DPrintf("program link log:\n%s\n", linklog);
2719                 // software vertex shader is ok but software fragment shader is WAY
2720                 // too slow, fail program if so.
2721                 // NOTE: this string might be ATI specific, but that's ok because the
2722                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
2723                 // software fragment shader due to low instruction and dependent
2724                 // texture limits.
2725                 if (strstr(linklog, "fragment shader will run in software"))
2726                         programlinked = false;
2727         }
2728         if (!programlinked)
2729                 goto cleanup;
2730         return programobject;
2731 cleanup:
2732         qglDeleteProgram(programobject);CHECKGLERROR
2733         return 0;
2734 }
2735
2736 void GL_Backend_FreeProgram(unsigned int prog)
2737 {
2738         CHECKGLERROR
2739         qglDeleteProgram(prog);
2740         CHECKGLERROR
2741 }
2742
2743 // renders triangles using vertices from the active arrays
2744 int paranoidblah = 0;
2745 void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const r_meshbuffer_t *element3i_indexbuffer, size_t element3i_bufferoffset, const unsigned short *element3s, const r_meshbuffer_t *element3s_indexbuffer, size_t element3s_bufferoffset)
2746 {
2747         unsigned int numelements = numtriangles * 3;
2748         int bufferobject3i;
2749         size_t bufferoffset3i;
2750         int bufferobject3s;
2751         size_t bufferoffset3s;
2752         if (numvertices < 3 || numtriangles < 1)
2753         {
2754                 if (numvertices < 0 || numtriangles < 0 || developer_extra.integer)
2755                         Con_DPrintf("R_Mesh_Draw(%d, %d, %d, %d, %8p, %8p, %8x, %8p, %8p, %8x);\n", firstvertex, numvertices, firsttriangle, numtriangles, (void *)element3i, (void *)element3i_indexbuffer, (int)element3i_bufferoffset, (void *)element3s, (void *)element3s_indexbuffer, (int)element3s_bufferoffset);
2756                 return;
2757         }
2758         if (!gl_mesh_prefer_short_elements.integer)
2759         {
2760                 if (element3i)
2761                 {
2762                         element3s = NULL;
2763                         element3s_indexbuffer = NULL;
2764                 }
2765         }
2766         // adjust the pointers for firsttriangle
2767         if (element3i)
2768                 element3i += firsttriangle * 3;
2769         if (element3i_indexbuffer)
2770                 element3i_bufferoffset += firsttriangle * 3 * sizeof(*element3i);
2771         if (element3s)
2772                 element3s += firsttriangle * 3;
2773         if (element3s_indexbuffer)
2774                 element3s_bufferoffset += firsttriangle * 3 * sizeof(*element3s);
2775         switch(vid.renderpath)
2776         {
2777         case RENDERPATH_GL11:
2778         case RENDERPATH_GL13:
2779         case RENDERPATH_GL20:
2780         case RENDERPATH_GLES1:
2781         case RENDERPATH_GLES2:
2782                 // check if the user specified to ignore static index buffers
2783                 if (!gl_state.usevbo_staticindex || (gl_vbo.integer == 3 && !vid.forcevbo && (element3i_bufferoffset || element3s_bufferoffset)))
2784                 {
2785                         element3i_indexbuffer = NULL;
2786                         element3s_indexbuffer = NULL;
2787                 }
2788                 break;
2789         case RENDERPATH_D3D9:
2790         case RENDERPATH_D3D10:
2791         case RENDERPATH_D3D11:
2792                 break;
2793         case RENDERPATH_SOFT:
2794                 break;
2795         }
2796         // upload a dynamic index buffer if needed
2797         if (element3s)
2798         {
2799                 if (!element3s_indexbuffer && gl_state.usevbo_dynamicindex)
2800                 {
2801                         if (gl_state.draw_dynamicindexbuffer)
2802                                 R_Mesh_UpdateMeshBuffer(gl_state.draw_dynamicindexbuffer, (void *)element3s, numelements * sizeof(*element3s), false, 0);
2803                         else
2804                                 gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3s, numelements * sizeof(*element3s), "temporary", true, false, true, true);
2805                         element3s_indexbuffer = gl_state.draw_dynamicindexbuffer;
2806                         element3s_bufferoffset = 0;
2807                 }
2808         }
2809         else if (element3i)
2810         {
2811                 if (!element3i_indexbuffer && gl_state.usevbo_dynamicindex)
2812                 {
2813                         if (gl_state.draw_dynamicindexbuffer)
2814                                 R_Mesh_UpdateMeshBuffer(gl_state.draw_dynamicindexbuffer, (void *)element3i, numelements * sizeof(*element3i), false, 0);
2815                         else
2816                                 gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3i, numelements * sizeof(*element3i), "temporary", true, false, true, false);
2817                         element3i_indexbuffer = gl_state.draw_dynamicindexbuffer;
2818                         element3i_bufferoffset = 0;
2819                 }
2820         }
2821         bufferobject3i = element3i_indexbuffer ? element3i_indexbuffer->bufferobject : 0;
2822         bufferoffset3i = element3i_bufferoffset;
2823         bufferobject3s = element3s_indexbuffer ? element3s_indexbuffer->bufferobject : 0;
2824         bufferoffset3s = element3s_bufferoffset;
2825         r_refdef.stats[r_stat_draws]++;
2826         r_refdef.stats[r_stat_draws_vertices] += numvertices;
2827         r_refdef.stats[r_stat_draws_elements] += numelements;
2828         if (gl_paranoid.integer)
2829         {
2830                 unsigned int i;
2831                 // LordHavoc: disabled this - it needs to be updated to handle components and gltype and stride in each array
2832 #if 0
2833                 unsigned int j, size;
2834                 const int *p;
2835                 // note: there's no validation done here on buffer objects because it
2836                 // is somewhat difficult to get at the data, and gl_paranoid can be
2837                 // used without buffer objects if the need arises
2838                 // (the data could be gotten using glMapBuffer but it would be very
2839                 //  slow due to uncachable video memory reads)
2840                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
2841                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
2842                 CHECKGLERROR
2843                 if (gl_state.pointer_vertex_pointer)
2844                         for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
2845                                 paranoidblah += *p;
2846                 if (gl_state.pointer_color_enabled)
2847                 {
2848                         if (!qglIsEnabled(GL_COLOR_ARRAY))
2849                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
2850                         CHECKGLERROR
2851                         if (gl_state.pointer_color && gl_state.pointer_color_enabled)
2852                                 for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
2853                                         paranoidblah += *p;
2854                 }
2855                 for (i = 0;i < vid.texarrayunits;i++)
2856                 {
2857                         if (gl_state.units[i].arrayenabled)
2858                         {
2859                                 GL_ClientActiveTexture(i);
2860                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
2861                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
2862                                 CHECKGLERROR
2863                                 if (gl_state.units[i].pointer_texcoord && gl_state.units[i].arrayenabled)
2864                                         for (j = 0, size = numvertices * gl_state.units[i].arraycomponents, p = (int *)((float *)gl_state.units[i].pointer_texcoord + firstvertex * gl_state.units[i].arraycomponents);j < size;j++, p++)
2865                                                 paranoidblah += *p;
2866                         }
2867                 }
2868 #endif
2869                 if (element3i)
2870                 {
2871                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2872                         {
2873                                 if (element3i[i] < firstvertex || element3i[i] >= firstvertex + numvertices)
2874                                 {
2875                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3i array\n", element3i[i], firstvertex, firstvertex + numvertices);
2876                                         return;
2877                                 }
2878                         }
2879                 }
2880                 if (element3s)
2881                 {
2882                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2883                         {
2884                                 if (element3s[i] < firstvertex || element3s[i] >= firstvertex + numvertices)
2885                                 {
2886                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3s array\n", element3s[i], firstvertex, firstvertex + numvertices);
2887                                         return;
2888                                 }
2889                         }
2890                 }
2891         }
2892         if (r_render.integer || r_refdef.draw2dstage)
2893         {
2894                 switch(vid.renderpath)
2895                 {
2896                 case RENDERPATH_GL11:
2897                 case RENDERPATH_GL13:
2898                 case RENDERPATH_GL20:
2899                         CHECKGLERROR
2900                         if (gl_mesh_testmanualfeeding.integer)
2901                         {
2902 #ifndef USE_GLES2
2903                                 unsigned int i, j, element;
2904                                 const GLfloat *p;
2905                                 qglBegin(GL_TRIANGLES);
2906                                 if(vid.renderpath == RENDERPATH_GL20)
2907                                 {
2908                                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2909                                         {
2910                                                 if (element3i)
2911                                                         element = element3i[i];
2912                                                 else if (element3s)
2913                                                         element = element3s[i];
2914                                                 else
2915                                                         element = firstvertex + i;
2916                                                 for (j = 0;j < vid.texarrayunits;j++)
2917                                                 {
2918                                                         if (gl_state.units[j].pointer_texcoord_pointer && gl_state.units[j].arrayenabled)
2919                                                         {
2920                                                                 if (gl_state.units[j].pointer_texcoord_gltype == GL_FLOAT)
2921                                                                 {
2922                                                                         p = (const GLfloat *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2923                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2924                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1], p[2], p[3]);
2925                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
2926                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1], p[2]);
2927                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
2928                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1]);
2929                                                                         else
2930                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, p[0]);
2931                                                                 }
2932                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == (int)(GL_SHORT | 0x80000000))
2933                                                                 {
2934                                                                         const GLshort *s = (const GLshort *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2935                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2936                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1], s[2], s[3]);
2937                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
2938                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1], s[2]);
2939                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
2940                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1]);
2941                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
2942                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, s[0]);
2943                                                                 }
2944                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == GL_BYTE)
2945                                                                 {
2946                                                                         const GLbyte *sb = (const GLbyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2947                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2948                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f), sb[2] * (1.0f / 127.0f), sb[3] * (1.0f / 127.0f));
2949                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
2950                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f), sb[2] * (1.0f / 127.0f));
2951                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
2952                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f));
2953                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
2954                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f));
2955                                                                 }
2956                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == GL_UNSIGNED_BYTE)
2957                                                                 {
2958                                                                         const GLubyte *sb = (const GLubyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2959                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2960                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f), sb[2] * (1.0f / 255.0f), sb[3] * (1.0f / 255.0f));
2961                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
2962                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f), sb[2] * (1.0f / 255.0f));
2963                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
2964                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f));
2965                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
2966                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f));
2967                                                                 }
2968                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == (int)(GL_UNSIGNED_BYTE | 0x80000000))
2969                                                                 {
2970                                                                         const GLubyte *sb = (const GLubyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2971                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2972                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1], sb[2], sb[3]);
2973                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
2974                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1], sb[2]);
2975                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
2976                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1]);
2977                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
2978                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0]);
2979                                                                 }
2980                                                         }
2981                                                 }
2982                                                 if (gl_state.pointer_color_pointer && gl_state.pointer_color_enabled && gl_state.pointer_color_components == 4)
2983                                                 {
2984                                                         if (gl_state.pointer_color_gltype == GL_FLOAT)
2985                                                         {
2986                                                                 p = (const GLfloat *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
2987                                                                 qglVertexAttrib4f(GLSLATTRIB_COLOR, p[0], p[1], p[2], p[3]);
2988                                                         }
2989                                                         else if (gl_state.pointer_color_gltype == GL_UNSIGNED_BYTE)
2990                                                         {
2991                                                                 const GLubyte *ub = (const GLubyte *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
2992                                                                 qglVertexAttrib4Nub(GLSLATTRIB_COLOR, ub[0], ub[1], ub[2], ub[3]);
2993                                                         }
2994                                                 }
2995                                                 if (gl_state.pointer_vertex_gltype == GL_FLOAT)
2996                                                 {
2997                                                         p = (const GLfloat *)((const unsigned char *)gl_state.pointer_vertex_pointer + element * gl_state.pointer_vertex_stride);
2998                                                         if (gl_state.pointer_vertex_components == 4)
2999                                                                 qglVertexAttrib4f(GLSLATTRIB_POSITION, p[0], p[1], p[2], p[3]);
3000                                                         else if (gl_state.pointer_vertex_components == 3)
3001                                                                 qglVertexAttrib3f(GLSLATTRIB_POSITION, p[0], p[1], p[2]);
3002                                                         else
3003                                                                 qglVertexAttrib2f(GLSLATTRIB_POSITION, p[0], p[1]);
3004                                                 }
3005                                         }
3006                                 }
3007                                 else
3008                                 {
3009                                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
3010                                         {
3011                                                 if (element3i)
3012                                                         element = element3i[i];
3013                                                 else if (element3s)
3014                                                         element = element3s[i];
3015                                                 else
3016                                                         element = firstvertex + i;
3017                                                 for (j = 0;j < vid.texarrayunits;j++)
3018                                                 {
3019                                                         if (gl_state.units[j].pointer_texcoord_pointer && gl_state.units[j].arrayenabled)
3020                                                         {
3021                                                                 if (gl_state.units[j].pointer_texcoord_gltype == GL_FLOAT)
3022                                                                 {
3023                                                                         p = (const GLfloat *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
3024                                                                         if (vid.texarrayunits > 1)
3025                                                                         {
3026                                                                                 if (gl_state.units[j].pointer_texcoord_components == 4)
3027                                                                                         qglMultiTexCoord4f(GL_TEXTURE0 + j, p[0], p[1], p[2], p[3]);
3028                                                                                 else if (gl_state.units[j].pointer_texcoord_components == 3)
3029                                                                                         qglMultiTexCoord3f(GL_TEXTURE0 + j, p[0], p[1], p[2]);
3030                                                                                 else if (gl_state.units[j].pointer_texcoord_components == 2)
3031                                                                                         qglMultiTexCoord2f(GL_TEXTURE0 + j, p[0], p[1]);
3032                                                                                 else
3033                                                                                         qglMultiTexCoord1f(GL_TEXTURE0 + j, p[0]);
3034                                                                         }
3035                                                                         else
3036                                                                         {
3037                                                                                 if (gl_state.units[j].pointer_texcoord_components == 4)
3038                                                                                         qglTexCoord4f(p[0], p[1], p[2], p[3]);
3039                                                                                 else if (gl_state.units[j].pointer_texcoord_components == 3)
3040                                                                                         qglTexCoord3f(p[0], p[1], p[2]);
3041                                                                                 else if (gl_state.units[j].pointer_texcoord_components == 2)
3042                                                                                         qglTexCoord2f(p[0], p[1]);
3043                                                                                 else
3044                                                                                         qglTexCoord1f(p[0]);
3045                                                                         }
3046                                                                 }
3047                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == GL_SHORT)