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