Cleanup: style, whitespace, doxy filepaths
[blender-staging.git] / source / blender / gpu / intern / gpu_draw.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Brecht Van Lommel.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/gpu/intern/gpu_draw.c
29  *  \ingroup gpu
30  *
31  * Utility functions for dealing with OpenGL texture & material context,
32  * mipmap generation and light objects.
33  *
34  * These are some obscure rendering functions shared between the
35  * game engine and the blender, in this module to avoid duplication
36  * and abstract them away from the rest a bit.
37  */
38
39 #include <string.h>
40
41 #include "GPU_glew.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_linklist.h"
45 #include "BLI_math.h"
46 #include "BLI_threads.h"
47 #include "BLI_utildefines.h"
48
49 #include "DNA_lamp_types.h"
50 #include "DNA_material_types.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_modifier_types.h"
54 #include "DNA_node_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_smoke_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_particle_types.h"
60
61 #include "MEM_guardedalloc.h"
62
63 #include "IMB_imbuf.h"
64 #include "IMB_imbuf_types.h"
65
66 #include "BKE_bmfont.h"
67 #include "BKE_global.h"
68 #include "BKE_image.h"
69 #include "BKE_main.h"
70 #include "BKE_material.h"
71 #include "BKE_node.h"
72 #include "BKE_scene.h"
73 #include "BKE_DerivedMesh.h"
74 #ifdef WITH_GAMEENGINE
75 #  include "BKE_object.h"
76 #endif
77
78 #include "GPU_basic_shader.h"
79 #include "GPU_buffers.h"
80 #include "GPU_draw.h"
81 #include "GPU_extensions.h"
82 #include "GPU_material.h"
83 #include "GPU_shader.h"
84 #include "GPU_texture.h"
85
86 #include "PIL_time.h"
87
88 #ifdef WITH_SMOKE
89 #  include "smoke_API.h"
90 #endif
91
92 #ifdef WITH_OPENSUBDIV
93 #  include "BKE_subsurf.h"
94 #  include "BKE_editmesh.h"
95
96 #  include "gpu_codegen.h"
97 #endif
98
99 extern Material defmaterial; /* from material.c */
100
101 /* Text Rendering */
102
103 static void gpu_mcol(unsigned int ucol)
104 {
105         /* mcol order is swapped */
106         const char *cp = (char *)&ucol;
107         glColor3ub(cp[3], cp[2], cp[1]);
108 }
109
110 void GPU_render_text(
111         MTexPoly *mtexpoly, int mode,
112         const char *textstr, int textlen, unsigned int *col,
113         const float *v_quad[4], const float *uv_quad[4],
114         int glattrib)
115 {
116         if ((mode & GEMAT_TEXT) && (textlen > 0) && mtexpoly->tpage) {
117                 const float *v1 = v_quad[0];
118                 const float *v2 = v_quad[1];
119                 const float *v3 = v_quad[2];
120                 const float *v4 = v_quad[3];
121                 Image *ima = (Image *)mtexpoly->tpage;
122                 const size_t textlen_st = textlen;
123                 float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
124                 
125                 /* multiline */
126                 float line_start = 0.0f, line_height;
127                 
128                 if (v4)
129                         line_height = max_ffff(v1[1], v2[1], v3[1], v4[2]) - min_ffff(v1[1], v2[1], v3[1], v4[2]);
130                 else
131                         line_height = max_fff(v1[1], v2[1], v3[1]) - min_fff(v1[1], v2[1], v3[1]);
132                 line_height *= 1.2f; /* could be an option? */
133                 /* end multiline */
134
135                 
136                 /* color has been set */
137                 if (mtexpoly->mode & TF_OBCOL)
138                         col = NULL;
139                 else if (!col)
140                         glColor3f(1.0f, 1.0f, 1.0f);
141
142                 glPushMatrix();
143                 
144                 /* get the tab width */
145                 ImBuf *first_ibuf = BKE_image_get_first_ibuf(ima);
146                 matrixGlyph(first_ibuf, ' ', &centerx, &centery,
147                         &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
148                 
149                 float advance_tab = advance * 4; /* tab width could also be an option */
150                 
151                 
152                 for (size_t index = 0; index < textlen_st; ) {
153                         unsigned int character;
154                         float uv[4][2];
155
156                         /* lets calculate offset stuff */
157                         character = BLI_str_utf8_as_unicode_and_size_safe(textstr + index, &index);
158                         
159                         if (character == '\n') {
160                                 glTranslatef(line_start, -line_height, 0.0f);
161                                 line_start = 0.0f;
162                                 continue;
163                         }
164                         else if (character == '\t') {
165                                 glTranslatef(advance_tab, 0.0f, 0.0f);
166                                 line_start -= advance_tab; /* so we can go back to the start of the line */
167                                 continue;
168                                 
169                         }
170                         else if (character > USHRT_MAX) {
171                                 /* not much we can do here bmfonts take ushort */
172                                 character = '?';
173                         }
174                         
175                         /* space starts at offset 1 */
176                         /* character = character - ' ' + 1; */
177                         matrixGlyph(first_ibuf, character, & centerx, &centery,
178                                 &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
179
180                         uv[0][0] = (uv_quad[0][0] - centerx) * sizex + transx;
181                         uv[0][1] = (uv_quad[0][1] - centery) * sizey + transy;
182                         uv[1][0] = (uv_quad[1][0] - centerx) * sizex + transx;
183                         uv[1][1] = (uv_quad[1][1] - centery) * sizey + transy;
184                         uv[2][0] = (uv_quad[2][0] - centerx) * sizex + transx;
185                         uv[2][1] = (uv_quad[2][1] - centery) * sizey + transy;
186                         
187                         glBegin(GL_POLYGON);
188                         if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[0]);
189                         else glTexCoord2fv(uv[0]);
190                         if (col) gpu_mcol(col[0]);
191                         glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
192                         
193                         if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[1]);
194                         else glTexCoord2fv(uv[1]);
195                         if (col) gpu_mcol(col[1]);
196                         glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
197
198                         if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[2]);
199                         else glTexCoord2fv(uv[2]);
200                         if (col) gpu_mcol(col[2]);
201                         glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
202
203                         if (v4) {
204                                 uv[3][0] = (uv_quad[3][0] - centerx) * sizex + transx;
205                                 uv[3][1] = (uv_quad[3][1] - centery) * sizey + transy;
206
207                                 if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[3]);
208                                 else glTexCoord2fv(uv[3]);
209                                 if (col) gpu_mcol(col[3]);
210                                 glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
211                         }
212                         glEnd();
213
214                         glTranslatef(advance, 0.0f, 0.0f);
215                         line_start -= advance; /* so we can go back to the start of the line */
216                 }
217                 glPopMatrix();
218
219                 BKE_image_release_ibuf(ima, first_ibuf, NULL);
220         }
221 }
222
223 /* Checking powers of two for images since OpenGL ES requires it */
224
225 static bool is_power_of_2_resolution(int w, int h)
226 {
227         return is_power_of_2_i(w) && is_power_of_2_i(h);
228 }
229
230 static bool is_over_resolution_limit(GLenum textarget, int w, int h)
231 {
232         int size = (textarget == GL_TEXTURE_2D) ?
233                 GPU_max_texture_size() : GPU_max_cube_map_size();
234         int reslimit = (U.glreslimit != 0) ?
235                 min_ii(U.glreslimit, size) : size;
236
237         return (w > reslimit || h > reslimit);
238 }
239
240 static int smaller_power_of_2_limit(int num)
241 {
242         int reslimit = (U.glreslimit != 0) ?
243                 min_ii(U.glreslimit, GPU_max_texture_size()) :
244                 GPU_max_texture_size();
245         /* take texture clamping into account */
246         if (num > reslimit)
247                 return reslimit;
248
249         return power_of_2_min_i(num);
250 }
251
252 /* Current OpenGL state caching for GPU_set_tpage */
253
254 static struct GPUTextureState {
255         int curtile, tile;
256         int curtilemode, tilemode;
257         int curtileXRep, tileXRep;
258         int curtileYRep, tileYRep;
259         Image *ima, *curima;
260
261         /* also controls min/mag filtering */
262         bool domipmap;
263         /* only use when 'domipmap' is set */
264         bool linearmipmap;
265         /* store this so that new images created while texture painting won't be set to mipmapped */
266         bool texpaint;
267
268         int alphablend;
269         float anisotropic;
270         int gpu_mipmap;
271         MTexPoly *lasttface;
272 } GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, 0, -1, 1.0f, 0, NULL};
273
274 /* Mipmap settings */
275
276 void GPU_set_gpu_mipmapping(int gpu_mipmap)
277 {
278         int old_value = GTS.gpu_mipmap;
279
280         /* only actually enable if it's supported */
281         GTS.gpu_mipmap = gpu_mipmap && GLEW_EXT_framebuffer_object;
282
283         if (old_value != GTS.gpu_mipmap) {
284                 GPU_free_images();
285         }
286 }
287
288 static void gpu_generate_mipmap(GLenum target)
289 {
290         const bool is_ati = GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_ANY, GPU_DRIVER_ANY);
291         int target_enabled = 0;
292
293         /* work around bug in ATI driver, need to have GL_TEXTURE_2D enabled
294          * http://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation */
295         if (is_ati) {
296                 target_enabled = glIsEnabled(target);
297                 if (!target_enabled)
298                         glEnable(target);
299         }
300
301         /* TODO: simplify when we transition to GL >= 3 */
302         if (GLEW_VERSION_3_0 || GLEW_ARB_framebuffer_object)
303                 glGenerateMipmap(target);
304         else if (GLEW_EXT_framebuffer_object)
305                 glGenerateMipmapEXT(target);
306
307         if (is_ati && !target_enabled)
308                 glDisable(target);
309 }
310
311 void GPU_set_mipmap(bool mipmap)
312 {
313         if (GTS.domipmap != mipmap) {
314                 GPU_free_images();
315                 GTS.domipmap = mipmap;
316         }
317 }
318
319 void GPU_set_linear_mipmap(bool linear)
320 {
321         if (GTS.linearmipmap != linear) {
322                 GTS.linearmipmap = linear;
323         }
324 }
325
326 bool GPU_get_mipmap(void)
327 {
328         return GTS.domipmap && !GTS.texpaint;
329 }
330
331 bool GPU_get_linear_mipmap(void)
332 {
333         return GTS.linearmipmap;
334 }
335
336 static GLenum gpu_get_mipmap_filter(bool mag)
337 {
338         /* linearmipmap is off by default *when mipmapping is off,
339          * use unfiltered display */
340         if (mag) {
341                 if (GTS.domipmap)
342                         return GL_LINEAR;
343                 else
344                         return GL_NEAREST;
345         }
346         else {
347                 if (GTS.domipmap) {
348                         if (GTS.linearmipmap) {
349                                 return GL_LINEAR_MIPMAP_LINEAR;
350                         }
351                         else {
352                                 return GL_LINEAR_MIPMAP_NEAREST;
353                         }
354                 }
355                 else {
356                         return GL_NEAREST;
357                 }
358         }
359 }
360
361 /* Anisotropic filtering settings */
362 void GPU_set_anisotropic(float value)
363 {
364         if (GTS.anisotropic != value) {
365                 GPU_free_images();
366
367                 /* Clamp value to the maximum value the graphics card supports */
368                 const float max = GPU_max_texture_anisotropy();
369                 if (value > max)
370                         value = max;
371
372                 GTS.anisotropic = value;
373         }
374 }
375
376 float GPU_get_anisotropic(void)
377 {
378         return GTS.anisotropic;
379 }
380
381 /* Set OpenGL state for an MTFace */
382
383 static void gpu_make_repbind(Image *ima)
384 {
385         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
386         if (ibuf == NULL)
387                 return;
388
389         if (ima->repbind) {
390                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
391                 MEM_freeN(ima->repbind);
392                 ima->repbind = NULL;
393                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
394         }
395
396         ima->totbind = ima->xrep * ima->yrep;
397
398         if (ima->totbind > 1) {
399                 ima->repbind = MEM_callocN(sizeof(int) * ima->totbind, "repbind");
400         }
401
402         BKE_image_release_ibuf(ima, ibuf, NULL);
403 }
404
405 static unsigned int *gpu_get_image_bindcode(Image *ima, GLenum textarget)
406 {
407         unsigned int *bind = 0;
408
409         if (textarget == GL_TEXTURE_2D)
410                 bind = &ima->bindcode[TEXTARGET_TEXTURE_2D];
411         else if (textarget == GL_TEXTURE_CUBE_MAP)
412                 bind = &ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP];
413
414         return bind;
415 }
416
417 void GPU_clear_tpage(bool force)
418 {
419         if (GTS.lasttface == NULL && !force)
420                 return;
421         
422         GTS.lasttface = NULL;
423         GTS.curtile = 0;
424         GTS.curima = NULL;
425         if (GTS.curtilemode != 0) {
426                 glMatrixMode(GL_TEXTURE);
427                 glLoadIdentity();
428                 glMatrixMode(GL_MODELVIEW);
429         }
430         GTS.curtilemode = 0;
431         GTS.curtileXRep = 0;
432         GTS.curtileYRep = 0;
433         GTS.alphablend = -1;
434         
435         glDisable(GL_BLEND);
436         glDisable(GL_TEXTURE_2D);
437         glDisable(GL_TEXTURE_GEN_S);
438         glDisable(GL_TEXTURE_GEN_T);
439         glDisable(GL_ALPHA_TEST);
440 }
441
442 static void gpu_set_alpha_blend(GPUBlendMode alphablend)
443 {
444         if (alphablend == GPU_BLEND_SOLID) {
445                 glDisable(GL_BLEND);
446                 glDisable(GL_ALPHA_TEST);
447                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
448                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
449         }
450         else if (alphablend == GPU_BLEND_ADD) {
451                 glEnable(GL_BLEND);
452                 glBlendFunc(GL_ONE, GL_ONE);
453                 glDisable(GL_ALPHA_TEST);
454                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
455         }
456         else if (ELEM(alphablend, GPU_BLEND_ALPHA, GPU_BLEND_ALPHA_SORT)) {
457                 glEnable(GL_BLEND);
458                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
459
460                 /* for OpenGL render we use the alpha channel, this makes alpha blend correct */
461                 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
462                 
463                 /* if U.glalphaclip == 1.0, some cards go bonkers...
464                  * turn off alpha test in this case */
465
466                 /* added after 2.45 to clip alpha */
467                 if (U.glalphaclip == 1.0f) {
468                         glDisable(GL_ALPHA_TEST);
469                 }
470                 else {
471                         glEnable(GL_ALPHA_TEST);
472                         glAlphaFunc(GL_GREATER, U.glalphaclip);
473                 }
474         }
475         else if (alphablend == GPU_BLEND_CLIP) {
476                 glDisable(GL_BLEND);
477                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
478                 glEnable(GL_ALPHA_TEST);
479                 glAlphaFunc(GL_GREATER, 0.5f);
480         }
481         else if (alphablend == GPU_BLEND_ALPHA_TO_COVERAGE) {
482                 glEnable(GL_ALPHA_TEST);
483                 glAlphaFunc(GL_GREATER, U.glalphaclip);
484                 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
485         }
486 }
487
488 static void gpu_verify_alpha_blend(int alphablend)
489 {
490         /* verify alpha blending modes */
491         if (GTS.alphablend == alphablend)
492                 return;
493
494         gpu_set_alpha_blend(alphablend);
495         GTS.alphablend = alphablend;
496 }
497
498 static void gpu_verify_reflection(Image *ima)
499 {
500         if (ima && (ima->flag & IMA_REFLECT)) {
501                 /* enable reflection mapping */
502                 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
503                 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
504
505                 glEnable(GL_TEXTURE_GEN_S);
506                 glEnable(GL_TEXTURE_GEN_T);
507         }
508         else {
509                 /* disable reflection mapping */
510                 glDisable(GL_TEXTURE_GEN_S);
511                 glDisable(GL_TEXTURE_GEN_T);
512         }
513 }
514
515 typedef struct VerifyThreadData {
516         ImBuf *ibuf;
517         float *srgb_frect;
518 } VerifyThreadData;
519
520 static void gpu_verify_high_bit_srgb_buffer_slice(float *srgb_frect,
521                                                   ImBuf *ibuf,
522                                                   const int start_line,
523                                                   const int height)
524 {
525         size_t offset = ibuf->channels * start_line * ibuf->x;
526         float *current_srgb_frect = srgb_frect + offset;
527         float *current_rect_float = ibuf->rect_float + offset;
528         IMB_buffer_float_from_float(current_srgb_frect,
529                                     current_rect_float,
530                                     ibuf->channels,
531                                     IB_PROFILE_SRGB,
532                                     IB_PROFILE_LINEAR_RGB, true,
533                                     ibuf->x, height,
534                                     ibuf->x, ibuf->x);
535         IMB_buffer_float_unpremultiply(current_srgb_frect, ibuf->x, height);
536         /* Clamp buffer colors to 1.0 to avoid artifacts due to glu for hdr images. */
537         IMB_buffer_float_clamp(current_srgb_frect, ibuf->x, height);
538 }
539
540 static void verify_thread_do(void *data_v,
541                              int start_scanline,
542                              int num_scanlines)
543 {
544         VerifyThreadData *data = (VerifyThreadData *)data_v;
545         gpu_verify_high_bit_srgb_buffer_slice(data->srgb_frect,
546                                               data->ibuf,
547                                               start_scanline,
548                                               num_scanlines);
549 }
550
551 static void gpu_verify_high_bit_srgb_buffer(float *srgb_frect,
552                                             ImBuf *ibuf)
553 {
554         if (ibuf->y < 64) {
555                 gpu_verify_high_bit_srgb_buffer_slice(srgb_frect,
556                                                       ibuf,
557                                                       0, ibuf->y);
558         }
559         else {
560                 VerifyThreadData data;
561                 data.ibuf = ibuf;
562                 data.srgb_frect = srgb_frect;
563                 IMB_processor_apply_threaded_scanlines(ibuf->y, verify_thread_do, &data);
564         }
565 }
566
567 int GPU_verify_image(
568         Image *ima, ImageUser *iuser,
569         int textarget, int tftile, bool compare, bool mipmap, bool is_data)
570 {
571         unsigned int *bind = NULL;
572         int tpx = 0, tpy = 0;
573         unsigned int *rect = NULL;
574         float *frect = NULL;
575         float *srgb_frect = NULL;
576         /* flag to determine whether deep format is used */
577         bool use_high_bit_depth = false, do_color_management = false;
578
579         /* initialize tile mode and number of repeats */
580         GTS.ima = ima;
581         GTS.tilemode = (ima && (ima->tpageflag & (IMA_TILES | IMA_TWINANIM)));
582         GTS.tileXRep = 0;
583         GTS.tileYRep = 0;
584
585         /* setting current tile according to frame */
586         if (ima && (ima->tpageflag & IMA_TWINANIM))
587                 GTS.tile = ima->lastframe;
588         else
589                 GTS.tile = tftile;
590
591         GTS.tile = MAX2(0, GTS.tile);
592
593         if (ima) {
594                 GTS.tileXRep = ima->xrep;
595                 GTS.tileYRep = ima->yrep;
596         }
597
598         /* if same image & tile, we're done */
599         if (compare && ima == GTS.curima && GTS.curtile == GTS.tile &&
600             GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep &&
601             GTS.curtileYRep == GTS.tileYRep)
602         {
603                 return (ima != NULL);
604         }
605
606         /* if tiling mode or repeat changed, change texture matrix to fit */
607         if (GTS.tilemode != GTS.curtilemode || GTS.curtileXRep != GTS.tileXRep ||
608             GTS.curtileYRep != GTS.tileYRep)
609         {
610                 glMatrixMode(GL_TEXTURE);
611                 glLoadIdentity();
612
613                 if (ima && (ima->tpageflag & IMA_TILES))
614                         glScalef(ima->xrep, ima->yrep, 1.0f);
615
616                 glMatrixMode(GL_MODELVIEW);
617         }
618
619         /* check if we have a valid image */
620         if (ima == NULL || ima->ok == 0)
621                 return 0;
622
623         /* check if we have a valid image buffer */
624         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL);
625
626         if (ibuf == NULL)
627                 return 0;
628
629         if (ibuf->rect_float) {
630                 if (U.use_16bit_textures) {
631                         /* use high precision textures. This is relatively harmless because OpenGL gives us
632                          * a high precision format only if it is available */
633                         use_high_bit_depth = true;
634                 }
635                 else if (ibuf->rect == NULL) {
636                         IMB_rect_from_float(ibuf);
637                 }
638                 /* we may skip this in high precision, but if not, we need to have a valid buffer here */
639                 else if (ibuf->userflags & IB_RECT_INVALID) {
640                         IMB_rect_from_float(ibuf);
641                 }
642
643                 /* TODO unneeded when float images are correctly treated as linear always */
644                 if (!is_data) {
645                         do_color_management = true;
646                 }
647         }
648
649         /* currently, tpage refresh is used by ima sequences */
650         if (ima->tpageflag & IMA_TPAGE_REFRESH) {
651                 GPU_free_image(ima);
652                 ima->tpageflag &= ~IMA_TPAGE_REFRESH;
653         }
654         
655         if (GTS.tilemode) {
656                 /* tiled mode */
657                 if (ima->repbind == NULL) gpu_make_repbind(ima);
658                 if (GTS.tile >= ima->totbind) GTS.tile = 0;
659                 
660                 /* this happens when you change repeat buttons */
661                 if (ima->repbind && textarget == GL_TEXTURE_2D) bind = &ima->repbind[GTS.tile];
662                 else bind = gpu_get_image_bindcode(ima, textarget);
663                 
664                 if (*bind == 0) {
665                         short texwindx = ibuf->x / ima->xrep;
666                         short texwindy = ibuf->y / ima->yrep;
667                         
668                         if (GTS.tile >= ima->xrep * ima->yrep)
669                                 GTS.tile = ima->xrep * ima->yrep - 1;
670         
671                         short texwinsy = GTS.tile / ima->xrep;
672                         short texwinsx = GTS.tile - texwinsy * ima->xrep;
673         
674                         texwinsx *= texwindx;
675                         texwinsy *= texwindy;
676         
677                         tpx = texwindx;
678                         tpy = texwindy;
679
680                         if (use_high_bit_depth) {
681                                 if (do_color_management) {
682                                         srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(float) * 4, "floar_buf_col_cor");
683                                         gpu_verify_high_bit_srgb_buffer(srgb_frect, ibuf);
684                                         frect = srgb_frect + texwinsy * ibuf->x + texwinsx;
685                                 }
686                                 else {
687                                         frect = ibuf->rect_float + texwinsy * ibuf->x + texwinsx;
688                                 }
689                         }
690                         else {
691                                 rect = ibuf->rect + texwinsy * ibuf->x + texwinsx;
692                         }
693                 }
694         }
695         else {
696                 /* regular image mode */
697                 bind = gpu_get_image_bindcode(ima, textarget);
698
699                 if (*bind == 0) {
700                         tpx = ibuf->x;
701                         tpy = ibuf->y;
702                         rect = ibuf->rect;
703                         if (use_high_bit_depth) {
704                                 if (do_color_management) {
705                                         frect = srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(*srgb_frect) * 4, "floar_buf_col_cor");
706                                         gpu_verify_high_bit_srgb_buffer(srgb_frect, ibuf);
707                                 }
708                                 else
709                                         frect = ibuf->rect_float;
710                         }
711                 }
712         }
713
714         if (*bind != 0) {
715                 /* enable opengl drawing with textures */
716                 glBindTexture(textarget, *bind);
717                 BKE_image_release_ibuf(ima, ibuf, NULL);
718                 return *bind;
719         }
720
721         const int rectw = tpx;
722         const int recth = tpy;
723
724         unsigned *tilerect = NULL;
725         float *ftilerect = NULL;
726
727         /* for tiles, copy only part of image into buffer */
728         if (GTS.tilemode) {
729                 if (use_high_bit_depth) {
730                         ftilerect = MEM_mallocN(rectw * recth * sizeof(*ftilerect), "tilerect");
731
732                         for (int y = 0; y < recth; y++) {
733                                 const float *frectrow = &frect[y * ibuf->x];
734                                 float *ftilerectrow = &ftilerect[y * rectw];
735
736                                 memcpy(ftilerectrow, frectrow, tpx * sizeof(*frectrow));
737                         }
738
739                         frect = ftilerect;
740                 }
741                 else {
742                         tilerect = MEM_mallocN(rectw * recth * sizeof(*tilerect), "tilerect");
743
744                         for (int y = 0; y < recth; y++) {
745                                 const unsigned *rectrow = &rect[y * ibuf->x];
746                                 unsigned *tilerectrow = &tilerect[y * rectw];
747
748                                 memcpy(tilerectrow, rectrow, tpx * sizeof(*rectrow));
749                         }
750                         
751                         rect = tilerect;
752                 }
753         }
754
755 #ifdef WITH_DDS
756         if (ibuf->ftype == IMB_FTYPE_DDS)
757                 GPU_create_gl_tex_compressed(bind, rect, rectw, recth, textarget, mipmap, ima, ibuf);
758         else
759 #endif
760                 GPU_create_gl_tex(bind, rect, frect, rectw, recth, textarget, mipmap, use_high_bit_depth, ima);
761         
762         /* mark as non-color data texture */
763         if (*bind) {
764                 if (is_data)
765                         ima->tpageflag |= IMA_GLBIND_IS_DATA;   
766                 else
767                         ima->tpageflag &= ~IMA_GLBIND_IS_DATA;  
768         }
769
770         /* clean up */
771         if (tilerect)
772                 MEM_freeN(tilerect);
773         if (ftilerect)
774                 MEM_freeN(ftilerect);
775         if (srgb_frect)
776                 MEM_freeN(srgb_frect);
777
778         BKE_image_release_ibuf(ima, ibuf, NULL);
779
780         return *bind;
781 }
782
783 static void **gpu_gen_cube_map(unsigned int *rect, float *frect, int rectw, int recth, bool use_high_bit_depth)
784 {
785         size_t block_size = use_high_bit_depth ? sizeof(float) * 4 : sizeof(unsigned char) * 4;
786         void **sides = NULL;
787         int h = recth / 2;
788         int w = rectw / 3;
789
790         if ((use_high_bit_depth && frect == NULL) || (!use_high_bit_depth && rect == NULL) || w != h)
791                 return sides;
792
793         /* PosX, NegX, PosY, NegY, PosZ, NegZ */
794         sides = MEM_mallocN(sizeof(void *) * 6, "");
795         for (int i = 0; i < 6; i++)
796                 sides[i] = MEM_mallocN(block_size * w * h, "");
797
798         /* divide image into six parts */
799         /* ______________________
800          * |      |      |      |
801          * | NegX | NegY | PosX |
802          * |______|______|______|
803          * |      |      |      |
804          * | NegZ | PosZ | PosY |
805          * |______|______|______|
806         */
807         if (use_high_bit_depth) {
808                 float (*frectb)[4] = (float(*)[4])frect;
809                 float (**fsides)[4] = (float(**)[4])sides;
810
811                 for (int y = 0; y < h; y++) {
812                         for (int x = 0; x < w; x++) {
813                                 memcpy(&fsides[0][x * h + y], &frectb[(recth - y - 1) * rectw + 2 * w + x], block_size);
814                                 memcpy(&fsides[1][x * h + y], &frectb[(y + h) * rectw + w - 1 - x], block_size);
815                                 memcpy(&fsides[3][y * w + x], &frectb[(recth - y - 1) * rectw + 2 * w - 1 - x], block_size);
816                                 memcpy(&fsides[5][y * w + x], &frectb[(h - y - 1) * rectw + w - 1 - x], block_size);
817                         }
818                         memcpy(&fsides[2][y * w], frectb[y * rectw + 2 * w], block_size * w);
819                         memcpy(&fsides[4][y * w], frectb[y * rectw + w], block_size * w);
820                 }
821         }
822         else {
823                 unsigned int **isides = (unsigned int **)sides;
824
825                 for (int y = 0; y < h; y++) {
826                         for (int x = 0; x < w; x++) {
827                                 isides[0][x * h + y] = rect[(recth - y - 1) * rectw + 2 * w + x];
828                                 isides[1][x * h + y] = rect[(y + h) * rectw + w - 1 - x];
829                                 isides[3][y * w + x] = rect[(recth - y - 1) * rectw + 2 * w - 1 - x];
830                                 isides[5][y * w + x] = rect[(h - y - 1) * rectw + w - 1 - x];
831                         }
832                         memcpy(&isides[2][y * w], &rect[y * rectw + 2 * w], block_size * w);
833                         memcpy(&isides[4][y * w], &rect[y * rectw + w], block_size * w);
834                 }
835         }
836
837         return sides;
838 }
839
840 static void gpu_del_cube_map(void **cube_map)
841 {
842         int i;
843         if (cube_map == NULL)
844                 return;
845         for (i = 0; i < 6; i++)
846                 MEM_freeN(cube_map[i]);
847         MEM_freeN(cube_map);
848 }
849
850 /* Image *ima can be NULL */
851 void GPU_create_gl_tex(
852         unsigned int *bind, unsigned int *rect, float *frect, int rectw, int recth,
853         int textarget, bool mipmap, bool use_high_bit_depth, Image *ima)
854 {
855         ImBuf *ibuf = NULL;
856
857         int tpx = rectw;
858         int tpy = recth;
859
860         /* scale if not a power of two. this is not strictly necessary for newer
861          * GPUs (OpenGL version >= 2.0) since they support non-power-of-two-textures 
862          * Then don't bother scaling for hardware that supports NPOT textures! */
863         if (textarget == GL_TEXTURE_2D &&
864             ((!GPU_full_non_power_of_two_support() && !is_power_of_2_resolution(rectw, recth)) ||
865              is_over_resolution_limit(textarget, rectw, recth)))
866         {
867                 rectw = smaller_power_of_2_limit(rectw);
868                 recth = smaller_power_of_2_limit(recth);
869
870                 if (use_high_bit_depth) {
871                         ibuf = IMB_allocFromBuffer(NULL, frect, tpx, tpy);
872                         IMB_scaleImBuf(ibuf, rectw, recth);
873
874                         frect = ibuf->rect_float;
875                 }
876                 else {
877                         ibuf = IMB_allocFromBuffer(rect, NULL, tpx, tpy);
878                         IMB_scaleImBuf(ibuf, rectw, recth);
879
880                         rect = ibuf->rect;
881                 }
882         }
883
884         /* create image */
885         glGenTextures(1, (GLuint *)bind);
886         glBindTexture(textarget, *bind);
887
888         if (textarget == GL_TEXTURE_2D) {
889                 if (use_high_bit_depth) {
890                         if (GLEW_ARB_texture_float)
891                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, rectw, recth, 0, GL_RGBA, GL_FLOAT, frect);
892                         else
893                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, rectw, recth, 0, GL_RGBA, GL_FLOAT, frect);
894                 }
895                 else
896                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
897
898                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
899
900                 if (GPU_get_mipmap() && mipmap) {
901                         if (GTS.gpu_mipmap) {
902                                 gpu_generate_mipmap(GL_TEXTURE_2D);
903                         }
904                         else {
905                                 int i;
906                                 if (!ibuf) {
907                                         if (use_high_bit_depth) {
908                                                 ibuf = IMB_allocFromBuffer(NULL, frect, tpx, tpy);
909                                         }
910                                         else {
911                                                 ibuf = IMB_allocFromBuffer(rect, NULL, tpx, tpy);
912                                         }
913                                 }
914                                 IMB_makemipmap(ibuf, true);
915
916                                 for (i = 1; i < ibuf->miptot; i++) {
917                                         ImBuf *mip = ibuf->mipmap[i - 1];
918                                         if (use_high_bit_depth) {
919                                                 if (GLEW_ARB_texture_float)
920                                                         glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA16F_ARB, mip->x, mip->y, 0, GL_RGBA, GL_FLOAT, mip->rect_float);
921                                                 else
922                                                         glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA16, mip->x, mip->y, 0, GL_RGBA, GL_FLOAT, mip->rect_float);
923                                         }
924                                         else {
925                                                 glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA8, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect);
926                                         }
927                                 }
928                         }
929                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
930                         if (ima)
931                                 ima->tpageflag |= IMA_MIPMAP_COMPLETE;
932                 }
933                 else {
934                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
935                 }
936         }
937         else if (textarget == GL_TEXTURE_CUBE_MAP) {
938                 int w = rectw / 3, h = recth / 2;
939
940                 if (h == w && is_power_of_2_i(h) && !is_over_resolution_limit(textarget, h, w)) {
941                         void **cube_map = gpu_gen_cube_map(rect, frect, rectw, recth, use_high_bit_depth);
942                         GLenum informat = use_high_bit_depth ? (GLEW_ARB_texture_float ? GL_RGBA16F_ARB : GL_RGBA16) : GL_RGBA8;
943                         GLenum type = use_high_bit_depth ? GL_FLOAT : GL_UNSIGNED_BYTE;
944
945                         if (cube_map)
946                                 for (int i = 0; i < 6; i++)
947                                         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, informat, w, h, 0, GL_RGBA, type, cube_map[i]);
948
949                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
950
951                         if (GPU_get_mipmap() && mipmap) {
952                                 if (GTS.gpu_mipmap) {
953                                         gpu_generate_mipmap(GL_TEXTURE_CUBE_MAP);
954                                 }
955                                 else {
956                                         if (!ibuf) {
957                                                 if (use_high_bit_depth) {
958                                                         ibuf = IMB_allocFromBuffer(NULL, frect, tpx, tpy);
959                                                 }
960                                                 else {
961                                                         ibuf = IMB_allocFromBuffer(rect, NULL, tpx, tpy);
962                                                 }
963                                         }
964
965                                         IMB_makemipmap(ibuf, true);
966
967                                         for (int i = 1; i < ibuf->miptot; i++) {
968                                                 ImBuf *mip = ibuf->mipmap[i - 1];
969                                                 void **mip_cube_map = gpu_gen_cube_map(
970                                                         mip->rect, mip->rect_float,
971                                                         mip->x, mip->y, use_high_bit_depth);
972                                                 int mipw = mip->x / 3, miph = mip->y / 2;
973
974                                                 if (mip_cube_map) {
975                                                         for (int j = 0; j < 6; j++) {
976                                                                 glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + j, i,
977                                                                         informat, mipw, miph, 0, GL_RGBA, type, mip_cube_map[j]);
978                                                         }
979                                                 }
980                                                 gpu_del_cube_map(mip_cube_map);
981                                         }
982                                 }
983                                 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
984
985                                 if (ima)
986                                         ima->tpageflag |= IMA_MIPMAP_COMPLETE;
987                         }
988                         else {
989                                 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
990                         }
991                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
992                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
993                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
994
995                         gpu_del_cube_map(cube_map);
996                 }
997                 else {
998                         printf("Incorrect envmap size\n");
999                 }
1000         }
1001
1002         if (GLEW_EXT_texture_filter_anisotropic)
1003                 glTexParameterf(textarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
1004
1005         if (ibuf)
1006                 IMB_freeImBuf(ibuf);
1007 }
1008
1009 /**
1010  * GPU_upload_dxt_texture() assumes that the texture is already bound and ready to go.
1011  * This is so the viewport and the BGE can share some code.
1012  * Returns false if the provided ImBuf doesn't have a supported DXT compression format
1013  */
1014 bool GPU_upload_dxt_texture(ImBuf *ibuf)
1015 {
1016 #ifdef WITH_DDS
1017         GLint format = 0;
1018         int blocksize, height, width, i, size, offset = 0;
1019
1020         width = ibuf->x;
1021         height = ibuf->y;
1022
1023         if (GLEW_EXT_texture_compression_s3tc) {
1024                 if (ibuf->dds_data.fourcc == FOURCC_DXT1)
1025                         format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1026                 else if (ibuf->dds_data.fourcc == FOURCC_DXT3)
1027                         format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
1028                 else if (ibuf->dds_data.fourcc == FOURCC_DXT5)
1029                         format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
1030         }
1031
1032         if (format == 0) {
1033                 fprintf(stderr, "Unable to find a suitable DXT compression, falling back to uncompressed\n");
1034                 return false;
1035         }
1036
1037         if (!is_power_of_2_resolution(width, height)) {
1038                 fprintf(stderr, "Unable to load non-power-of-two DXT image resolution, falling back to uncompressed\n");
1039                 return false;
1040         }
1041
1042         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
1043         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
1044
1045         if (GLEW_EXT_texture_filter_anisotropic)
1046                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
1047
1048         blocksize = (ibuf->dds_data.fourcc == FOURCC_DXT1) ? 8 : 16;
1049         for (i = 0; i < ibuf->dds_data.nummipmaps && (width || height); ++i) {
1050                 if (width == 0)
1051                         width = 1;
1052                 if (height == 0)
1053                         height = 1;
1054
1055                 size = ((width + 3) / 4) * ((height + 3) / 4) * blocksize;
1056
1057                 glCompressedTexImage2D(GL_TEXTURE_2D, i, format, width, height,
1058                         0, size, ibuf->dds_data.data + offset);
1059
1060                 offset += size;
1061                 width >>= 1;
1062                 height >>= 1;
1063         }
1064
1065         /* set number of mipmap levels we have, needed in case they don't go down to 1x1 */
1066         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, i - 1);
1067
1068         return true;
1069 #else
1070         (void)ibuf;
1071         return false;
1072 #endif
1073 }
1074
1075 void GPU_create_gl_tex_compressed(
1076         unsigned int *bind, unsigned int *pix, int x, int y,
1077         int textarget, int mipmap, Image *ima, ImBuf *ibuf)
1078 {
1079 #ifndef WITH_DDS
1080         (void)ibuf;
1081         /* Fall back to uncompressed if DDS isn't enabled */
1082         GPU_create_gl_tex(bind, pix, NULL, x, y, textarget, mipmap, 0, ima);
1083 #else
1084         glGenTextures(1, (GLuint *)bind);
1085         glBindTexture(textarget, *bind);
1086
1087         if (textarget == GL_TEXTURE_2D && GPU_upload_dxt_texture(ibuf) == 0) {
1088                 glDeleteTextures(1, (GLuint *)bind);
1089                 GPU_create_gl_tex(bind, pix, NULL, x, y, textarget, mipmap, 0, ima);
1090         }
1091 #endif
1092 }
1093 static void gpu_verify_repeat(Image *ima)
1094 {
1095         /* set either clamp or repeat in X/Y */
1096         if (ima->tpageflag & IMA_CLAMP_U)
1097                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1098         else
1099                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1100
1101         if (ima->tpageflag & IMA_CLAMP_V)
1102                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1103         else
1104                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1105 }
1106
1107 int GPU_set_tpage(MTexPoly *mtexpoly, int mipmap, int alphablend)
1108 {
1109         /* check if we need to clear the state */
1110         if (mtexpoly == NULL) {
1111                 GPU_clear_tpage(false);
1112                 return 0;
1113         }
1114
1115         Image *ima = mtexpoly->tpage;
1116         GTS.lasttface = mtexpoly;
1117
1118         gpu_verify_alpha_blend(alphablend);
1119         gpu_verify_reflection(ima);
1120
1121         if (GPU_verify_image(ima, NULL, GL_TEXTURE_2D, mtexpoly->tile, 1, mipmap, false)) {
1122                 GTS.curtile = GTS.tile;
1123                 GTS.curima = GTS.ima;
1124                 GTS.curtilemode = GTS.tilemode;
1125                 GTS.curtileXRep = GTS.tileXRep;
1126                 GTS.curtileYRep = GTS.tileYRep;
1127
1128                 glEnable(GL_TEXTURE_2D);
1129         }
1130         else {
1131                 glDisable(GL_TEXTURE_2D);
1132                 
1133                 GTS.curtile = 0;
1134                 GTS.curima = NULL;
1135                 GTS.curtilemode = 0;
1136                 GTS.curtileXRep = 0;
1137                 GTS.curtileYRep = 0;
1138
1139                 return 0;
1140         }
1141         
1142         gpu_verify_repeat(ima);
1143         
1144         /* Did this get lost in the image recode? */
1145         /* BKE_image_tag_time(ima);*/
1146
1147         return 1;
1148 }
1149
1150 /* these two functions are called on entering and exiting texture paint mode,
1151  * temporary disabling/enabling mipmapping on all images for quick texture
1152  * updates with glTexSubImage2D. images that didn't change don't have to be
1153  * re-uploaded to OpenGL */
1154 void GPU_paint_set_mipmap(bool mipmap)
1155 {
1156         if (!GTS.domipmap)
1157                 return;
1158
1159         GTS.texpaint = !mipmap;
1160
1161         if (mipmap) {
1162                 for (Image *ima = G.main->image.first; ima; ima = ima->id.next) {
1163                         if (BKE_image_has_bindcode(ima)) {
1164                                 if (ima->tpageflag & IMA_MIPMAP_COMPLETE) {
1165                                         if (ima->bindcode[TEXTARGET_TEXTURE_2D]) {
1166                                                 glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1167                                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
1168                                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
1169                                         }
1170                                         if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) {
1171                                                 glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]);
1172                                                 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
1173                                                 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
1174                                         }
1175                                 }
1176                                 else
1177                                         GPU_free_image(ima);
1178                         }
1179                         else
1180                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1181                 }
1182
1183         }
1184         else {
1185                 for (Image *ima = G.main->image.first; ima; ima = ima->id.next) {
1186                         if (BKE_image_has_bindcode(ima)) {
1187                                 if (ima->bindcode[TEXTARGET_TEXTURE_2D]) {
1188                                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1189                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1190                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
1191                                 }
1192                                 if (ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]) {
1193                                         glBindTexture(GL_TEXTURE_CUBE_MAP, ima->bindcode[TEXTARGET_TEXTURE_CUBE_MAP]);
1194                                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1195                                         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
1196                                 }
1197                         }
1198                         else
1199                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1200                 }
1201         }
1202 }
1203
1204
1205 /* check if image has been downscaled and do scaled partial update */
1206 static bool GPU_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, int y, int w, int h)
1207 {
1208         if ((!GPU_full_non_power_of_two_support() && !is_power_of_2_resolution(ibuf->x, ibuf->y)) ||
1209             is_over_resolution_limit(GL_TEXTURE_2D, ibuf->x, ibuf->y))
1210         {
1211                 int x_limit = smaller_power_of_2_limit(ibuf->x);
1212                 int y_limit = smaller_power_of_2_limit(ibuf->y);
1213
1214                 float xratio = x_limit / (float)ibuf->x;
1215                 float yratio = y_limit / (float)ibuf->y;
1216
1217                 /* find new width, height and x,y gpu texture coordinates */
1218
1219                 /* take ceiling because we will be losing 1 pixel due to rounding errors in x,y... */
1220                 int rectw = (int)ceil(xratio * w);
1221                 int recth = (int)ceil(yratio * h);
1222
1223                 x *= xratio;
1224                 y *= yratio;
1225
1226                 /* ...but take back if we are over the limit! */
1227                 if (rectw + x > x_limit) rectw--;
1228                 if (recth + y > y_limit) recth--;
1229
1230                 /* float rectangles are already continuous in memory so we can use IMB_scaleImBuf */
1231                 if (frect) {
1232                         ImBuf *ibuf_scale = IMB_allocFromBuffer(NULL, frect, w, h);
1233                         IMB_scaleImBuf(ibuf_scale, rectw, recth);
1234
1235                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1236                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA,
1237                                         GL_FLOAT, ibuf_scale->rect_float);
1238
1239                         IMB_freeImBuf(ibuf_scale);
1240                 }
1241                 /* byte images are not continuous in memory so do manual interpolation */
1242                 else {
1243                         unsigned char *scalerect = MEM_mallocN(rectw * recth * sizeof(*scalerect) * 4, "scalerect");
1244                         unsigned int *p = (unsigned int *)scalerect;
1245                         int i, j;
1246                         float inv_xratio = 1.0f / xratio;
1247                         float inv_yratio = 1.0f / yratio;
1248                         for (i = 0; i < rectw; i++) {
1249                                 float u = (x + i) * inv_xratio;
1250                                 for (j = 0; j < recth; j++) {
1251                                         float v = (y + j) * inv_yratio;
1252                                         bilinear_interpolation_color_wrap(ibuf, (unsigned char *)(p + i + j * (rectw)), NULL, u, v);
1253                                 }
1254                         }
1255                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1256                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA,
1257                                         GL_UNSIGNED_BYTE, scalerect);
1258
1259                         MEM_freeN(scalerect);
1260                 }
1261
1262                 if (GPU_get_mipmap()) {
1263                         gpu_generate_mipmap(GL_TEXTURE_2D);
1264                 }
1265                 else {
1266                         ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1267                 }
1268
1269                 return true;
1270         }
1271
1272         return false;
1273 }
1274
1275 void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, int h)
1276 {
1277         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL);
1278
1279         if (ima->repbind ||
1280             (!GTS.gpu_mipmap && GPU_get_mipmap()) ||
1281             (ima->bindcode[TEXTARGET_TEXTURE_2D] == 0) ||
1282             (ibuf == NULL) ||
1283             (w == 0) || (h == 0))
1284         {
1285                 /* these cases require full reload still */
1286                 GPU_free_image(ima);
1287         }
1288         else {
1289                 /* for the special case, we can do a partial update
1290                  * which is much quicker for painting */
1291                 GLint row_length, skip_pixels, skip_rows;
1292
1293                 /* if color correction is needed, we must update the part that needs updating. */
1294                 if (ibuf->rect_float) {
1295                         float *buffer = MEM_mallocN(w * h * sizeof(float) * 4, "temp_texpaint_float_buf");
1296                         bool is_data = (ima->tpageflag & IMA_GLBIND_IS_DATA) != 0;
1297                         IMB_partial_rect_from_float(ibuf, buffer, x, y, w, h, is_data);
1298                         
1299                         if (GPU_check_scaled_image(ibuf, ima, buffer, x, y, w, h)) {
1300                                 MEM_freeN(buffer);
1301                                 BKE_image_release_ibuf(ima, ibuf, NULL);
1302                                 return;
1303                         }
1304
1305                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1306                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_FLOAT, buffer);
1307
1308                         MEM_freeN(buffer);
1309
1310                         /* we have already accounted for the case where GTS.gpu_mipmap is false
1311                          * so we will be using GPU mipmap generation here */
1312                         if (GPU_get_mipmap()) {
1313                                 gpu_generate_mipmap(GL_TEXTURE_2D);
1314                         }
1315                         else {
1316                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1317                         }
1318
1319                         BKE_image_release_ibuf(ima, ibuf, NULL);
1320                         return;
1321                 }
1322
1323                 if (GPU_check_scaled_image(ibuf, ima, NULL, x, y, w, h)) {
1324                         BKE_image_release_ibuf(ima, ibuf, NULL);
1325                         return;
1326                 }
1327
1328                 glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1329
1330                 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
1331                 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
1332                 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
1333
1334                 glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x);
1335                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
1336                 glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
1337
1338                 glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
1339                         GL_UNSIGNED_BYTE, ibuf->rect);
1340
1341                 glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
1342                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
1343                 glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
1344
1345                 /* see comment above as to why we are using gpu mipmap generation here */
1346                 if (GPU_get_mipmap()) {
1347                         gpu_generate_mipmap(GL_TEXTURE_2D);
1348                 }
1349                 else {
1350                         ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1351                 }
1352         }
1353
1354         BKE_image_release_ibuf(ima, ibuf, NULL);
1355 }
1356
1357 void GPU_update_images_framechange(void)
1358 {
1359         for (Image *ima = G.main->image.first; ima; ima = ima->id.next) {
1360                 if (ima->tpageflag & IMA_TWINANIM) {
1361                         if (ima->twend >= ima->xrep * ima->yrep)
1362                                 ima->twend = ima->xrep * ima->yrep - 1;
1363                 
1364                         /* check: is bindcode not in the array? free. (to do) */
1365                         
1366                         ima->lastframe++;
1367                         if (ima->lastframe > ima->twend)
1368                                 ima->lastframe = ima->twsta;
1369                 }
1370         }
1371 }
1372
1373 int GPU_update_image_time(Image *ima, double time)
1374 {
1375         if (!ima)
1376                 return 0;
1377
1378         if (ima->lastupdate < 0)
1379                 ima->lastupdate = 0;
1380
1381         if (ima->lastupdate > (float)time)
1382                 ima->lastupdate = (float)time;
1383
1384         int inc = 0;
1385
1386         if (ima->tpageflag & IMA_TWINANIM) {
1387                 if (ima->twend >= ima->xrep * ima->yrep) ima->twend = ima->xrep * ima->yrep - 1;
1388                 
1389                 /* check: is the bindcode not in the array? Then free. (still to do) */
1390                 
1391                 float diff = (float)((float)time - ima->lastupdate);
1392                 inc = (int)(diff * (float)ima->animspeed);
1393
1394                 ima->lastupdate += ((float)inc / (float)ima->animspeed);
1395
1396                 int newframe = ima->lastframe + inc;
1397
1398                 if (newframe > (int)ima->twend) {
1399                         if (ima->twend - ima->twsta != 0)
1400                                 newframe = (int)ima->twsta - 1 + (newframe - ima->twend) % (ima->twend - ima->twsta);
1401                         else
1402                                 newframe = ima->twsta;
1403                 }
1404
1405                 ima->lastframe = newframe;
1406         }
1407
1408         return inc;
1409 }
1410
1411
1412 void GPU_free_smoke(SmokeModifierData *smd)
1413 {
1414         if (smd->type & MOD_SMOKE_TYPE_DOMAIN && smd->domain) {
1415                 if (smd->domain->tex)
1416                         GPU_texture_free(smd->domain->tex);
1417                 smd->domain->tex = NULL;
1418
1419                 if (smd->domain->tex_shadow)
1420                         GPU_texture_free(smd->domain->tex_shadow);
1421                 smd->domain->tex_shadow = NULL;
1422
1423                 if (smd->domain->tex_flame)
1424                         GPU_texture_free(smd->domain->tex_flame);
1425                 smd->domain->tex_flame = NULL;
1426         }
1427 }
1428
1429 void GPU_create_smoke(SmokeModifierData *smd, int highres)
1430 {
1431 #ifdef WITH_SMOKE
1432         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1433                 SmokeDomainSettings *sds = smd->domain;
1434                 if (!sds->tex && !highres) {
1435                         /* rgba texture for color + density */
1436                         if (smoke_has_colors(sds->fluid)) {
1437                                 float *data = MEM_callocN(sizeof(float) * sds->total_cells * 4, "smokeColorTexture");
1438                                 smoke_get_rgba(sds->fluid, data, 0);
1439                                 sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 4, data);
1440                                 MEM_freeN(data);
1441                         }
1442                         /* density only */
1443                         else {
1444                                 sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_density(sds->fluid));
1445                         }
1446                         sds->tex_flame = (smoke_has_fuel(sds->fluid)) ? GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_flame(sds->fluid)) : NULL;
1447                 }
1448                 else if (!sds->tex && highres) {
1449                         /* rgba texture for color + density */
1450                         if (smoke_turbulence_has_colors(sds->wt)) {
1451                                 float *data = MEM_callocN(sizeof(float) * smoke_turbulence_get_cells(sds->wt) * 4, "smokeColorTexture");
1452                                 smoke_turbulence_get_rgba(sds->wt, data, 0);
1453                                 sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 4, data);
1454                                 MEM_freeN(data);
1455                         }
1456                         /* density only */
1457                         else {
1458                                 sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_density(sds->wt));
1459                         }
1460                         sds->tex_flame = (smoke_turbulence_has_fuel(sds->wt)) ? GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_flame(sds->wt)) : NULL;
1461                 }
1462
1463                 sds->tex_shadow = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, sds->shadow);
1464         }
1465 #else // WITH_SMOKE
1466         (void)highres;
1467         smd->domain->tex = NULL;
1468         smd->domain->tex_flame = NULL;
1469         smd->domain->tex_shadow = NULL;
1470 #endif // WITH_SMOKE
1471 }
1472
1473 static LinkNode *image_free_queue = NULL;
1474
1475 static void gpu_queue_image_for_free(Image *ima)
1476 {
1477         BLI_lock_thread(LOCK_OPENGL);
1478         BLI_linklist_prepend(&image_free_queue, ima);
1479         BLI_unlock_thread(LOCK_OPENGL);
1480 }
1481
1482 void GPU_free_unused_buffers(void)
1483 {
1484         if (!BLI_thread_is_main())
1485                 return;
1486
1487         BLI_lock_thread(LOCK_OPENGL);
1488
1489         /* images */
1490         for (LinkNode *node = image_free_queue; node; node = node->next) {
1491                 Image *ima = node->link;
1492
1493                 /* check in case it was freed in the meantime */
1494                 if (G.main && BLI_findindex(&G.main->image, ima) != -1)
1495                         GPU_free_image(ima);
1496         }
1497
1498         BLI_linklist_free(image_free_queue, NULL);
1499         image_free_queue = NULL;
1500
1501         /* vbo buffers */
1502         GPU_global_buffer_pool_free_unused();
1503
1504         BLI_unlock_thread(LOCK_OPENGL);
1505 }
1506
1507 void GPU_free_image(Image *ima)
1508 {
1509         if (!BLI_thread_is_main()) {
1510                 gpu_queue_image_for_free(ima);
1511                 return;
1512         }
1513
1514         for (int i = 0; i < TEXTARGET_COUNT; i++) {
1515                 /* free regular image binding */
1516                 if (ima->bindcode[i]) {
1517                         glDeleteTextures(1, (GLuint *)&ima->bindcode[i]);
1518                         ima->bindcode[i] = 0;
1519                 }
1520                 /* free glsl image binding */
1521                 if (ima->gputexture[i]) {
1522                         GPU_texture_free(ima->gputexture[i]);
1523                         ima->gputexture[i] = NULL;
1524                 }
1525         }
1526
1527         /* free repeated image binding */
1528         if (ima->repbind) {
1529                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
1530         
1531                 MEM_freeN(ima->repbind);
1532                 ima->repbind = NULL;
1533         }
1534
1535         ima->tpageflag &= ~(IMA_MIPMAP_COMPLETE | IMA_GLBIND_IS_DATA);
1536 }
1537
1538 void GPU_free_images(void)
1539 {
1540         if (G.main)
1541                 for (Image *ima = G.main->image.first; ima; ima = ima->id.next)
1542                         GPU_free_image(ima);
1543 }
1544
1545 /* same as above but only free animated images */
1546 void GPU_free_images_anim(void)
1547 {
1548         if (G.main)
1549                 for (Image *ima = G.main->image.first; ima; ima = ima->id.next)
1550                         if (BKE_image_is_animated(ima))
1551                                 GPU_free_image(ima);
1552 }
1553
1554
1555 void GPU_free_images_old(void)
1556 {
1557         static int lasttime = 0;
1558         int ctime = (int)PIL_check_seconds_timer();
1559
1560         /*
1561          * Run garbage collector once for every collecting period of time
1562          * if textimeout is 0, that's the option to NOT run the collector
1563          */
1564         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
1565                 return;
1566
1567         /* of course not! */
1568         if (G.is_rendering)
1569                 return;
1570
1571         lasttime = ctime;
1572
1573         Image *ima = G.main->image.first;
1574         while (ima) {
1575                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
1576                         /* If it's in GL memory, deallocate and set time tag to current time
1577                          * This gives textures a "second chance" to be used before dying. */
1578                         if (BKE_image_has_bindcode(ima) || ima->repbind) {
1579                                 GPU_free_image(ima);
1580                                 ima->lastused = ctime;
1581                         }
1582                         /* Otherwise, just kill the buffers */
1583                         else {
1584                                 BKE_image_free_buffers(ima);
1585                         }
1586                 }
1587                 ima = ima->id.next;
1588         }
1589 }
1590
1591
1592 /* OpenGL Materials */
1593
1594 #define FIXEDMAT 8
1595
1596 /* OpenGL state caching for materials */
1597
1598 typedef struct GPUMaterialFixed {
1599         float diff[3];
1600         float spec[3];
1601         int hard;
1602         float alpha;
1603 } GPUMaterialFixed; 
1604
1605 static struct GPUMaterialState {
1606         GPUMaterialFixed (*matbuf);
1607         GPUMaterialFixed matbuf_fixed[FIXEDMAT];
1608         int totmat;
1609
1610         /* set when called inside GPU_begin_object_materials / GPU_end_object_materials
1611          * otherwise calling GPU_object_material_bind returns zero */
1612         bool is_enabled;
1613
1614         Material **gmatbuf;
1615         Material *gmatbuf_fixed[FIXEDMAT];
1616         Material *gboundmat;
1617         Object *gob;
1618         DupliObject *dob;
1619         Scene *gscene;
1620         int glay;
1621         bool gscenelock;
1622         float (*gviewmat)[4];
1623         float (*gviewinv)[4];
1624         float (*gviewcamtexcofac);
1625
1626         bool backface_culling;
1627         bool two_sided_lighting;
1628
1629         GPUBlendMode *alphablend;
1630         GPUBlendMode alphablend_fixed[FIXEDMAT];
1631         bool use_alpha_pass, is_alpha_pass;
1632         bool use_matcaps;
1633
1634         int lastmatnr, lastretval;
1635         GPUBlendMode lastalphablend;
1636         bool is_opensubdiv;
1637 } GMS = {NULL};
1638
1639 /* fixed function material, alpha handed by caller */
1640 static void gpu_material_to_fixed(
1641         GPUMaterialFixed *smat, const Material *bmat, const int gamma, const Object *ob,
1642         const int new_shading_nodes, const bool dimdown)
1643 {
1644         if (bmat->mode & MA_SHLESS) {
1645                 copy_v3_v3(smat->diff, &bmat->r);
1646
1647                 if (gamma)
1648                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1649
1650                 zero_v3(smat->spec);
1651                 smat->alpha = 1.0f;
1652                 smat->hard = 0;
1653         }
1654         else if (new_shading_nodes) {
1655                 copy_v3_v3(smat->diff, &bmat->r);
1656                 copy_v3_v3(smat->spec, &bmat->specr);
1657                 smat->alpha = 1.0f;
1658                 smat->hard = CLAMPIS(bmat->har, 0, 128);
1659                 
1660                 if (dimdown) {
1661                         mul_v3_fl(smat->diff, 0.8f);
1662                         mul_v3_fl(smat->spec, 0.5f);
1663                 }
1664                 
1665                 if (gamma) {
1666                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1667                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1668                 }
1669         }
1670         else {
1671                 mul_v3_v3fl(smat->diff, &bmat->r, bmat->ref + bmat->emit);
1672
1673                 if (bmat->shade_flag & MA_OBCOLOR)
1674                         mul_v3_v3(smat->diff, ob->col);
1675                 
1676                 mul_v3_v3fl(smat->spec, &bmat->specr, bmat->spec);
1677                 smat->hard = CLAMPIS(bmat->har, 1, 128);
1678                 smat->alpha = 1.0f;
1679
1680                 if (gamma) {
1681                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1682                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1683                 }
1684         }
1685 }
1686
1687 static Material *gpu_active_node_material(Material *ma)
1688 {
1689         if (ma && ma->use_nodes && ma->nodetree) {
1690                 bNode *node = nodeGetActiveID(ma->nodetree, ID_MA);
1691
1692                 if (node)
1693                         return (Material *)node->id;
1694                 else
1695                         return NULL;
1696         }
1697
1698         return ma;
1699 }
1700
1701 void GPU_begin_dupli_object(DupliObject *dob)
1702 {
1703         GMS.dob = dob;
1704 }
1705
1706 void GPU_end_dupli_object(void)
1707 {
1708         GMS.dob = NULL;
1709 }
1710
1711 void GPU_begin_object_materials(
1712         View3D *v3d, RegionView3D *rv3d, Scene *scene, Object *ob,
1713         bool glsl, bool *do_alpha_after)
1714 {
1715         Material *ma;
1716         GPUMaterial *gpumat;
1717         GPUBlendMode alphablend;
1718         DupliObject *dob;
1719         int a;
1720         const bool gamma = BKE_scene_check_color_management_enabled(scene);
1721         const bool new_shading_nodes = BKE_scene_use_new_shading_nodes(scene);
1722         const bool use_matcap = (v3d->flag2 & V3D_SHOW_SOLID_MATCAP) != 0;  /* assumes v3d->defmaterial->preview is set */
1723         bool use_opensubdiv = false;
1724
1725 #ifdef WITH_OPENSUBDIV
1726         {
1727                 DerivedMesh *derivedFinal = NULL;
1728                 if (ob->type == OB_MESH) {
1729                         Mesh *me = ob->data;
1730                         BMEditMesh *em = me->edit_btmesh;
1731                         if (em != NULL) {
1732                                 derivedFinal = em->derivedFinal;
1733                         }
1734                         else {
1735                                 derivedFinal = ob->derivedFinal;
1736                         }
1737                 }
1738                 else {
1739                         derivedFinal = ob->derivedFinal;
1740                 }
1741
1742                 if (derivedFinal != NULL && derivedFinal->type == DM_TYPE_CCGDM) {
1743                         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) derivedFinal;
1744                         use_opensubdiv = ccgdm->useGpuBackend;
1745                 }
1746         }
1747 #endif
1748
1749 #ifdef WITH_GAMEENGINE
1750         if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1751                 ob = BKE_object_lod_matob_get(ob, scene);
1752         }
1753 #endif
1754
1755         /* initialize state */
1756         /* DupliObject must be restored */
1757         dob = GMS.dob;
1758         memset(&GMS, 0, sizeof(GMS));
1759         GMS.is_enabled = true;
1760         GMS.dob = dob;
1761         GMS.lastmatnr = -1;
1762         GMS.lastretval = -1;
1763         GMS.lastalphablend = GPU_BLEND_SOLID;
1764         GMS.use_matcaps = use_matcap;
1765
1766         GMS.backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
1767
1768         GMS.two_sided_lighting = false;
1769         if (ob && ob->type == OB_MESH)
1770                 GMS.two_sided_lighting = (((Mesh *)ob->data)->flag & ME_TWOSIDED) != 0;
1771
1772         GMS.gob = ob;
1773         GMS.gscene = scene;
1774         GMS.is_opensubdiv = use_opensubdiv;
1775         GMS.totmat = use_matcap ? 1 : ob->totcol + 1;  /* materials start from 1, default material is 0 */
1776         GMS.glay = (v3d->localvd) ? v3d->localvd->lay : v3d->lay; /* keep lamps visible in local view */
1777         GMS.gscenelock = (v3d->scenelock != 0);
1778         GMS.gviewmat = rv3d->viewmat;
1779         GMS.gviewinv = rv3d->viewinv;
1780         GMS.gviewcamtexcofac = rv3d->viewcamtexcofac;
1781
1782         /* alpha pass setup. there's various cases to handle here:
1783          * - object transparency on: only solid materials draw in the first pass,
1784          * and only transparent in the second 'alpha' pass.
1785          * - object transparency off: for glsl we draw both in a single pass, and
1786          * for solid we don't use transparency at all. */
1787         GMS.use_alpha_pass = (do_alpha_after != NULL);
1788         GMS.is_alpha_pass = (v3d->transp != false);
1789         if (GMS.use_alpha_pass)
1790                 *do_alpha_after = false;
1791         
1792         if (GMS.totmat > FIXEDMAT) {
1793                 GMS.matbuf = MEM_callocN(sizeof(GPUMaterialFixed) * GMS.totmat, "GMS.matbuf");
1794                 GMS.gmatbuf = MEM_callocN(sizeof(*GMS.gmatbuf) * GMS.totmat, "GMS.matbuf");
1795                 GMS.alphablend = MEM_callocN(sizeof(*GMS.alphablend) * GMS.totmat, "GMS.matbuf");
1796         }
1797         else {
1798                 GMS.matbuf = GMS.matbuf_fixed;
1799                 GMS.gmatbuf = GMS.gmatbuf_fixed;
1800                 GMS.alphablend = GMS.alphablend_fixed;
1801         }
1802
1803         /* viewport material, setup in space_view3d, defaults to matcap using ma->preview now */
1804         if (use_matcap) {
1805                 GMS.gmatbuf[0] = v3d->defmaterial;
1806                 GPU_material_matcap(scene, v3d->defmaterial, use_opensubdiv);
1807
1808                 /* do material 1 too, for displists! */
1809                 memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1810         
1811                 GMS.alphablend[0] = GPU_BLEND_SOLID;
1812         }
1813         else {
1814         
1815                 /* no materials assigned? */
1816                 if (ob->totcol == 0) {
1817                         gpu_material_to_fixed(&GMS.matbuf[0], &defmaterial, 0, ob, new_shading_nodes, true);
1818
1819                         /* do material 1 too, for displists! */
1820                         memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1821
1822                         if (glsl) {
1823                                 GMS.gmatbuf[0] = &defmaterial;
1824                                 GPU_material_from_blender(GMS.gscene, &defmaterial, GMS.is_opensubdiv);
1825                         }
1826
1827                         GMS.alphablend[0] = GPU_BLEND_SOLID;
1828                 }
1829                 
1830                 /* setup materials */
1831                 for (a = 1; a <= ob->totcol; a++) {
1832                         /* find a suitable material */
1833                         ma = give_current_material(ob, a);
1834                         if (!glsl && !new_shading_nodes) ma = gpu_active_node_material(ma);
1835                         if (ma == NULL) ma = &defmaterial;
1836
1837                         /* create glsl material if requested */
1838                         gpumat = glsl ? GPU_material_from_blender(GMS.gscene, ma, GMS.is_opensubdiv) : NULL;
1839
1840                         if (gpumat) {
1841                                 /* do glsl only if creating it succeed, else fallback */
1842                                 GMS.gmatbuf[a] = ma;
1843                                 alphablend = GPU_material_alpha_blend(gpumat, ob->col);
1844                         }
1845                         else {
1846                                 /* fixed function opengl materials */
1847                                 gpu_material_to_fixed(&GMS.matbuf[a], ma, gamma, ob, new_shading_nodes, false);
1848
1849                                 if (GMS.use_alpha_pass && ((ma->mode & MA_TRANSP) || (new_shading_nodes && ma->alpha != 1.0f))) {
1850                                         GMS.matbuf[a].alpha = ma->alpha;
1851                                         alphablend = (ma->alpha == 1.0f) ? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
1852                                 }
1853                                 else {
1854                                         GMS.matbuf[a].alpha = 1.0f;
1855                                         alphablend = GPU_BLEND_SOLID;
1856                                 }
1857                         }
1858
1859                         /* setting 'do_alpha_after = true' indicates this object needs to be
1860                          * drawn in a second alpha pass for improved blending */
1861                         if (do_alpha_after && !GMS.is_alpha_pass)
1862                                 if (ELEM(alphablend, GPU_BLEND_ALPHA, GPU_BLEND_ADD, GPU_BLEND_ALPHA_SORT))
1863                                         *do_alpha_after = true;
1864
1865                         GMS.alphablend[a] = alphablend;
1866                 }
1867         }
1868
1869         /* let's start with a clean state */
1870         GPU_object_material_unbind();
1871 }
1872
1873 static int GPU_get_particle_info(GPUParticleInfo *pi)
1874 {
1875         DupliObject *dob = GMS.dob;
1876         if (dob->particle_system) {
1877                 int ind;
1878                 if (dob->persistent_id[0] < dob->particle_system->totpart)
1879                         ind = dob->persistent_id[0];
1880                 else {
1881                         ind = dob->particle_system->child[dob->persistent_id[0] - dob->particle_system->totpart].parent;
1882                 }
1883                 if (ind >= 0) {
1884                         ParticleData *p = &dob->particle_system->particles[ind];
1885
1886                         pi->scalprops[0] = ind;
1887                         pi->scalprops[1] = GMS.gscene->r.cfra - p->time;
1888                         pi->scalprops[2] = p->lifetime;
1889                         pi->scalprops[3] = p->size;
1890
1891                         copy_v3_v3(pi->location, p->state.co);
1892                         copy_v3_v3(pi->velocity, p->state.vel);
1893                         copy_v3_v3(pi->angular_velocity, p->state.ave);
1894                         return 1;
1895                 }
1896                 else return 0;
1897         }
1898         else
1899                 return 0;
1900 }
1901
1902 int GPU_object_material_bind(int nr, void *attribs)
1903 {
1904         GPUVertexAttribs *gattribs = attribs;
1905
1906         /* no GPU_begin_object_materials, use default material */
1907         if (!GMS.matbuf) {
1908                 memset(&GMS, 0, sizeof(GMS));
1909
1910                 float diffuse[3], specular[3];
1911                 mul_v3_v3fl(diffuse, &defmaterial.r, defmaterial.ref + defmaterial.emit);
1912                 mul_v3_v3fl(specular, &defmaterial.specr, defmaterial.spec);
1913                 GPU_basic_shader_colors(diffuse, specular, 35, 1.0f);
1914
1915                 if (GMS.two_sided_lighting)
1916                         GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_TWO_SIDED);
1917                 else
1918                         GPU_basic_shader_bind(GPU_SHADER_LIGHTING);
1919
1920                 return 0;
1921         }
1922
1923         /* prevent index to use un-initialized array items */
1924         if (nr >= GMS.totmat)
1925                 nr = 0;
1926
1927         if (gattribs)
1928                 memset(gattribs, 0, sizeof(*gattribs));
1929
1930         /* keep current material */
1931         if (nr == GMS.lastmatnr)
1932                 return GMS.lastretval;
1933
1934         /* unbind glsl material */
1935         if (GMS.gboundmat) {
1936                 if (GMS.is_alpha_pass) glDepthMask(0);
1937                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
1938                 GMS.gboundmat = NULL;
1939         }
1940
1941         /* draw materials with alpha in alpha pass */
1942         GMS.lastmatnr = nr;
1943         GMS.lastretval = 1;
1944
1945         if (GMS.use_alpha_pass) {
1946                 GMS.lastretval = ELEM(GMS.alphablend[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
1947                 if (GMS.is_alpha_pass)
1948                         GMS.lastretval = !GMS.lastretval;
1949         }
1950         else
1951                 GMS.lastretval = !GMS.is_alpha_pass;
1952
1953         if (GMS.lastretval) {
1954                 /* for alpha pass, use alpha blend */
1955                 GPUBlendMode alphablend = GMS.alphablend[nr];
1956
1957                 if (gattribs && GMS.gmatbuf[nr]) {
1958                         /* bind glsl material and get attributes */
1959                         Material *mat = GMS.gmatbuf[nr];
1960                         GPUParticleInfo partile_info;
1961
1962                         float auto_bump_scale;
1963
1964                         GPUMaterial *gpumat = GPU_material_from_blender(GMS.gscene, mat, GMS.is_opensubdiv);
1965                         GPU_material_vertex_attributes(gpumat, gattribs);
1966
1967                         if (GMS.dob)
1968                                 GPU_get_particle_info(&partile_info);
1969
1970                         GPU_material_bind(
1971                                 gpumat, GMS.gob->lay, GMS.glay, 1.0, !(GMS.gob->mode & OB_MODE_TEXTURE_PAINT),
1972                                 GMS.gviewmat, GMS.gviewinv, GMS.gviewcamtexcofac, GMS.gscenelock);
1973
1974                         auto_bump_scale = GMS.gob->derivedFinal != NULL ? GMS.gob->derivedFinal->auto_bump_scale : 1.0f;
1975                         GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gob->col, auto_bump_scale, &partile_info);
1976                         GMS.gboundmat = mat;
1977
1978                         /* for glsl use alpha blend mode, unless it's set to solid and
1979                          * we are already drawing in an alpha pass */
1980                         if (mat->game.alpha_blend != GPU_BLEND_SOLID)
1981                                 alphablend = mat->game.alpha_blend;
1982
1983                         if (GMS.is_alpha_pass) glDepthMask(1);
1984
1985                         if (GMS.backface_culling) {
1986                                 if (mat->game.flag)
1987                                         glEnable(GL_CULL_FACE);
1988                                 else
1989                                         glDisable(GL_CULL_FACE);
1990                         }
1991
1992                         if (GMS.use_matcaps)
1993                                 glColor3f(1.0f, 1.0f, 1.0f);
1994                 }
1995                 else {
1996                         /* or do fixed function opengl material */
1997                         GPU_basic_shader_colors(
1998                                 GMS.matbuf[nr].diff,
1999                                 GMS.matbuf[nr].spec, GMS.matbuf[nr].hard, GMS.matbuf[nr].alpha);
2000
2001                         if (GMS.two_sided_lighting)
2002                                 GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_TWO_SIDED);
2003                         else
2004                                 GPU_basic_shader_bind(GPU_SHADER_LIGHTING);
2005                 }
2006
2007                 /* set (alpha) blending mode */
2008                 GPU_set_material_alpha_blend(alphablend);
2009         }
2010
2011         return GMS.lastretval;
2012 }
2013
2014 int GPU_object_material_visible(int nr, void *attribs)
2015 {
2016         GPUVertexAttribs *gattribs = attribs;
2017         int visible;
2018
2019         if (!GMS.matbuf)
2020                 return 0;
2021
2022         if (gattribs)
2023                 memset(gattribs, 0, sizeof(*gattribs));
2024
2025         if (nr >= GMS.totmat)
2026                 nr = 0;
2027
2028         if (GMS.use_alpha_pass) {
2029                 visible = ELEM(GMS.alphablend[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
2030                 if (GMS.is_alpha_pass)
2031                         visible = !visible;
2032         }
2033         else
2034                 visible = !GMS.is_alpha_pass;
2035
2036         return visible;
2037 }
2038
2039 void GPU_set_material_alpha_blend(int alphablend)
2040 {
2041         if (GMS.lastalphablend == alphablend)
2042                 return;
2043         
2044         gpu_set_alpha_blend(alphablend);
2045         GMS.lastalphablend = alphablend;
2046 }
2047
2048 int GPU_get_material_alpha_blend(void)
2049 {
2050         return GMS.lastalphablend;
2051 }
2052
2053 void GPU_object_material_unbind(void)
2054 {
2055         GMS.lastmatnr = -1;
2056         GMS.lastretval = 1;
2057
2058         if (GMS.gboundmat) {
2059                 if (GMS.backface_culling)
2060                         glDisable(GL_CULL_FACE);
2061
2062                 if (GMS.is_alpha_pass) glDepthMask(0);
2063                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
2064                 GMS.gboundmat = NULL;
2065         }
2066         else
2067                 GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
2068
2069         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
2070 }
2071
2072 void GPU_material_diffuse_get(int nr, float diff[4])
2073 {
2074         /* prevent index to use un-initialized array items */
2075         if (nr >= GMS.totmat)
2076                 nr = 0;
2077
2078         /* no GPU_begin_object_materials, use default material */
2079         if (!GMS.matbuf) {
2080                 mul_v3_v3fl(diff, &defmaterial.r, defmaterial.ref + defmaterial.emit);
2081         }
2082         else {
2083                 copy_v3_v3(diff, GMS.matbuf[nr].diff);
2084                 diff[3] = GMS.matbuf[nr].alpha;
2085         }
2086 }
2087
2088 bool GPU_material_use_matcaps_get(void)
2089 {
2090         return GMS.use_matcaps;
2091 }
2092
2093 bool GPU_object_materials_check(void)
2094 {
2095         return GMS.is_enabled;
2096 }
2097
2098 void GPU_end_object_materials(void)
2099 {
2100         GPU_object_material_unbind();
2101
2102         GMS.is_enabled = false;
2103
2104         if (GMS.matbuf && GMS.matbuf != GMS.matbuf_fixed) {
2105                 MEM_freeN(GMS.matbuf);
2106                 MEM_freeN(GMS.gmatbuf);
2107                 MEM_freeN(GMS.alphablend);
2108         }
2109
2110         GMS.matbuf = NULL;
2111         GMS.gmatbuf = NULL;
2112         GMS.alphablend = NULL;
2113         GMS.two_sided_lighting = false;
2114
2115         /* resetting the texture matrix after the scaling needed for tiled textures */
2116         if (GTS.tilemode) {
2117                 glMatrixMode(GL_TEXTURE);
2118                 glLoadIdentity();
2119                 glMatrixMode(GL_MODELVIEW);
2120         }
2121 }
2122
2123 /* Lights */
2124
2125 int GPU_default_lights(void)
2126 {
2127         /* initialize */
2128         if (U.light[0].flag == 0 && U.light[1].flag == 0 && U.light[2].flag == 0) {
2129                 U.light[0].flag = 1;
2130                 U.light[0].vec[0] = -0.3; U.light[0].vec[1] = 0.3; U.light[0].vec[2] = 0.9;
2131                 U.light[0].col[0] = 0.8; U.light[0].col[1] = 0.8; U.light[0].col[2] = 0.8;
2132                 U.light[0].spec[0] = 0.5; U.light[0].spec[1] = 0.5; U.light[0].spec[2] = 0.5;
2133                 U.light[0].spec[3] = 1.0;
2134                 
2135                 U.light[1].flag = 0;
2136                 U.light[1].vec[0] = 0.5; U.light[1].vec[1] = 0.5; U.light[1].vec[2] = 0.1;
2137                 U.light[1].col[0] = 0.4; U.light[1].col[1] = 0.4; U.light[1].col[2] = 0.8;
2138                 U.light[1].spec[0] = 0.3; U.light[1].spec[1] = 0.3; U.light[1].spec[2] = 0.5;
2139                 U.light[1].spec[3] = 1.0;
2140         
2141                 U.light[2].flag = 0;
2142                 U.light[2].vec[0] = 0.3; U.light[2].vec[1] = -0.3; U.light[2].vec[2] = -0.2;
2143                 U.light[2].col[0] = 0.8; U.light[2].col[1] = 0.5; U.light[2].col[2] = 0.4;
2144                 U.light[2].spec[0] = 0.5; U.light[2].spec[1] = 0.4; U.light[2].spec[2] = 0.3;
2145                 U.light[2].spec[3] = 1.0;
2146         }
2147
2148         GPU_basic_shader_light_set_viewer(false);
2149
2150         int count = 0;
2151
2152         for (int a = 0; a < 8; a++) {
2153                 if (a < 3 && U.light[a].flag) {
2154                         GPULightData light = {0};
2155
2156                         light.type = GPU_LIGHT_SUN;
2157
2158                         normalize_v3_v3(light.direction, U.light[a].vec);
2159                         copy_v3_v3(light.diffuse, U.light[a].col);
2160                         copy_v3_v3(light.specular, U.light[a].spec);
2161
2162                         GPU_basic_shader_light_set(a, &light);
2163
2164                         count++;
2165                 }
2166                 else
2167                         GPU_basic_shader_light_set(a, NULL);
2168         }
2169
2170         return count;
2171 }
2172
2173 int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[4][4], int ortho)
2174 {
2175         /* disable all lights */
2176         for (int count = 0; count < 8; count++)
2177                 GPU_basic_shader_light_set(count, NULL);
2178         
2179         /* view direction for specular is not computed correct by default in
2180          * opengl, so we set the settings ourselfs */
2181         GPU_basic_shader_light_set_viewer(!ortho);
2182
2183         int count = 0;
2184
2185         for (Base *base = scene->base.first; base; base = base->next) {
2186                 if (base->object->type != OB_LAMP)
2187                         continue;
2188
2189                 if (!(base->lay & lay) || !(base->lay & ob->lay))
2190                         continue;
2191
2192                 Lamp *la = base->object->data;
2193                 
2194                 /* setup lamp transform */
2195                 glPushMatrix();
2196                 glLoadMatrixf((float *)viewmat);
2197                 
2198                 /* setup light */
2199                 GPULightData light = {0};
2200
2201                 mul_v3_v3fl(light.diffuse, &la->r, la->energy);
2202                 mul_v3_v3fl(light.specular, &la->r, la->energy);
2203
2204                 if (la->type == LA_SUN) {
2205                         /* directional sun light */
2206                         light.type = GPU_LIGHT_SUN;
2207                         normalize_v3_v3(light.direction, base->object->obmat[2]);
2208                 }
2209                 else {
2210                         /* other lamps with position attenuation */
2211                         copy_v3_v3(light.position, base->object->obmat[3]);
2212
2213                         light.constant_attenuation = 1.0f;
2214                         light.linear_attenuation = la->att1 / la->dist;
2215                         light.quadratic_attenuation = la->att2 / (la->dist * la->dist);
2216                         
2217                         if (la->type == LA_SPOT) {
2218                                 light.type = GPU_LIGHT_SPOT;
2219                                 negate_v3_v3(light.direction, base->object->obmat[2]);
2220                                 normalize_v3(light.direction);
2221                                 light.spot_cutoff = RAD2DEGF(la->spotsize * 0.5f);
2222                                 light.spot_exponent = 128.0f * la->spotblend;
2223                         }
2224                         else
2225                                 light.type = GPU_LIGHT_POINT;
2226                 }
2227                 
2228                 GPU_basic_shader_light_set(count, &light);
2229                 
2230                 glPopMatrix();
2231                 
2232                 count++;
2233                 if (count == 8)
2234                         break;
2235         }
2236
2237         return count;
2238 }
2239
2240 static void gpu_multisample(bool enable)
2241 {
2242 #ifdef __linux__
2243         /* changing multisample from the default (enabled) causes problems on some
2244          * systems (NVIDIA/Linux) when the pixel format doesn't have a multisample buffer */
2245         bool toggle_ok = true;
2246
2247         if (GPU_type_matches(GPU_DEVICE_NVIDIA, GPU_OS_UNIX, GPU_DRIVER_ANY)) {
2248                 int samples = 0;
2249                 glGetIntegerv(GL_SAMPLES, &samples);
2250
2251                 if (samples == 0)
2252                         toggle_ok = false;
2253         }
2254
2255         if (toggle_ok) {
2256                 if (enable)
2257                         glEnable(GL_MULTISAMPLE);
2258                 else
2259                         glDisable(GL_MULTISAMPLE);
2260         }
2261 #else
2262         if (enable)
2263                 glEnable(GL_MULTISAMPLE);
2264         else
2265                 glDisable(GL_MULTISAMPLE);
2266 #endif
2267 }
2268
2269 /* Default OpenGL State
2270  *
2271  * This is called on startup, for opengl offscreen render and to restore state
2272  * for the game engine. Generally we should always return to this state when
2273  * temporarily modifying the state for drawing, though that are (undocumented)
2274  * exceptions that we should try to get rid of. */
2275
2276 void GPU_state_init(void)
2277 {
2278         float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
2279         float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
2280         
2281         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
2282         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
2283         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
2284         glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 35);
2285         glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
2286
2287         GPU_default_lights();
2288         
2289         glDepthFunc(GL_LEQUAL);
2290         /* scaling matrices */
2291         glEnable(GL_NORMALIZE);
2292
2293         glDisable(GL_ALPHA_TEST);
2294         glDisable(GL_BLEND);
2295         glDisable(GL_DEPTH_TEST);
2296         glDisable(GL_FOG);
2297         glDisable(GL_LIGHTING);
2298         glDisable(GL_COLOR_MATERIAL);
2299         glDisable(GL_LOGIC_OP);
2300         glDisable(GL_STENCIL_TEST);
2301         glDisable(GL_TEXTURE_1D);
2302         glDisable(GL_TEXTURE_2D);
2303         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
2304
2305         /* default disabled, enable should be local per function */
2306         glDisableClientState(GL_VERTEX_ARRAY);
2307         glDisableClientState(GL_NORMAL_ARRAY);
2308         glDisableClientState(GL_COLOR_ARRAY);
2309         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2310         
2311         glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
2312         glPixelTransferi(GL_RED_SCALE, 1);
2313         glPixelTransferi(GL_RED_BIAS, 0);
2314         glPixelTransferi(GL_GREEN_SCALE, 1);
2315         glPixelTransferi(GL_GREEN_BIAS, 0);
2316         glPixelTransferi(GL_BLUE_SCALE, 1);
2317         glPixelTransferi(GL_BLUE_BIAS, 0);
2318         glPixelTransferi(GL_ALPHA_SCALE, 1);
2319         glPixelTransferi(GL_ALPHA_BIAS, 0);
2320         
2321         glPixelTransferi(GL_DEPTH_BIAS, 0);
2322         glPixelTransferi(GL_DEPTH_SCALE, 1);
2323         glDepthRange(0.0, 1.0);
2324
2325         glMatrixMode(GL_TEXTURE);
2326         glLoadIdentity();
2327         glMatrixMode(GL_MODELVIEW);
2328
2329         glFrontFace(GL_CCW);
2330         glCullFace(GL_BACK);
2331         glDisable(GL_CULL_FACE);
2332
2333         gpu_multisample(false);
2334
2335         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
2336 }
2337
2338 #ifdef WITH_OPENSUBDIV
2339 /* Update face-varying variables offset which might be
2340  * different from mesh to mesh sharing the same material.
2341  */
2342 void GPU_draw_update_fvar_offset(DerivedMesh *dm)
2343 {
2344         /* Sanity check to be sure we only do this for OpenSubdiv draw. */
2345         BLI_assert(dm->type == DM_TYPE_CCGDM);
2346         BLI_assert(GMS.is_opensubdiv);
2347
2348         for (int i = 0; i < GMS.totmat; ++i) {
2349                 Material *material = GMS.gmatbuf[i];
2350                 GPUMaterial *gpu_material;
2351
2352                 if (material == NULL) {
2353                         continue;
2354                 }
2355
2356                 gpu_material = GPU_material_from_blender(GMS.gscene,
2357                                                          material,
2358                                                          GMS.is_opensubdiv);
2359
2360                 GPU_material_update_fvar_offset(gpu_material, dm);
2361         }
2362 }
2363 #endif