]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_backend.c
Just assume GL_ARB_texture_non_power_of_two and a number of other extensions are...
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4
5 // on GLES we have to use some proper #define's
6 #ifndef GL_FRAMEBUFFER
7 #define GL_FRAMEBUFFER                                   0x8D40
8 #define GL_DEPTH_ATTACHMENT                              0x8D00
9 #define GL_COLOR_ATTACHMENT0                             0x8CE0
10 #define GL_INVALID_FRAMEBUFFER_OPERATION                 0x0506
11 #endif
12 #ifndef GL_COLOR_ATTACHMENT1
13 #define GL_COLOR_ATTACHMENT1                             0x8CE1
14 #define GL_COLOR_ATTACHMENT2                             0x8CE2
15 #define GL_COLOR_ATTACHMENT3                             0x8CE3
16 #define GL_COLOR_ATTACHMENT4                             0x8CE4
17 #define GL_COLOR_ATTACHMENT5                             0x8CE5
18 #define GL_COLOR_ATTACHMENT6                             0x8CE6
19 #define GL_COLOR_ATTACHMENT7                             0x8CE7
20 #define GL_COLOR_ATTACHMENT8                             0x8CE8
21 #define GL_COLOR_ATTACHMENT9                             0x8CE9
22 #define GL_COLOR_ATTACHMENT10                            0x8CEA
23 #define GL_COLOR_ATTACHMENT11                            0x8CEB
24 #define GL_COLOR_ATTACHMENT12                            0x8CEC
25 #define GL_COLOR_ATTACHMENT13                            0x8CED
26 #define GL_COLOR_ATTACHMENT14                            0x8CEE
27 #define GL_COLOR_ATTACHMENT15                            0x8CEF
28 #endif
29 #ifndef GL_ARRAY_BUFFER
30 #define GL_ARRAY_BUFFER               0x8892
31 #define GL_ELEMENT_ARRAY_BUFFER       0x8893
32 #endif
33 #ifndef GL_TEXTURE0
34 #define GL_TEXTURE0                                     0x84C0
35 #define GL_TEXTURE1                                     0x84C1
36 #define GL_TEXTURE2                                     0x84C2
37 #define GL_TEXTURE3                                     0x84C3
38 #define GL_TEXTURE4                                     0x84C4
39 #define GL_TEXTURE5                                     0x84C5
40 #define GL_TEXTURE6                                     0x84C6
41 #define GL_TEXTURE7                                     0x84C7
42 #define GL_TEXTURE8                                     0x84C8
43 #define GL_TEXTURE9                                     0x84C9
44 #define GL_TEXTURE10                            0x84CA
45 #define GL_TEXTURE11                            0x84CB
46 #define GL_TEXTURE12                            0x84CC
47 #define GL_TEXTURE13                            0x84CD
48 #define GL_TEXTURE14                            0x84CE
49 #define GL_TEXTURE15                            0x84CF
50 #define GL_TEXTURE16                            0x84D0
51 #define GL_TEXTURE17                            0x84D1
52 #define GL_TEXTURE18                            0x84D2
53 #define GL_TEXTURE19                            0x84D3
54 #define GL_TEXTURE20                            0x84D4
55 #define GL_TEXTURE21                            0x84D5
56 #define GL_TEXTURE22                            0x84D6
57 #define GL_TEXTURE23                            0x84D7
58 #define GL_TEXTURE24                            0x84D8
59 #define GL_TEXTURE25                            0x84D9
60 #define GL_TEXTURE26                            0x84DA
61 #define GL_TEXTURE27                            0x84DB
62 #define GL_TEXTURE28                            0x84DC
63 #define GL_TEXTURE29                            0x84DD
64 #define GL_TEXTURE30                            0x84DE
65 #define GL_TEXTURE31                            0x84DF
66 #endif
67
68 #ifndef GL_TEXTURE_3D
69 #define GL_TEXTURE_3D                           0x806F
70 #endif
71 #ifndef GL_TEXTURE_CUBE_MAP
72 #define GL_TEXTURE_CUBE_MAP                 0x8513
73 #endif
74
75
76 #define MAX_RENDERTARGETS 4
77
78 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
79 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
80
81 cvar_t r_render = {0, "r_render", "1", "enables rendering 3D views (you want this on!)"};
82 cvar_t r_renderview = {0, "r_renderview", "1", "enables rendering 3D views (you want this on!)"};
83 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
84 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
85 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
86 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"};
87
88 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
89 qboolean v_flipped_state = false;
90
91 r_viewport_t gl_viewport;
92 matrix4x4_t gl_modelmatrix;
93 matrix4x4_t gl_viewmatrix;
94 matrix4x4_t gl_modelviewmatrix;
95 matrix4x4_t gl_projectionmatrix;
96 matrix4x4_t gl_modelviewprojectionmatrix;
97 float gl_modelview16f[16];
98 float gl_modelviewprojection16f[16];
99 qboolean gl_modelmatrixchanged;
100
101 int gl_maxdrawrangeelementsvertices;
102 int gl_maxdrawrangeelementsindices;
103
104 #ifdef DEBUGGL
105 int gl_errornumber = 0;
106
107 void GL_PrintError(int errornumber, const char *filename, int linenumber)
108 {
109         switch(errornumber)
110         {
111 #ifdef GL_INVALID_ENUM
112         case GL_INVALID_ENUM:
113                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
114                 break;
115 #endif
116 #ifdef GL_INVALID_VALUE
117         case GL_INVALID_VALUE:
118                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
119                 break;
120 #endif
121 #ifdef GL_INVALID_OPERATION
122         case GL_INVALID_OPERATION:
123                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
124                 break;
125 #endif
126 #ifdef GL_STACK_OVERFLOW
127         case GL_STACK_OVERFLOW:
128                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
129                 break;
130 #endif
131 #ifdef GL_STACK_UNDERFLOW
132         case GL_STACK_UNDERFLOW:
133                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
134                 break;
135 #endif
136 #ifdef GL_OUT_OF_MEMORY
137         case GL_OUT_OF_MEMORY:
138                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
139                 break;
140 #endif
141 #ifdef GL_TABLE_TOO_LARGE
142         case GL_TABLE_TOO_LARGE:
143                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
144                 break;
145 #endif
146 #ifdef GL_INVALID_FRAMEBUFFER_OPERATION
147         case GL_INVALID_FRAMEBUFFER_OPERATION:
148                 Con_Printf("GL_INVALID_FRAMEBUFFER_OPERATION at %s:%i\n", filename, linenumber);
149                 break;
150 #endif
151         default:
152                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
153                 break;
154         }
155 }
156 #endif
157
158 #define BACKENDACTIVECHECK if (!gl_state.active) Sys_Error("GL backend function called when backend is not active");
159
160 void SCR_ScreenShot_f (void);
161
162 typedef struct gltextureunit_s
163 {
164         int pointer_texcoord_components;
165         int pointer_texcoord_gltype;
166         size_t pointer_texcoord_stride;
167         const void *pointer_texcoord_pointer;
168         const r_meshbuffer_t *pointer_texcoord_vertexbuffer;
169         size_t pointer_texcoord_offset;
170
171         rtexture_t *texture;
172         int t2d, t3d, tcubemap;
173         int arrayenabled;
174         int rgbscale, alphascale;
175         int combine;
176         int combinergb, combinealpha;
177         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
178         int texmatrixenabled;
179         matrix4x4_t matrix;
180 }
181 gltextureunit_t;
182
183 typedef struct gl_state_s
184 {
185         int cullface;
186         int cullfaceenable;
187         int blendfunc1;
188         int blendfunc2;
189         qboolean blend;
190         GLboolean depthmask;
191         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
192         int depthtest;
193         int depthfunc;
194         float depthrange[2];
195         float polygonoffset[2];
196         int alphatest;
197         int alphafunc;
198         float alphafuncvalue;
199         qboolean alphatocoverage;
200         int scissortest;
201         unsigned int unit;
202         unsigned int clientunit;
203         gltextureunit_t units[MAX_TEXTUREUNITS];
204         float color4f[4];
205         int lockrange_first;
206         int lockrange_count;
207         int vertexbufferobject;
208         int elementbufferobject;
209         int uniformbufferobject;
210         int framebufferobject;
211         int defaultframebufferobject; // deal with platforms that use a non-zero default fbo
212         qboolean pointer_color_enabled;
213
214         int pointer_vertex_components;
215         int pointer_vertex_gltype;
216         size_t pointer_vertex_stride;
217         const void *pointer_vertex_pointer;
218         const r_meshbuffer_t *pointer_vertex_vertexbuffer;
219         size_t pointer_vertex_offset;
220
221         int pointer_color_components;
222         int pointer_color_gltype;
223         size_t pointer_color_stride;
224         const void *pointer_color_pointer;
225         const r_meshbuffer_t *pointer_color_vertexbuffer;
226         size_t pointer_color_offset;
227
228         void *preparevertices_tempdata;
229         size_t preparevertices_tempdatamaxsize;
230         int preparevertices_numvertices;
231
232         memexpandablearray_t meshbufferarray;
233
234         qboolean active;
235 }
236 gl_state_t;
237
238 static gl_state_t gl_state;
239
240
241 /*
242 note: here's strip order for a terrain row:
243 0--1--2--3--4
244 |\ |\ |\ |\ |
245 | \| \| \| \|
246 A--B--C--D--E
247 clockwise
248
249 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
250
251 *elements++ = i + row;
252 *elements++ = i;
253 *elements++ = i + row + 1;
254 *elements++ = i;
255 *elements++ = i + 1;
256 *elements++ = i + row + 1;
257
258
259 for (y = 0;y < rows - 1;y++)
260 {
261         for (x = 0;x < columns - 1;x++)
262         {
263                 i = y * rows + x;
264                 *elements++ = i + columns;
265                 *elements++ = i;
266                 *elements++ = i + columns + 1;
267                 *elements++ = i;
268                 *elements++ = i + 1;
269                 *elements++ = i + columns + 1;
270         }
271 }
272
273 alternative:
274 0--1--2--3--4
275 | /| /|\ | /|
276 |/ |/ | \|/ |
277 A--B--C--D--E
278 counterclockwise
279
280 for (y = 0;y < rows - 1;y++)
281 {
282         for (x = 0;x < columns - 1;x++)
283         {
284                 i = y * rows + x;
285                 *elements++ = i;
286                 *elements++ = i + columns;
287                 *elements++ = i + columns + 1;
288                 *elements++ = i + columns;
289                 *elements++ = i + columns + 1;
290                 *elements++ = i + 1;
291         }
292 }
293 */
294
295 int polygonelement3i[(POLYGONELEMENTS_MAXPOINTS-2)*3];
296 unsigned short polygonelement3s[(POLYGONELEMENTS_MAXPOINTS-2)*3];
297 int quadelement3i[QUADELEMENTS_MAXQUADS*6];
298 unsigned short quadelement3s[QUADELEMENTS_MAXQUADS*6];
299
300 static void GL_VBOStats_f(void)
301 {
302         GL_Mesh_ListVBOs(true);
303 }
304
305 static void GL_Backend_ResetState(void);
306
307 static void gl_backend_start(void)
308 {
309         memset(&gl_state, 0, sizeof(gl_state));
310
311         Mem_ExpandableArray_NewArray(&gl_state.meshbufferarray, r_main_mempool, sizeof(r_meshbuffer_t), 128);
312
313         Con_DPrintf("OpenGL backend started.\n");
314
315         CHECKGLERROR
316
317         GL_Backend_ResetState();
318
319         switch(vid.renderpath)
320         {
321         case RENDERPATH_GL20:
322         case RENDERPATH_GLES2:
323                 // fetch current fbo here (default fbo is not 0 on some GLES devices)
324                 qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &gl_state.defaultframebufferobject);
325                 break;
326         }
327 }
328
329 static void gl_backend_shutdown(void)
330 {
331         Con_DPrint("OpenGL Backend shutting down\n");
332
333         switch(vid.renderpath)
334         {
335         case RENDERPATH_GL20:
336         case RENDERPATH_GLES2:
337                 break;
338         }
339
340         if (gl_state.preparevertices_tempdata)
341                 Mem_Free(gl_state.preparevertices_tempdata);
342
343         Mem_ExpandableArray_FreeArray(&gl_state.meshbufferarray);
344
345         memset(&gl_state, 0, sizeof(gl_state));
346 }
347
348 static void gl_backend_newmap(void)
349 {
350 }
351
352 static void gl_backend_devicelost(void)
353 {
354         int i, endindex;
355         r_meshbuffer_t *buffer;
356         switch(vid.renderpath)
357         {
358         case RENDERPATH_GL20:
359         case RENDERPATH_GLES2:
360                 break;
361         }
362         endindex = (int)Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
363         for (i = 0;i < endindex;i++)
364         {
365                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
366                 if (!buffer || !buffer->isdynamic)
367                         continue;
368                 switch(vid.renderpath)
369                 {
370                 case RENDERPATH_GL20:
371                 case RENDERPATH_GLES2:
372                         break;
373                 }
374         }
375 }
376
377 static void gl_backend_devicerestored(void)
378 {
379         switch(vid.renderpath)
380         {
381         case RENDERPATH_GL20:
382         case RENDERPATH_GLES2:
383                 break;
384         }
385 }
386
387 void gl_backend_init(void)
388 {
389         int i;
390
391         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
392         {
393                 polygonelement3s[i * 3 + 0] = 0;
394                 polygonelement3s[i * 3 + 1] = i + 1;
395                 polygonelement3s[i * 3 + 2] = i + 2;
396         }
397         // elements for rendering a series of quads as triangles
398         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
399         {
400                 quadelement3s[i * 6 + 0] = i * 4;
401                 quadelement3s[i * 6 + 1] = i * 4 + 1;
402                 quadelement3s[i * 6 + 2] = i * 4 + 2;
403                 quadelement3s[i * 6 + 3] = i * 4;
404                 quadelement3s[i * 6 + 4] = i * 4 + 2;
405                 quadelement3s[i * 6 + 5] = i * 4 + 3;
406         }
407
408         for (i = 0;i < (POLYGONELEMENTS_MAXPOINTS - 2)*3;i++)
409                 polygonelement3i[i] = polygonelement3s[i];
410         for (i = 0;i < QUADELEMENTS_MAXQUADS*6;i++)
411                 quadelement3i[i] = quadelement3s[i];
412
413         Cvar_RegisterVariable(&r_render);
414         Cvar_RegisterVariable(&r_renderview);
415         Cvar_RegisterVariable(&r_waterwarp);
416         Cvar_RegisterVariable(&gl_polyblend);
417         Cvar_RegisterVariable(&v_flipped);
418         Cvar_RegisterVariable(&gl_dither);
419         Cvar_RegisterVariable(&gl_paranoid);
420         Cvar_RegisterVariable(&gl_printcheckerror);
421
422         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");
423
424         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, gl_backend_devicelost, gl_backend_devicerestored);
425 }
426
427 void GL_SetMirrorState(qboolean state);
428
429 void R_Viewport_TransformToScreen(const r_viewport_t *v, const vec4_t in, vec4_t out)
430 {
431         vec4_t temp;
432         float iw;
433         Matrix4x4_Transform4 (&v->viewmatrix, in, temp);
434         Matrix4x4_Transform4 (&v->projectmatrix, temp, out);
435         iw = 1.0f / out[3];
436         out[0] = v->x + (out[0] * iw + 1.0f) * v->width * 0.5f;
437
438         // for an odd reason, inverting this is wrong for R_Shadow_ScissorForBBox (we then get badly scissored lights)
439         //out[1] = v->y + v->height - (out[1] * iw + 1.0f) * v->height * 0.5f;
440         out[1] = v->y + (out[1] * iw + 1.0f) * v->height * 0.5f;
441
442         out[2] = v->z + (out[2] * iw + 1.0f) * v->depth * 0.5f;
443 }
444
445 void GL_Finish(void)
446 {
447         switch(vid.renderpath)
448         {
449         case RENDERPATH_GL20:
450         case RENDERPATH_GLES2:
451                 qglFinish();
452                 break;
453         }
454 }
455
456 static int bboxedges[12][2] =
457 {
458         // top
459         {0, 1}, // +X
460         {0, 2}, // +Y
461         {1, 3}, // Y, +X
462         {2, 3}, // X, +Y
463         // bottom
464         {4, 5}, // +X
465         {4, 6}, // +Y
466         {5, 7}, // Y, +X
467         {6, 7}, // X, +Y
468         // verticals
469         {0, 4}, // +Z
470         {1, 5}, // X, +Z
471         {2, 6}, // Y, +Z
472         {3, 7}, // XY, +Z
473 };
474
475 qboolean R_ScissorForBBox(const float *mins, const float *maxs, int *scissor)
476 {
477         int i, ix1, iy1, ix2, iy2;
478         float x1, y1, x2, y2;
479         vec4_t v, v2;
480         float vertex[20][3];
481         int j, k;
482         vec4_t plane4f;
483         int numvertices;
484         float corner[8][4];
485         float dist[8];
486         int sign[8];
487         float f;
488
489         scissor[0] = r_refdef.view.viewport.x;
490         scissor[1] = r_refdef.view.viewport.y;
491         scissor[2] = r_refdef.view.viewport.width;
492         scissor[3] = r_refdef.view.viewport.height;
493
494         // if view is inside the box, just say yes it's visible
495         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
496                 return false;
497
498         // transform all corners that are infront of the nearclip plane
499         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
500         plane4f[3] = r_refdef.view.frustum[4].dist;
501         numvertices = 0;
502         for (i = 0;i < 8;i++)
503         {
504                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
505                 dist[i] = DotProduct4(corner[i], plane4f);
506                 sign[i] = dist[i] > 0;
507                 if (!sign[i])
508                 {
509                         VectorCopy(corner[i], vertex[numvertices]);
510                         numvertices++;
511                 }
512         }
513         // if some points are behind the nearclip, add clipped edge points to make
514         // sure that the scissor boundary is complete
515         if (numvertices > 0 && numvertices < 8)
516         {
517                 // add clipped edge points
518                 for (i = 0;i < 12;i++)
519                 {
520                         j = bboxedges[i][0];
521                         k = bboxedges[i][1];
522                         if (sign[j] != sign[k])
523                         {
524                                 f = dist[j] / (dist[j] - dist[k]);
525                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
526                                 numvertices++;
527                         }
528                 }
529         }
530
531         // if we have no points to check, it is behind the view plane
532         if (!numvertices)
533                 return true;
534
535         // if we have some points to transform, check what screen area is covered
536         x1 = y1 = x2 = y2 = 0;
537         v[3] = 1.0f;
538         //Con_Printf("%i vertices to transform...\n", numvertices);
539         for (i = 0;i < numvertices;i++)
540         {
541                 VectorCopy(vertex[i], v);
542                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
543                 //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]);
544                 if (i)
545                 {
546                         if (x1 > v2[0]) x1 = v2[0];
547                         if (x2 < v2[0]) x2 = v2[0];
548                         if (y1 > v2[1]) y1 = v2[1];
549                         if (y2 < v2[1]) y2 = v2[1];
550                 }
551                 else
552                 {
553                         x1 = x2 = v2[0];
554                         y1 = y2 = v2[1];
555                 }
556         }
557
558         // now convert the scissor rectangle to integer screen coordinates
559         ix1 = (int)(x1 - 1.0f);
560         //iy1 = vid.height - (int)(y2 - 1.0f);
561         //iy1 = r_refdef.view.viewport.width + 2 * r_refdef.view.viewport.x - (int)(y2 - 1.0f);
562         iy1 = (int)(y1 - 1.0f);
563         ix2 = (int)(x2 + 1.0f);
564         //iy2 = vid.height - (int)(y1 + 1.0f);
565         //iy2 = r_refdef.view.viewport.height + 2 * r_refdef.view.viewport.y - (int)(y1 + 1.0f);
566         iy2 = (int)(y2 + 1.0f);
567         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
568
569         // clamp it to the screen
570         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
571         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
572         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
573         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
574
575         // if it is inside out, it's not visible
576         if (ix2 <= ix1 || iy2 <= iy1)
577                 return true;
578
579         // the light area is visible, set up the scissor rectangle
580         scissor[0] = ix1;
581         scissor[1] = iy1;
582         scissor[2] = ix2 - ix1;
583         scissor[3] = iy2 - iy1;
584
585         // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
586         switch(vid.renderpath)
587         {
588         case RENDERPATH_GL20:
589         case RENDERPATH_GLES2:
590                 break;
591         }
592
593         return false;
594 }
595
596
597 static void R_Viewport_ApplyNearClipPlaneFloatGL(const r_viewport_t *v, float *m, float normalx, float normaly, float normalz, float dist)
598 {
599         float q[4];
600         float d;
601         float clipPlane[4], v3[3], v4[3];
602         float normal[3];
603
604         // This is inspired by Oblique Depth Projection from http://www.terathon.com/code/oblique.php
605
606         VectorSet(normal, normalx, normaly, normalz);
607         Matrix4x4_Transform3x3(&v->viewmatrix, normal, clipPlane);
608         VectorScale(normal, -dist, v3);
609         Matrix4x4_Transform(&v->viewmatrix, v3, v4);
610         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
611         clipPlane[3] = -DotProduct(v4, clipPlane);
612
613 #if 0
614 {
615         // testing code for comparing results
616         float clipPlane2[4];
617         VectorCopy4(clipPlane, clipPlane2);
618         R_EntityMatrix(&identitymatrix);
619         VectorSet(q, normal[0], normal[1], normal[2], -dist);
620         qglClipPlane(GL_CLIP_PLANE0, q);
621         qglGetClipPlane(GL_CLIP_PLANE0, q);
622         VectorCopy4(q, clipPlane);
623 }
624 #endif
625
626         // Calculate the clip-space corner point opposite the clipping plane
627         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
628         // transform it into camera space by multiplying it
629         // by the inverse of the projection matrix
630         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + m[8]) / m[0];
631         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + m[9]) / m[5];
632         q[2] = -1.0f;
633         q[3] = (1.0f + m[10]) / m[14];
634
635         // Calculate the scaled plane vector
636         d = 2.0f / DotProduct4(clipPlane, q);
637
638         // Replace the third row of the projection matrix
639         m[2] = clipPlane[0] * d;
640         m[6] = clipPlane[1] * d;
641         m[10] = clipPlane[2] * d + 1.0f;
642         m[14] = clipPlane[3] * d;
643 }
644
645 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)
646 {
647         float left = x1, right = x2, bottom = y2, top = y1, zNear = nearclip, zFar = farclip;
648         float m[16];
649         memset(v, 0, sizeof(*v));
650         v->type = R_VIEWPORTTYPE_ORTHO;
651         v->cameramatrix = *cameramatrix;
652         v->x = x;
653         v->y = y;
654         v->z = 0;
655         v->width = width;
656         v->height = height;
657         v->depth = 1;
658         memset(m, 0, sizeof(m));
659         m[0]  = 2/(right - left);
660         m[5]  = 2/(top - bottom);
661         m[10] = -2/(zFar - zNear);
662         m[12] = - (right + left)/(right - left);
663         m[13] = - (top + bottom)/(top - bottom);
664         m[14] = - (zFar + zNear)/(zFar - zNear);
665         m[15] = 1;
666         switch(vid.renderpath)
667         {
668         case RENDERPATH_GL20:
669         case RENDERPATH_GLES2:
670                 break;
671         }
672         v->screentodepth[0] = -farclip / (farclip - nearclip);
673         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
674
675         Matrix4x4_Invert_Full(&v->viewmatrix, &v->cameramatrix);
676
677         if (nearplane)
678                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
679
680         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
681
682 #if 0
683         {
684                 vec4_t test1;
685                 vec4_t test2;
686                 Vector4Set(test1, (x1+x2)*0.5f, (y1+y2)*0.5f, 0.0f, 1.0f);
687                 R_Viewport_TransformToScreen(v, test1, test2);
688                 Con_Printf("%f %f %f -> %f %f %f\n", test1[0], test1[1], test1[2], test2[0], test2[1], test2[2]);
689         }
690 #endif
691 }
692
693 void R_Viewport_InitOrtho3D(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)
694 {
695         matrix4x4_t tempmatrix, basematrix;
696         float m[16];
697         memset(v, 0, sizeof(*v));
698
699         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
700         v->cameramatrix = *cameramatrix;
701         v->x = x;
702         v->y = y;
703         v->z = 0;
704         v->width = width;
705         v->height = height;
706         v->depth = 1;
707         memset(m, 0, sizeof(m));
708         m[0]  = 1.0 / frustumx;
709         m[5]  = 1.0 / frustumy;
710         m[10] = -2 / (farclip - nearclip);
711         m[14] = -(farclip + nearclip) / (farclip - nearclip);
712         m[15] = 1;
713         v->screentodepth[0] = -farclip / (farclip - nearclip);
714         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
715
716         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
717         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
718         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
719         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
720
721         if (nearplane)
722                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
723
724         if(v_flipped.integer)
725         {
726                 m[0] = -m[0];
727                 m[4] = -m[4];
728                 m[8] = -m[8];
729                 m[12] = -m[12];
730         }
731
732         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
733 }
734
735 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)
736 {
737         matrix4x4_t tempmatrix, basematrix;
738         float m[16];
739         memset(v, 0, sizeof(*v));
740
741         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
742         v->cameramatrix = *cameramatrix;
743         v->x = x;
744         v->y = y;
745         v->z = 0;
746         v->width = width;
747         v->height = height;
748         v->depth = 1;
749         memset(m, 0, sizeof(m));
750         m[0]  = 1.0 / frustumx;
751         m[5]  = 1.0 / frustumy;
752         m[10] = -(farclip + nearclip) / (farclip - nearclip);
753         m[11] = -1;
754         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
755         v->screentodepth[0] = -farclip / (farclip - nearclip);
756         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
757
758         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
759         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
760         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
761         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
762
763         if (nearplane)
764                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
765
766         if(v_flipped.integer)
767         {
768                 m[0] = -m[0];
769                 m[4] = -m[4];
770                 m[8] = -m[8];
771                 m[12] = -m[12];
772         }
773
774         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
775 }
776
777 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)
778 {
779         matrix4x4_t tempmatrix, basematrix;
780         const float nudge = 1.0 - 1.0 / (1<<23);
781         float m[16];
782         memset(v, 0, sizeof(*v));
783
784         v->type = R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP;
785         v->cameramatrix = *cameramatrix;
786         v->x = x;
787         v->y = y;
788         v->z = 0;
789         v->width = width;
790         v->height = height;
791         v->depth = 1;
792         memset(m, 0, sizeof(m));
793         m[ 0] = 1.0 / frustumx;
794         m[ 5] = 1.0 / frustumy;
795         m[10] = -nudge;
796         m[11] = -1;
797         m[14] = -2 * nearclip * nudge;
798         v->screentodepth[0] = (m[10] + 1) * 0.5 - 1;
799         v->screentodepth[1] = m[14] * -0.5;
800
801         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
802         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
803         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
804         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
805
806         if (nearplane)
807                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
808
809         if(v_flipped.integer)
810         {
811                 m[0] = -m[0];
812                 m[4] = -m[4];
813                 m[8] = -m[8];
814                 m[12] = -m[12];
815         }
816
817         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
818 }
819
820 float cubeviewmatrix[6][16] =
821 {
822     // standard cubemap projections
823     { // +X
824          0, 0,-1, 0,
825          0,-1, 0, 0,
826         -1, 0, 0, 0,
827          0, 0, 0, 1,
828     },
829     { // -X
830          0, 0, 1, 0,
831          0,-1, 0, 0,
832          1, 0, 0, 0,
833          0, 0, 0, 1,
834     },
835     { // +Y
836          1, 0, 0, 0,
837          0, 0,-1, 0,
838          0, 1, 0, 0,
839          0, 0, 0, 1,
840     },
841     { // -Y
842          1, 0, 0, 0,
843          0, 0, 1, 0,
844          0,-1, 0, 0,
845          0, 0, 0, 1,
846     },
847     { // +Z
848          1, 0, 0, 0,
849          0,-1, 0, 0,
850          0, 0,-1, 0,
851          0, 0, 0, 1,
852     },
853     { // -Z
854         -1, 0, 0, 0,
855          0,-1, 0, 0,
856          0, 0, 1, 0,
857          0, 0, 0, 1,
858     },
859 };
860 float rectviewmatrix[6][16] =
861 {
862     // sign-preserving cubemap projections
863     { // +X
864          0, 0,-1, 0,
865          0, 1, 0, 0,
866          1, 0, 0, 0,
867          0, 0, 0, 1,
868     },
869     { // -X
870          0, 0, 1, 0,
871          0, 1, 0, 0,
872          1, 0, 0, 0,
873          0, 0, 0, 1,
874     },
875     { // +Y
876          1, 0, 0, 0,
877          0, 0,-1, 0,
878          0, 1, 0, 0,
879          0, 0, 0, 1,
880     },
881     { // -Y
882          1, 0, 0, 0,
883          0, 0, 1, 0,
884          0, 1, 0, 0,
885          0, 0, 0, 1,
886     },
887     { // +Z
888          1, 0, 0, 0,
889          0, 1, 0, 0,
890          0, 0,-1, 0,
891          0, 0, 0, 1,
892     },
893     { // -Z
894          1, 0, 0, 0,
895          0, 1, 0, 0,
896          0, 0, 1, 0,
897          0, 0, 0, 1,
898     },
899 };
900
901 void R_Viewport_InitCubeSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, float nearclip, float farclip, const float *nearplane)
902 {
903         matrix4x4_t tempmatrix, basematrix;
904         float m[16];
905         memset(v, 0, sizeof(*v));
906         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
907         v->cameramatrix = *cameramatrix;
908         v->width = size;
909         v->height = size;
910         v->depth = 1;
911         memset(m, 0, sizeof(m));
912         m[0] = m[5] = 1.0f;
913         m[10] = -(farclip + nearclip) / (farclip - nearclip);
914         m[11] = -1;
915         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
916
917         Matrix4x4_FromArrayFloatGL(&basematrix, cubeviewmatrix[side]);
918         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
919         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
920
921         if (nearplane)
922                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
923
924         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
925 }
926
927 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, int offsetx, int offsety)
928 {
929         matrix4x4_t tempmatrix, basematrix;
930         float m[16];
931         memset(v, 0, sizeof(*v));
932         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
933         v->cameramatrix = *cameramatrix;
934         v->x = offsetx + (side & 1) * size;
935         v->y = offsety + (side >> 1) * size;
936         v->width = size;
937         v->height = size;
938         v->depth = 1;
939         memset(m, 0, sizeof(m));
940         m[0] = m[5] = 1.0f * ((float)size - border) / size;
941         m[10] = -(farclip + nearclip) / (farclip - nearclip);
942         m[11] = -1;
943         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
944
945         Matrix4x4_FromArrayFloatGL(&basematrix, rectviewmatrix[side]);
946         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
947         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
948
949         if (nearplane)
950                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
951
952         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
953 }
954
955 void R_SetViewport(const r_viewport_t *v)
956 {
957         gl_viewport = *v;
958
959         // FIXME: v_flipped_state is evil, this probably breaks somewhere
960         GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
961
962         // copy over the matrices to our state
963         gl_viewmatrix = v->viewmatrix;
964         gl_projectionmatrix = v->projectmatrix;
965
966         switch(vid.renderpath)
967         {
968         case RENDERPATH_GL20:
969         case RENDERPATH_GLES2:
970                 CHECKGLERROR
971                 qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
972                 break;
973         }
974
975         // force an update of the derived matrices
976         gl_modelmatrixchanged = true;
977         R_EntityMatrix(&gl_modelmatrix);
978 }
979
980 void R_GetViewport(r_viewport_t *v)
981 {
982         *v = gl_viewport;
983 }
984
985 static void GL_BindVBO(int bufferobject)
986 {
987         if (gl_state.vertexbufferobject != bufferobject)
988         {
989                 gl_state.vertexbufferobject = bufferobject;
990                 CHECKGLERROR
991                 qglBindBuffer(GL_ARRAY_BUFFER, bufferobject);CHECKGLERROR
992         }
993 }
994
995 static void GL_BindEBO(int bufferobject)
996 {
997         if (gl_state.elementbufferobject != bufferobject)
998         {
999                 gl_state.elementbufferobject = bufferobject;
1000                 CHECKGLERROR
1001                 qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferobject);CHECKGLERROR
1002         }
1003 }
1004
1005 static void GL_BindUBO(int bufferobject)
1006 {
1007         if (gl_state.uniformbufferobject != bufferobject)
1008         {
1009                 gl_state.uniformbufferobject = bufferobject;
1010 #ifdef GL_UNIFORM_BUFFER
1011                 CHECKGLERROR
1012                 qglBindBuffer(GL_UNIFORM_BUFFER, bufferobject);CHECKGLERROR
1013 #endif
1014         }
1015 }
1016
1017 static const GLuint drawbuffers[4] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
1018 int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1019 {
1020         int temp;
1021         GLuint status;
1022         switch(vid.renderpath)
1023         {
1024         case RENDERPATH_GL20:
1025         case RENDERPATH_GLES2:
1026                 qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1027                 R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1028                 // GL_ARB_framebuffer_object (GL3-class hardware) - depth stencil attachment
1029 #ifdef USE_GLES2
1030                 // FIXME: separate stencil attachment on GLES
1031                 if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1032                 if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1033 #else
1034                 if (depthtexture  && depthtexture->texnum )
1035                 {
1036                         qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1037                         if (depthtexture->glisdepthstencil) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1038                 }
1039                 if (depthtexture  && depthtexture->renderbuffernum )
1040                 {
1041                         qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1042                         if (depthtexture->glisdepthstencil) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1043                 }
1044 #endif
1045                 if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1046                 if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1047                 if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1048                 if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1049                 if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1050                 if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1051                 if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1052                 if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1053
1054 #ifndef USE_GLES2
1055                 if (colortexture4 && qglDrawBuffersARB)
1056                 {
1057                         qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1058                         qglReadBuffer(GL_NONE);CHECKGLERROR
1059                 }
1060                 else if (colortexture3 && qglDrawBuffersARB)
1061                 {
1062                         qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1063                         qglReadBuffer(GL_NONE);CHECKGLERROR
1064                 }
1065                 else if (colortexture2 && qglDrawBuffersARB)
1066                 {
1067                         qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1068                         qglReadBuffer(GL_NONE);CHECKGLERROR
1069                 }
1070                 else if (colortexture && qglDrawBuffer)
1071                 {
1072                         qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1073                         qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1074                 }
1075                 else if (qglDrawBuffer)
1076                 {
1077                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1078                         qglReadBuffer(GL_NONE);CHECKGLERROR
1079                 }
1080 #endif
1081                 status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1082                 if (status != GL_FRAMEBUFFER_COMPLETE)
1083                 {
1084                         Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1085                         gl_state.framebufferobject = 0; // GL unbinds it for us
1086                         qglDeleteFramebuffers(1, (GLuint*)&temp);
1087                         temp = 0;
1088                 }
1089                 return temp;
1090         }
1091         return 0;
1092 }
1093
1094 void R_Mesh_DestroyFramebufferObject(int fbo)
1095 {
1096         switch(vid.renderpath)
1097         {
1098         case RENDERPATH_GL20:
1099         case RENDERPATH_GLES2:
1100                 if (fbo)
1101                 {
1102                         // GL clears the binding if we delete something bound
1103                         if (gl_state.framebufferobject == fbo)
1104                                 gl_state.framebufferobject = 0;
1105                         qglDeleteFramebuffers(1, (GLuint*)&fbo);
1106                 }
1107                 break;
1108         }
1109 }
1110
1111 void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1112 {
1113         unsigned int i;
1114         unsigned int j;
1115         rtexture_t *textures[5];
1116         Vector4Set(textures, colortexture, colortexture2, colortexture3, colortexture4);
1117         textures[4] = depthtexture;
1118         // unbind any matching textures immediately, otherwise D3D will complain about a bound texture being used as a render target
1119         for (j = 0;j < 5;j++)
1120                 if (textures[j])
1121                         for (i = 0;i < vid.teximageunits;i++)
1122                                 if (gl_state.units[i].texture == textures[j])
1123                                         R_Mesh_TexBind(i, NULL);
1124         // set up framebuffer object or render targets for the active rendering API
1125         switch (vid.renderpath)
1126         {
1127         case RENDERPATH_GL20:
1128         case RENDERPATH_GLES2:
1129                 if (gl_state.framebufferobject != fbo)
1130                 {
1131                         gl_state.framebufferobject = fbo;
1132                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject ? gl_state.framebufferobject : gl_state.defaultframebufferobject);
1133                 }
1134                 break;
1135         }
1136 }
1137
1138 static void GL_Backend_ResetState(void)
1139 {
1140         unsigned int i;
1141         gl_state.active = true;
1142         gl_state.depthtest = true;
1143         gl_state.alphatest = false;
1144         gl_state.alphafunc = GL_GEQUAL;
1145         gl_state.alphafuncvalue = 0.5f;
1146         gl_state.alphatocoverage = false;
1147         gl_state.blendfunc1 = GL_ONE;
1148         gl_state.blendfunc2 = GL_ZERO;
1149         gl_state.blend = false;
1150         gl_state.depthmask = GL_TRUE;
1151         gl_state.colormask = 15;
1152         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
1153         gl_state.lockrange_first = 0;
1154         gl_state.lockrange_count = 0;
1155         gl_state.cullface = GL_FRONT;
1156         gl_state.cullfaceenable = false;
1157         gl_state.polygonoffset[0] = 0;
1158         gl_state.polygonoffset[1] = 0;
1159         gl_state.framebufferobject = 0;
1160         gl_state.depthfunc = GL_LEQUAL;
1161
1162         switch(vid.renderpath)
1163         {
1164         case RENDERPATH_GL20:
1165         case RENDERPATH_GLES2:
1166                 CHECKGLERROR
1167                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1168                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1169                 qglDisable(GL_BLEND);CHECKGLERROR
1170                 qglCullFace(gl_state.cullface);CHECKGLERROR
1171                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1172                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1173                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1174                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1175                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1176                 qglBindBuffer(GL_ARRAY_BUFFER, 0);
1177                 qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1178                 qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.defaultframebufferobject);
1179                 qglEnableVertexAttribArray(GLSLATTRIB_POSITION);
1180                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);
1181                 qglVertexAttrib4f(GLSLATTRIB_COLOR, 1, 1, 1, 1);
1182                 gl_state.unit = MAX_TEXTUREUNITS;
1183                 gl_state.clientunit = MAX_TEXTUREUNITS;
1184                 for (i = 0;i < vid.teximageunits;i++)
1185                 {
1186                         GL_ActiveTexture(i);
1187                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1188                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1189                         qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1190                 }
1191                 for (i = 0;i < vid.texarrayunits;i++)
1192                 {
1193                         GL_BindVBO(0);
1194                         qglDisableVertexAttribArray(i+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
1195                 }
1196                 CHECKGLERROR
1197                 break;
1198         }
1199 }
1200
1201 void GL_ActiveTexture(unsigned int num)
1202 {
1203         if (gl_state.unit != num)
1204         {
1205                 gl_state.unit = num;
1206                 switch(vid.renderpath)
1207                 {
1208                 case RENDERPATH_GL20:
1209                 case RENDERPATH_GLES2:
1210                         CHECKGLERROR
1211                         qglActiveTexture(GL_TEXTURE0 + gl_state.unit);
1212                         CHECKGLERROR
1213                         break;
1214                 }
1215         }
1216 }
1217
1218 void GL_BlendFunc(int blendfunc1, int blendfunc2)
1219 {
1220         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
1221         {
1222                 qboolean blendenable;
1223                 gl_state.blendfunc1 = blendfunc1;
1224                 gl_state.blendfunc2 = blendfunc2;
1225                 blendenable = (gl_state.blendfunc1 != GL_ONE || gl_state.blendfunc2 != GL_ZERO);
1226                 switch(vid.renderpath)
1227                 {
1228                 case RENDERPATH_GL20:
1229                 case RENDERPATH_GLES2:
1230                         CHECKGLERROR
1231                         if (qglBlendFuncSeparate)
1232                         {
1233                                 qglBlendFuncSeparate(gl_state.blendfunc1, gl_state.blendfunc2, GL_ZERO, GL_ONE);CHECKGLERROR // ELUAN: Adreno 225 (and others) compositing workaround
1234                         }
1235                         else
1236                         {
1237                                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1238                         }
1239                         if (gl_state.blend != blendenable)
1240                         {
1241                                 gl_state.blend = blendenable;
1242                                 if (!gl_state.blend)
1243                                 {
1244                                         qglDisable(GL_BLEND);CHECKGLERROR
1245                                 }
1246                                 else
1247                                 {
1248                                         qglEnable(GL_BLEND);CHECKGLERROR
1249                                 }
1250                         }
1251                         break;
1252                 }
1253         }
1254 }
1255
1256 void GL_DepthMask(int state)
1257 {
1258         if (gl_state.depthmask != state)
1259         {
1260                 gl_state.depthmask = state;
1261                 switch(vid.renderpath)
1262                 {
1263                 case RENDERPATH_GL20:
1264                 case RENDERPATH_GLES2:
1265                         CHECKGLERROR
1266                         qglDepthMask(gl_state.depthmask);CHECKGLERROR
1267                         break;
1268                 }
1269         }
1270 }
1271
1272 void GL_DepthTest(int state)
1273 {
1274         if (gl_state.depthtest != state)
1275         {
1276                 gl_state.depthtest = state;
1277                 switch(vid.renderpath)
1278                 {
1279                 case RENDERPATH_GL20:
1280                 case RENDERPATH_GLES2:
1281                         CHECKGLERROR
1282                         if (gl_state.depthtest)
1283                         {
1284                                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1285                         }
1286                         else
1287                         {
1288                                 qglDisable(GL_DEPTH_TEST);CHECKGLERROR
1289                         }
1290                         break;
1291                 }
1292         }
1293 }
1294
1295 void GL_DepthFunc(int state)
1296 {
1297         if (gl_state.depthfunc != state)
1298         {
1299                 gl_state.depthfunc = state;
1300                 switch(vid.renderpath)
1301                 {
1302                 case RENDERPATH_GL20:
1303                 case RENDERPATH_GLES2:
1304                         CHECKGLERROR
1305                         qglDepthFunc(gl_state.depthfunc);CHECKGLERROR
1306                         break;
1307                 }
1308         }
1309 }
1310
1311 void GL_DepthRange(float nearfrac, float farfrac)
1312 {
1313         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
1314         {
1315                 gl_state.depthrange[0] = nearfrac;
1316                 gl_state.depthrange[1] = farfrac;
1317                 switch(vid.renderpath)
1318                 {
1319                 case RENDERPATH_GL20:
1320                 case RENDERPATH_GLES2:
1321 #ifdef USE_GLES2
1322                         qglDepthRangef(gl_state.depthrange[0], gl_state.depthrange[1]);
1323 #else
1324                         qglDepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
1325 #endif
1326                         break;
1327                 }
1328         }
1329 }
1330
1331 void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask)
1332 {
1333         switch (vid.renderpath)
1334         {
1335         case RENDERPATH_GL20:
1336         case RENDERPATH_GLES2:
1337                 CHECKGLERROR
1338                 if (enable)
1339                 {
1340                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1341                 }
1342                 else
1343                 {
1344                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1345                 }
1346                 qglStencilMask(writemask);CHECKGLERROR
1347                 qglStencilOp(fail, zfail, zpass);CHECKGLERROR
1348                 qglStencilFunc(compare, comparereference, comparemask);CHECKGLERROR
1349                 CHECKGLERROR
1350                 break;
1351         }
1352 }
1353
1354 void GL_PolygonOffset(float planeoffset, float depthoffset)
1355 {
1356         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
1357         {
1358                 gl_state.polygonoffset[0] = planeoffset;
1359                 gl_state.polygonoffset[1] = depthoffset;
1360                 switch(vid.renderpath)
1361                 {
1362                 case RENDERPATH_GL20:
1363                 case RENDERPATH_GLES2:
1364                         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1365                         break;
1366                 }
1367         }
1368 }
1369
1370 void GL_SetMirrorState(qboolean state)
1371 {
1372         if (v_flipped_state != state)
1373         {
1374                 v_flipped_state = state;
1375                 if (gl_state.cullface == GL_BACK)
1376                         gl_state.cullface = GL_FRONT;
1377                 else if (gl_state.cullface == GL_FRONT)
1378                         gl_state.cullface = GL_BACK;
1379                 else
1380                         return;
1381                 switch(vid.renderpath)
1382                 {
1383                 case RENDERPATH_GL20:
1384                 case RENDERPATH_GLES2:
1385                         qglCullFace(gl_state.cullface);CHECKGLERROR
1386                         break;
1387                 }
1388         }
1389 }
1390
1391 void GL_CullFace(int state)
1392 {
1393         if(v_flipped_state)
1394         {
1395                 if(state == GL_FRONT)
1396                         state = GL_BACK;
1397                 else if(state == GL_BACK)
1398                         state = GL_FRONT;
1399         }
1400
1401         switch(vid.renderpath)
1402         {
1403         case RENDERPATH_GL20:
1404         case RENDERPATH_GLES2:
1405                 CHECKGLERROR
1406
1407                 if (state != GL_NONE)
1408                 {
1409                         if (!gl_state.cullfaceenable)
1410                         {
1411                                 gl_state.cullfaceenable = true;
1412                                 qglEnable(GL_CULL_FACE);CHECKGLERROR
1413                         }
1414                         if (gl_state.cullface != state)
1415                         {
1416                                 gl_state.cullface = state;
1417                                 qglCullFace(gl_state.cullface);CHECKGLERROR
1418                         }
1419                 }
1420                 else
1421                 {
1422                         if (gl_state.cullfaceenable)
1423                         {
1424                                 gl_state.cullfaceenable = false;
1425                                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1426                         }
1427                 }
1428                 break;
1429         }
1430 }
1431
1432 void GL_AlphaToCoverage(qboolean state)
1433 {
1434         if (gl_state.alphatocoverage != state)
1435         {
1436                 gl_state.alphatocoverage = state;
1437                 switch(vid.renderpath)
1438                 {
1439                 case RENDERPATH_GLES2:
1440                         break;
1441                 case RENDERPATH_GL20:
1442 #ifdef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
1443                         // alpha to coverage turns the alpha value of the pixel into 0%, 25%, 50%, 75% or 100% by masking the multisample fragments accordingly
1444                         CHECKGLERROR
1445                         if (gl_state.alphatocoverage)
1446                         {
1447                                 qglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
1448 //                              qglEnable(GL_MULTISAMPLE_ARB);CHECKGLERROR
1449                         }
1450                         else
1451                         {
1452                                 qglDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
1453 //                              qglDisable(GL_MULTISAMPLE_ARB);CHECKGLERROR
1454                         }
1455 #endif
1456                         break;
1457                 }
1458         }
1459 }
1460
1461 void GL_ColorMask(int r, int g, int b, int a)
1462 {
1463         // NOTE: this matches D3DCOLORWRITEENABLE_RED, GREEN, BLUE, ALPHA
1464         int state = (r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0);
1465         if (gl_state.colormask != state)
1466         {
1467                 gl_state.colormask = state;
1468                 switch(vid.renderpath)
1469                 {
1470                 case RENDERPATH_GL20:
1471                 case RENDERPATH_GLES2:
1472                         CHECKGLERROR
1473                         qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
1474                         break;
1475                 }
1476         }
1477 }
1478
1479 void GL_Color(float cr, float cg, float cb, float ca)
1480 {
1481         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)
1482         {
1483                 gl_state.color4f[0] = cr;
1484                 gl_state.color4f[1] = cg;
1485                 gl_state.color4f[2] = cb;
1486                 gl_state.color4f[3] = ca;
1487                 switch(vid.renderpath)
1488                 {
1489                 case RENDERPATH_GL20:
1490                 case RENDERPATH_GLES2:
1491                         qglVertexAttrib4f(GLSLATTRIB_COLOR, cr, cg, cb, ca);
1492                         break;
1493                 }
1494         }
1495 }
1496
1497 void GL_Scissor (int x, int y, int width, int height)
1498 {
1499         switch(vid.renderpath)
1500         {
1501         case RENDERPATH_GL20:
1502         case RENDERPATH_GLES2:
1503                 CHECKGLERROR
1504                 qglScissor(x, y,width,height);
1505                 CHECKGLERROR
1506                 break;
1507         }
1508 }
1509
1510 void GL_ScissorTest(int state)
1511 {
1512         if (gl_state.scissortest != state)
1513         {
1514                 gl_state.scissortest = state;
1515                 switch(vid.renderpath)
1516                 {
1517                 case RENDERPATH_GL20:
1518                 case RENDERPATH_GLES2:
1519                         CHECKGLERROR
1520                         if(gl_state.scissortest)
1521                                 qglEnable(GL_SCISSOR_TEST);
1522                         else
1523                                 qglDisable(GL_SCISSOR_TEST);
1524                         CHECKGLERROR
1525                         break;
1526                 }
1527         }
1528 }
1529
1530 void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue)
1531 {
1532         // opaque black - if you want transparent black, you'll need to pass in a colorvalue
1533         static const float blackcolor[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1534         // prevent warnings when trying to clear a buffer that does not exist
1535         if (!colorvalue)
1536                 colorvalue = blackcolor;
1537         if (!vid.stencil)
1538         {
1539                 mask &= ~GL_STENCIL_BUFFER_BIT;
1540                 stencilvalue = 0;
1541         }
1542         switch(vid.renderpath)
1543         {
1544         case RENDERPATH_GL20:
1545         case RENDERPATH_GLES2:
1546                 CHECKGLERROR
1547                 if (mask & GL_COLOR_BUFFER_BIT)
1548                 {
1549                         qglClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);CHECKGLERROR
1550                 }
1551                 if (mask & GL_DEPTH_BUFFER_BIT)
1552                 {
1553 #ifdef USE_GLES2
1554                         qglClearDepthf(depthvalue);CHECKGLERROR
1555 #else
1556                         qglClearDepth(depthvalue);CHECKGLERROR
1557 #endif
1558                 }
1559                 if (mask & GL_STENCIL_BUFFER_BIT)
1560                 {
1561                         qglClearStencil(stencilvalue);CHECKGLERROR
1562                 }
1563                 qglClear(mask);CHECKGLERROR
1564                 break;
1565         }
1566 }
1567
1568 void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels)
1569 {
1570         switch(vid.renderpath)
1571         {
1572         case RENDERPATH_GL20:
1573         case RENDERPATH_GLES2:
1574                 CHECKGLERROR
1575 #ifndef GL_BGRA
1576                 {
1577                         int i;
1578                         int r;
1579                 //      int g;
1580                         int b;
1581                 //      int a;
1582                         qglReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
1583                         for (i = 0;i < width * height * 4;i += 4)
1584                         {
1585                                 r = outpixels[i+0];
1586                 //              g = outpixels[i+1];
1587                                 b = outpixels[i+2];
1588                 //              a = outpixels[i+3];
1589                                 outpixels[i+0] = b;
1590                 //              outpixels[i+1] = g;
1591                                 outpixels[i+2] = r;
1592                 //              outpixels[i+3] = a;
1593                         }
1594                 }
1595 #else
1596                 qglReadPixels(x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
1597 #endif
1598                         break;
1599         }
1600 }
1601
1602 // called at beginning of frame
1603 void R_Mesh_Start(void)
1604 {
1605         BACKENDACTIVECHECK
1606         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
1607         if (gl_printcheckerror.integer && !gl_paranoid.integer)
1608         {
1609                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
1610                 Cvar_SetValueQuick(&gl_paranoid, 1);
1611         }
1612 }
1613
1614 static qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
1615 {
1616         int shaderobject;
1617         int shadercompiled;
1618         char compilelog[MAX_INPUTLINE];
1619         shaderobject = qglCreateShader(shadertypeenum);CHECKGLERROR
1620         if (!shaderobject)
1621                 return false;
1622         qglShaderSource(shaderobject, numstrings, strings, NULL);CHECKGLERROR
1623         qglCompileShader(shaderobject);CHECKGLERROR
1624         qglGetShaderiv(shaderobject, GL_COMPILE_STATUS, &shadercompiled);CHECKGLERROR
1625         qglGetShaderInfoLog(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
1626         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))
1627         {
1628                 int i, j, pretextlines = 0;
1629                 for (i = 0;i < numstrings - 1;i++)
1630                         for (j = 0;strings[i][j];j++)
1631                                 if (strings[i][j] == '\n')
1632                                         pretextlines++;
1633                 Con_Printf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
1634         }
1635         if (!shadercompiled)
1636         {
1637                 qglDeleteShader(shaderobject);CHECKGLERROR
1638                 return false;
1639         }
1640         qglAttachShader(programobject, shaderobject);CHECKGLERROR
1641         qglDeleteShader(shaderobject);CHECKGLERROR
1642         return true;
1643 }
1644
1645 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)
1646 {
1647         GLint programlinked;
1648         GLuint programobject = 0;
1649         char linklog[MAX_INPUTLINE];
1650         CHECKGLERROR
1651
1652         programobject = qglCreateProgram();CHECKGLERROR
1653         if (!programobject)
1654                 return 0;
1655
1656         qglBindAttribLocation(programobject, GLSLATTRIB_POSITION , "Attrib_Position" );
1657         qglBindAttribLocation(programobject, GLSLATTRIB_COLOR    , "Attrib_Color"    );
1658         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD0, "Attrib_TexCoord0");
1659         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD1, "Attrib_TexCoord1");
1660         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD2, "Attrib_TexCoord2");
1661         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD3, "Attrib_TexCoord3");
1662         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD4, "Attrib_TexCoord4");
1663         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD5, "Attrib_TexCoord5");
1664         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD6, "Attrib_SkeletalIndex");
1665         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD7, "Attrib_SkeletalWeight");
1666 #ifndef USE_GLES2
1667         if(vid.support.gl20shaders130)
1668                 qglBindFragDataLocation(programobject, 0, "dp_FragColor");
1669 #endif
1670
1671         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER, "vertex", vertexstrings_count, vertexstrings_list))
1672                 goto cleanup;
1673
1674 #if defined(GL_GEOMETRY_SHADER) && !defined(USE_GLES2)
1675         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER, "geometry", geometrystrings_count, geometrystrings_list))
1676                 goto cleanup;
1677 #endif
1678
1679         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER, "fragment", fragmentstrings_count, fragmentstrings_list))
1680                 goto cleanup;
1681
1682         qglLinkProgram(programobject);CHECKGLERROR
1683         qglGetProgramiv(programobject, GL_LINK_STATUS, &programlinked);CHECKGLERROR
1684         qglGetProgramInfoLog(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
1685
1686         if (linklog[0])
1687         {
1688
1689                 if (strstr(linklog, "error") || strstr(linklog, "ERROR") || strstr(linklog, "Error") || strstr(linklog, "WARNING") || strstr(linklog, "warning") || strstr(linklog, "Warning") || developer_extra.integer)
1690                         Con_DPrintf("program link log:\n%s\n", linklog);
1691
1692                 // software vertex shader is ok but software fragment shader is WAY
1693                 // too slow, fail program if so.
1694                 // NOTE: this string might be ATI specific, but that's ok because the
1695                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
1696                 // software fragment shader due to low instruction and dependent
1697                 // texture limits.
1698                 if (strstr(linklog, "fragment shader will run in software"))
1699                         programlinked = false;
1700         }
1701
1702         if (!programlinked)
1703                 goto cleanup;
1704
1705         return programobject;
1706 cleanup:
1707         qglDeleteProgram(programobject);CHECKGLERROR
1708         return 0;
1709 }
1710
1711 void GL_Backend_FreeProgram(unsigned int prog)
1712 {
1713         CHECKGLERROR
1714         qglDeleteProgram(prog);
1715         CHECKGLERROR
1716 }
1717
1718 // renders triangles using vertices from the active arrays
1719 void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const r_meshbuffer_t *element3i_indexbuffer, int element3i_bufferoffset, const unsigned short *element3s, const r_meshbuffer_t *element3s_indexbuffer, int element3s_bufferoffset)
1720 {
1721         unsigned int numelements = numtriangles * 3;
1722         int bufferobject3i;
1723         size_t bufferoffset3i;
1724         int bufferobject3s;
1725         size_t bufferoffset3s;
1726         if (numvertices < 3 || numtriangles < 1)
1727         {
1728                 if (numvertices < 0 || numtriangles < 0 || developer_extra.integer)
1729                         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);
1730                 return;
1731         }
1732         // adjust the pointers for firsttriangle
1733         if (element3i)
1734                 element3i += firsttriangle * 3;
1735         if (element3i_indexbuffer)
1736                 element3i_bufferoffset += firsttriangle * 3 * sizeof(*element3i);
1737         if (element3s)
1738                 element3s += firsttriangle * 3;
1739         if (element3s_indexbuffer)
1740                 element3s_bufferoffset += firsttriangle * 3 * sizeof(*element3s);
1741         // upload a dynamic index buffer if needed
1742         if (element3s)
1743         {
1744                 if (!element3s_indexbuffer)
1745                         element3s_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3s), (void *)element3s, R_BUFFERDATA_INDEX16, &element3s_bufferoffset);
1746         }
1747         else if (element3i)
1748         {
1749                 if (!element3i_indexbuffer)
1750                         element3i_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3i), (void *)element3i, R_BUFFERDATA_INDEX32, &element3i_bufferoffset);
1751         }
1752         bufferobject3i = element3i_indexbuffer ? element3i_indexbuffer->bufferobject : 0;
1753         bufferoffset3i = element3i_bufferoffset;
1754         bufferobject3s = element3s_indexbuffer ? element3s_indexbuffer->bufferobject : 0;
1755         bufferoffset3s = element3s_bufferoffset;
1756         r_refdef.stats[r_stat_draws]++;
1757         r_refdef.stats[r_stat_draws_vertices] += numvertices;
1758         r_refdef.stats[r_stat_draws_elements] += numelements;
1759         if (gl_paranoid.integer)
1760         {
1761                 unsigned int i;
1762                 if (element3i)
1763                 {
1764                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1765                         {
1766                                 if (element3i[i] < firstvertex || element3i[i] >= firstvertex + numvertices)
1767                                 {
1768                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3i array\n", element3i[i], firstvertex, firstvertex + numvertices);
1769                                         return;
1770                                 }
1771                         }
1772                 }
1773                 if (element3s)
1774                 {
1775                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1776                         {
1777                                 if (element3s[i] < firstvertex || element3s[i] >= firstvertex + numvertices)
1778                                 {
1779                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3s array\n", element3s[i], firstvertex, firstvertex + numvertices);
1780                                         return;
1781                                 }
1782                         }
1783                 }
1784         }
1785         if (r_render.integer || r_refdef.draw2dstage)
1786         {
1787                 switch(vid.renderpath)
1788                 {
1789                 case RENDERPATH_GL20:
1790                 case RENDERPATH_GLES2:
1791                         CHECKGLERROR
1792                         if (bufferobject3s)
1793                         {
1794                                 GL_BindEBO(bufferobject3s);
1795                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, (void *)bufferoffset3s);CHECKGLERROR
1796                         }
1797                         else if (bufferobject3i)
1798                         {
1799                                 GL_BindEBO(bufferobject3i);
1800                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (void *)bufferoffset3i);CHECKGLERROR
1801                         }
1802                         else
1803                         {
1804                                 qglDrawArrays(GL_TRIANGLES, firstvertex, numvertices);CHECKGLERROR
1805                         }
1806                         break;
1807                 }
1808         }
1809 }
1810
1811 // restores backend state, used when done with 3D rendering
1812 void R_Mesh_Finish(void)
1813 {
1814         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
1815 }
1816
1817 r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isuniformbuffer, qboolean isdynamic, qboolean isindex16)
1818 {
1819         r_meshbuffer_t *buffer;
1820         buffer = (r_meshbuffer_t *)Mem_ExpandableArray_AllocRecord(&gl_state.meshbufferarray);
1821         memset(buffer, 0, sizeof(*buffer));
1822         buffer->bufferobject = 0;
1823         buffer->devicebuffer = NULL;
1824         buffer->size = size;
1825         buffer->isindexbuffer = isindexbuffer;
1826         buffer->isuniformbuffer = isuniformbuffer;
1827         buffer->isdynamic = isdynamic;
1828         buffer->isindex16 = isindex16;
1829         strlcpy(buffer->name, name, sizeof(buffer->name));
1830         R_Mesh_UpdateMeshBuffer(buffer, data, size, false, 0);
1831         return buffer;
1832 }
1833
1834 void R_Mesh_UpdateMeshBuffer(r_meshbuffer_t *buffer, const void *data, size_t size, qboolean subdata, size_t offset)
1835 {
1836         if (!buffer)
1837                 return;
1838         if (buffer->isindexbuffer)
1839         {
1840                 r_refdef.stats[r_stat_indexbufferuploadcount]++;
1841                 r_refdef.stats[r_stat_indexbufferuploadsize] += (int)size;
1842         }
1843         else
1844         {
1845                 r_refdef.stats[r_stat_vertexbufferuploadcount]++;
1846                 r_refdef.stats[r_stat_vertexbufferuploadsize] += (int)size;
1847         }
1848         if (!subdata)
1849                 buffer->size = size;
1850         switch(vid.renderpath)
1851         {
1852         case RENDERPATH_GL20:
1853         case RENDERPATH_GLES2:
1854                 if (!buffer->bufferobject)
1855                         qglGenBuffers(1, (GLuint *)&buffer->bufferobject);
1856                 if (buffer->isuniformbuffer)
1857                         GL_BindUBO(buffer->bufferobject);
1858                 else if (buffer->isindexbuffer)
1859                         GL_BindEBO(buffer->bufferobject);
1860                 else
1861                         GL_BindVBO(buffer->bufferobject);
1862
1863                 {
1864                         int buffertype;
1865                         buffertype = buffer->isindexbuffer ? GL_ELEMENT_ARRAY_BUFFER : GL_ARRAY_BUFFER;
1866 #ifdef GL_UNIFORM_BUFFER
1867                         if (buffer->isuniformbuffer)
1868                                 buffertype = GL_UNIFORM_BUFFER;
1869 #endif
1870                         if (subdata)
1871                                 qglBufferSubData(buffertype, offset, size, data);
1872                         else
1873                                 qglBufferData(buffertype, size, data, buffer->isdynamic ? GL_STREAM_DRAW : GL_STATIC_DRAW);
1874                 }
1875                 if (buffer->isuniformbuffer)
1876                         GL_BindUBO(0);
1877                 break;
1878         }
1879 }
1880
1881 void R_Mesh_DestroyMeshBuffer(r_meshbuffer_t *buffer)
1882 {
1883         if (!buffer)
1884                 return;
1885         switch(vid.renderpath)
1886         {
1887         case RENDERPATH_GL20:
1888         case RENDERPATH_GLES2:
1889                 // GL clears the binding if we delete something bound
1890                 if (gl_state.uniformbufferobject == buffer->bufferobject)
1891                         gl_state.uniformbufferobject = 0;
1892                 if (gl_state.vertexbufferobject == buffer->bufferobject)
1893                         gl_state.vertexbufferobject = 0;
1894                 if (gl_state.elementbufferobject == buffer->bufferobject)
1895                         gl_state.elementbufferobject = 0;
1896                 qglDeleteBuffers(1, (GLuint *)&buffer->bufferobject);
1897                 break;
1898         }
1899         Mem_ExpandableArray_FreeRecord(&gl_state.meshbufferarray, (void *)buffer);
1900 }
1901
1902 static const char *buffertypename[R_BUFFERDATA_COUNT] = {"vertex", "index16", "index32", "uniform"};
1903 void GL_Mesh_ListVBOs(qboolean printeach)
1904 {
1905         int i, endindex;
1906         int type;
1907         int isdynamic;
1908         int index16count, index16mem;
1909         int index32count, index32mem;
1910         int vertexcount, vertexmem;
1911         int uniformcount, uniformmem;
1912         int totalcount, totalmem;
1913         size_t bufferstat[R_BUFFERDATA_COUNT][2][2];
1914         r_meshbuffer_t *buffer;
1915         memset(bufferstat, 0, sizeof(bufferstat));
1916         endindex = (int)Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
1917         for (i = 0;i < endindex;i++)
1918         {
1919                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
1920                 if (!buffer)
1921                         continue;
1922                 if (buffer->isuniformbuffer)
1923                         type = R_BUFFERDATA_UNIFORM;
1924                 else if (buffer->isindexbuffer && buffer->isindex16)
1925                         type = R_BUFFERDATA_INDEX16;
1926                 else if (buffer->isindexbuffer)
1927                         type = R_BUFFERDATA_INDEX32;
1928                 else
1929                         type = R_BUFFERDATA_VERTEX;
1930                 isdynamic = buffer->isdynamic;
1931                 bufferstat[type][isdynamic][0]++;
1932                 bufferstat[type][isdynamic][1] += buffer->size;
1933                 if (printeach)
1934                         Con_Printf("buffer #%i %s = %i bytes (%s %s)\n", i, buffer->name, (int)buffer->size, isdynamic ? "dynamic" : "static", buffertypename[type]);
1935         }
1936         index16count   = (int)(bufferstat[R_BUFFERDATA_INDEX16][0][0] + bufferstat[R_BUFFERDATA_INDEX16][1][0]);
1937         index16mem     = (int)(bufferstat[R_BUFFERDATA_INDEX16][0][1] + bufferstat[R_BUFFERDATA_INDEX16][1][1]);
1938         index32count   = (int)(bufferstat[R_BUFFERDATA_INDEX32][0][0] + bufferstat[R_BUFFERDATA_INDEX32][1][0]);
1939         index32mem     = (int)(bufferstat[R_BUFFERDATA_INDEX32][0][1] + bufferstat[R_BUFFERDATA_INDEX32][1][1]);
1940         vertexcount  = (int)(bufferstat[R_BUFFERDATA_VERTEX ][0][0] + bufferstat[R_BUFFERDATA_VERTEX ][1][0]);
1941         vertexmem    = (int)(bufferstat[R_BUFFERDATA_VERTEX ][0][1] + bufferstat[R_BUFFERDATA_VERTEX ][1][1]);
1942         uniformcount = (int)(bufferstat[R_BUFFERDATA_UNIFORM][0][0] + bufferstat[R_BUFFERDATA_UNIFORM][1][0]);
1943         uniformmem   = (int)(bufferstat[R_BUFFERDATA_UNIFORM][0][1] + bufferstat[R_BUFFERDATA_UNIFORM][1][1]);
1944         totalcount = index16count + index32count + vertexcount + uniformcount;
1945         totalmem = index16mem + index32mem + vertexmem + uniformmem;
1946         Con_Printf("%i 16bit indexbuffers totalling %i bytes (%.3f MB)\n%i 32bit indexbuffers totalling %i bytes (%.3f MB)\n%i vertexbuffers totalling %i bytes (%.3f MB)\n%i uniformbuffers totalling %i bytes (%.3f MB)\ncombined %i buffers totalling %i bytes (%.3fMB)\n", index16count, index16mem, index16mem / 10248576.0, index32count, index32mem, index32mem / 10248576.0, vertexcount, vertexmem, vertexmem / 10248576.0, uniformcount, uniformmem, uniformmem / 10248576.0, totalcount, totalmem, totalmem / 10248576.0);
1947 }
1948
1949
1950
1951 void R_Mesh_VertexPointer(int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
1952 {
1953         switch(vid.renderpath)
1954         {
1955         case RENDERPATH_GL20:
1956         case RENDERPATH_GLES2:
1957                 if (gl_state.pointer_vertex_components != components || gl_state.pointer_vertex_gltype != gltype || gl_state.pointer_vertex_stride != stride || gl_state.pointer_vertex_pointer != pointer || gl_state.pointer_vertex_vertexbuffer != vertexbuffer || gl_state.pointer_vertex_offset != bufferoffset)
1958                 {
1959                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
1960                         if (!bufferobject && gl_paranoid.integer)
1961                                 Con_DPrintf("Warning: no bufferobject in R_Mesh_VertexPointer(%i, %i, %i, %p, %p, %08x)", components, gltype, (int)stride, pointer, vertexbuffer, (unsigned int)bufferoffset);
1962                         gl_state.pointer_vertex_components = components;
1963                         gl_state.pointer_vertex_gltype = gltype;
1964                         gl_state.pointer_vertex_stride = stride;
1965                         gl_state.pointer_vertex_pointer = pointer;
1966                         gl_state.pointer_vertex_vertexbuffer = vertexbuffer;
1967                         gl_state.pointer_vertex_offset = bufferoffset;
1968                         CHECKGLERROR
1969                         GL_BindVBO(bufferobject);
1970                         // LordHavoc: special flag added to gltype for unnormalized types
1971                         qglVertexAttribPointer(GLSLATTRIB_POSITION, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
1972                 }
1973                 break;
1974         }
1975 }
1976
1977 void R_Mesh_ColorPointer(int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
1978 {
1979         // note: vertexbuffer may be non-NULL even if pointer is NULL, so check
1980         // the pointer only.
1981         switch(vid.renderpath)
1982         {
1983         case RENDERPATH_GL20:
1984         case RENDERPATH_GLES2:
1985                 CHECKGLERROR
1986                 if (pointer)
1987                 {
1988                         // caller wants color array enabled
1989                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
1990                         if (!gl_state.pointer_color_enabled)
1991                         {
1992                                 gl_state.pointer_color_enabled = true;
1993                                 CHECKGLERROR
1994                                 qglEnableVertexAttribArray(GLSLATTRIB_COLOR);CHECKGLERROR
1995                         }
1996                         if (gl_state.pointer_color_components != components || gl_state.pointer_color_gltype != gltype || gl_state.pointer_color_stride != stride || gl_state.pointer_color_pointer != pointer || gl_state.pointer_color_vertexbuffer != vertexbuffer || gl_state.pointer_color_offset != bufferoffset)
1997                         {
1998                                 gl_state.pointer_color_components = components;
1999                                 gl_state.pointer_color_gltype = gltype;
2000                                 gl_state.pointer_color_stride = stride;
2001                                 gl_state.pointer_color_pointer = pointer;
2002                                 gl_state.pointer_color_vertexbuffer = vertexbuffer;
2003                                 gl_state.pointer_color_offset = bufferoffset;
2004                                 CHECKGLERROR
2005                                 GL_BindVBO(bufferobject);
2006                                 // LordHavoc: special flag added to gltype for unnormalized types
2007                                 qglVertexAttribPointer(GLSLATTRIB_COLOR, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
2008                         }
2009                 }
2010                 else
2011                 {
2012                         // caller wants color array disabled
2013                         if (gl_state.pointer_color_enabled)
2014                         {
2015                                 gl_state.pointer_color_enabled = false;
2016                                 CHECKGLERROR
2017                                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);CHECKGLERROR
2018                                 // when color array is on the current color gets trashed, set it again
2019                                 qglVertexAttrib4f(GLSLATTRIB_COLOR, gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);CHECKGLERROR
2020                         }
2021                 }
2022                 break;
2023         }
2024 }
2025
2026 void R_Mesh_TexCoordPointer(unsigned int unitnum, int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
2027 {
2028         gltextureunit_t *unit = gl_state.units + unitnum;
2029         // update array settings
2030         // note: there is no need to check bufferobject here because all cases
2031         // that involve a valid bufferobject also supply a texcoord array
2032         switch(vid.renderpath)
2033         {
2034         case RENDERPATH_GL20:
2035         case RENDERPATH_GLES2:
2036                 CHECKGLERROR
2037                 if (pointer)
2038                 {
2039                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
2040                         // texture array unit is enabled, enable the array
2041                         if (!unit->arrayenabled)
2042                         {
2043                                 unit->arrayenabled = true;
2044                                 qglEnableVertexAttribArray(unitnum+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
2045                         }
2046                         // texcoord array
2047                         if (unit->pointer_texcoord_components != components || unit->pointer_texcoord_gltype != gltype || unit->pointer_texcoord_stride != stride || unit->pointer_texcoord_pointer != pointer || unit->pointer_texcoord_vertexbuffer != vertexbuffer || unit->pointer_texcoord_offset != bufferoffset)
2048                         {
2049                                 unit->pointer_texcoord_components = components;
2050                                 unit->pointer_texcoord_gltype = gltype;
2051                                 unit->pointer_texcoord_stride = stride;
2052                                 unit->pointer_texcoord_pointer = pointer;
2053                                 unit->pointer_texcoord_vertexbuffer = vertexbuffer;
2054                                 unit->pointer_texcoord_offset = bufferoffset;
2055                                 GL_BindVBO(bufferobject);
2056                                 // LordHavoc: special flag added to gltype for unnormalized types
2057                                 qglVertexAttribPointer(unitnum+GLSLATTRIB_TEXCOORD0, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
2058                         }
2059                 }
2060                 else
2061                 {
2062                         // texture array unit is disabled, disable the array
2063                         if (unit->arrayenabled)
2064                         {
2065                                 unit->arrayenabled = false;
2066                                 qglDisableVertexAttribArray(unitnum+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
2067                         }
2068                 }
2069                 break;
2070         }
2071 }
2072
2073 int R_Mesh_TexBound(unsigned int unitnum, int id)
2074 {
2075         gltextureunit_t *unit = gl_state.units + unitnum;
2076         if (unitnum >= vid.teximageunits)
2077                 return 0;
2078         if (id == GL_TEXTURE_2D)
2079                 return unit->t2d;
2080         if (id == GL_TEXTURE_3D)
2081                 return unit->t3d;
2082         if (id == GL_TEXTURE_CUBE_MAP)
2083                 return unit->tcubemap;
2084         return 0;
2085 }
2086
2087 void R_Mesh_CopyToTexture(rtexture_t *tex, int tx, int ty, int sx, int sy, int width, int height)
2088 {
2089         switch(vid.renderpath)
2090         {
2091         case RENDERPATH_GL20:
2092         case RENDERPATH_GLES2:
2093                 R_Mesh_TexBind(0, tex);
2094                 GL_ActiveTexture(0);CHECKGLERROR
2095                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, tx, ty, sx, sy, width, height);CHECKGLERROR
2096                 break;
2097         }
2098 }
2099
2100 void R_Mesh_ClearBindingsForTexture(int texnum)
2101 {
2102         gltextureunit_t *unit;
2103         unsigned int unitnum;
2104         // this doesn't really unbind the texture, but it does prevent a mistaken "do nothing" behavior on the next time this same texnum is bound on the same unit as the same type (this mainly affects r_shadow_bouncegrid because 3D textures are so rarely used)
2105         for (unitnum = 0;unitnum < vid.teximageunits;unitnum++)
2106         {
2107                 unit = gl_state.units + unitnum;
2108                 if (unit->t2d == texnum)
2109                         unit->t2d = -1;
2110                 if (unit->t3d == texnum)
2111                         unit->t3d = -1;
2112                 if (unit->tcubemap == texnum)
2113                         unit->tcubemap = -1;
2114         }
2115 }
2116
2117 void R_Mesh_TexBind(unsigned int unitnum, rtexture_t *tex)
2118 {
2119         gltextureunit_t *unit = gl_state.units + unitnum;
2120         int texnum;
2121         if (unitnum >= vid.teximageunits)
2122                 return;
2123         if (unit->texture == tex)
2124                 return;
2125         switch(vid.renderpath)
2126         {
2127         case RENDERPATH_GL20:
2128         case RENDERPATH_GLES2:
2129                 if (!tex)
2130                 {
2131                         tex = r_texture_white;
2132                         // not initialized enough yet...
2133                         if (!tex)
2134                                 return;
2135                 }
2136                 unit->texture = tex;
2137                 texnum = R_GetTexture(tex);
2138                 switch(tex->gltexturetypeenum)
2139                 {
2140                 case GL_TEXTURE_2D: if (unit->t2d != texnum) {GL_ActiveTexture(unitnum);unit->t2d = texnum;qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR}break;
2141                 case GL_TEXTURE_3D: if (unit->t3d != texnum) {GL_ActiveTexture(unitnum);unit->t3d = texnum;qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR}break;
2142                 case GL_TEXTURE_CUBE_MAP: if (unit->tcubemap != texnum) {GL_ActiveTexture(unitnum);unit->tcubemap = texnum;qglBindTexture(GL_TEXTURE_CUBE_MAP, unit->tcubemap);CHECKGLERROR}break;
2143                 }
2144                 break;
2145         }
2146 }
2147
2148 void R_Mesh_ResetTextureState(void)
2149 {
2150         unsigned int unitnum;
2151
2152         BACKENDACTIVECHECK
2153
2154         for (unitnum = 0;unitnum < vid.teximageunits;unitnum++)
2155                 R_Mesh_TexBind(unitnum, NULL);
2156         for (unitnum = 0;unitnum < vid.texarrayunits;unitnum++)
2157                 R_Mesh_TexCoordPointer(unitnum, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2158 }
2159
2160 void R_Mesh_PrepareVertices_Vertex3f(int numvertices, const float *vertex3f, const r_meshbuffer_t *vertexbuffer, int bufferoffset)
2161 {
2162         // upload temporary vertexbuffer for this rendering
2163         if (!vertexbuffer)
2164                 vertexbuffer = R_BufferData_Store(numvertices * sizeof(float[3]), (void *)vertex3f, R_BUFFERDATA_VERTEX, &bufferoffset);
2165         if (vertexbuffer)
2166         {
2167                 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), vertex3f, vertexbuffer, bufferoffset);
2168                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, NULL, 0);
2169                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2170                 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2171                 R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2172                 R_Mesh_TexCoordPointer(3, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2173                 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2174                 R_Mesh_TexCoordPointer(5, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2175                 R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2176                 R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2177         }
2178         else
2179         {
2180                 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), vertex3f, vertexbuffer, 0);
2181                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, NULL, 0);
2182                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2183                 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2184                 R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2185                 R_Mesh_TexCoordPointer(3, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2186                 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2187                 R_Mesh_TexCoordPointer(5, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2188                 R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2189                 R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2190         }
2191 }
2192
2193 void R_Mesh_PrepareVertices_Generic_Arrays(int numvertices, const float *vertex3f, const float *color4f, const float *texcoord2f)
2194 {
2195         r_meshbuffer_t *buffer_vertex3f = NULL;
2196         r_meshbuffer_t *buffer_color4f = NULL;
2197         r_meshbuffer_t *buffer_texcoord2f = NULL;
2198         int bufferoffset_vertex3f = 0;
2199         int bufferoffset_color4f = 0;
2200         int bufferoffset_texcoord2f = 0;
2201         buffer_color4f    = R_BufferData_Store(numvertices * sizeof(float[4]), color4f   , R_BUFFERDATA_VERTEX, &bufferoffset_color4f   );
2202         buffer_vertex3f   = R_BufferData_Store(numvertices * sizeof(float[3]), vertex3f  , R_BUFFERDATA_VERTEX, &bufferoffset_vertex3f  );
2203         buffer_texcoord2f = R_BufferData_Store(numvertices * sizeof(float[2]), texcoord2f, R_BUFFERDATA_VERTEX, &bufferoffset_texcoord2f);
2204         R_Mesh_VertexPointer(     3, GL_FLOAT        , sizeof(float[3])        , vertex3f          , buffer_vertex3f          , bufferoffset_vertex3f          );
2205         R_Mesh_ColorPointer(      4, GL_FLOAT        , sizeof(float[4])        , color4f           , buffer_color4f           , bufferoffset_color4f           );
2206         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(float[2])        , texcoord2f        , buffer_texcoord2f        , bufferoffset_texcoord2f        );
2207         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2208         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2209         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2210         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2211         R_Mesh_TexCoordPointer(5, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2212         R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2213         R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2214 }
2215
2216 void R_Mesh_PrepareVertices_Mesh_Arrays(int numvertices, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *color4f, const float *texcoordtexture2f, const float *texcoordlightmap2f)
2217 {
2218         r_meshbuffer_t *buffer_vertex3f = NULL;
2219         r_meshbuffer_t *buffer_color4f = NULL;
2220         r_meshbuffer_t *buffer_texcoordtexture2f = NULL;
2221         r_meshbuffer_t *buffer_svector3f = NULL;
2222         r_meshbuffer_t *buffer_tvector3f = NULL;
2223         r_meshbuffer_t *buffer_normal3f = NULL;
2224         r_meshbuffer_t *buffer_texcoordlightmap2f = NULL;
2225         int bufferoffset_vertex3f = 0;
2226         int bufferoffset_color4f = 0;
2227         int bufferoffset_texcoordtexture2f = 0;
2228         int bufferoffset_svector3f = 0;
2229         int bufferoffset_tvector3f = 0;
2230         int bufferoffset_normal3f = 0;
2231         int bufferoffset_texcoordlightmap2f = 0;
2232         buffer_color4f            = R_BufferData_Store(numvertices * sizeof(float[4]), color4f           , R_BUFFERDATA_VERTEX, &bufferoffset_color4f           );
2233         buffer_vertex3f           = R_BufferData_Store(numvertices * sizeof(float[3]), vertex3f          , R_BUFFERDATA_VERTEX, &bufferoffset_vertex3f          );
2234         buffer_svector3f          = R_BufferData_Store(numvertices * sizeof(float[3]), svector3f         , R_BUFFERDATA_VERTEX, &bufferoffset_svector3f         );
2235         buffer_tvector3f          = R_BufferData_Store(numvertices * sizeof(float[3]), tvector3f         , R_BUFFERDATA_VERTEX, &bufferoffset_tvector3f         );
2236         buffer_normal3f           = R_BufferData_Store(numvertices * sizeof(float[3]), normal3f          , R_BUFFERDATA_VERTEX, &bufferoffset_normal3f          );
2237         buffer_texcoordtexture2f  = R_BufferData_Store(numvertices * sizeof(float[2]), texcoordtexture2f , R_BUFFERDATA_VERTEX, &bufferoffset_texcoordtexture2f );
2238         buffer_texcoordlightmap2f = R_BufferData_Store(numvertices * sizeof(float[2]), texcoordlightmap2f, R_BUFFERDATA_VERTEX, &bufferoffset_texcoordlightmap2f);
2239         R_Mesh_VertexPointer(     3, GL_FLOAT        , sizeof(float[3])        , vertex3f          , buffer_vertex3f          , bufferoffset_vertex3f          );
2240         R_Mesh_ColorPointer(      4, GL_FLOAT        , sizeof(float[4])        , color4f           , buffer_color4f           , bufferoffset_color4f           );
2241         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(float[2])        , texcoordtexture2f , buffer_texcoordtexture2f , bufferoffset_texcoordtexture2f );
2242         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT        , sizeof(float[3])        , svector3f         , buffer_svector3f         , bufferoffset_svector3f         );
2243         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT        , sizeof(float[3])        , tvector3f         , buffer_tvector3f         , bufferoffset_tvector3f         );
2244         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT        , sizeof(float[3])        , normal3f          , buffer_normal3f          , bufferoffset_normal3f          );
2245         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT        , sizeof(float[2])        , texcoordlightmap2f, buffer_texcoordlightmap2f, bufferoffset_texcoordlightmap2f);
2246         R_Mesh_TexCoordPointer(5, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2247         R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2248         R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2249 }
2250
2251 void GL_BlendEquationSubtract(qboolean negated)
2252 {
2253         if(negated)
2254         {
2255                 switch(vid.renderpath)
2256                 {
2257                 case RENDERPATH_GL20:
2258                 case RENDERPATH_GLES2:
2259                         qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT);
2260                         break;
2261                 }
2262         }
2263         else
2264         {
2265                 switch(vid.renderpath)
2266                 {
2267                 case RENDERPATH_GL20:
2268                 case RENDERPATH_GLES2:
2269                         qglBlendEquationEXT(GL_FUNC_ADD);
2270                         break;
2271                 }
2272         }
2273 }