Merge branch 'master' into blender2.8
[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_hash.h"
43 #include "BLI_linklist.h"
44 #include "BLI_math.h"
45 #include "BLI_threads.h"
46 #include "BLI_utildefines.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                 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, 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         eObjectMode gob_object_mode;
1464         DupliObject *dob;
1465         Scene *gscene;
1466         int glay;
1467         float (*gviewmat)[4];
1468         float (*gviewinv)[4];
1469         float (*gviewcamtexcofac);
1470
1471         bool backface_culling;
1472         bool two_sided_lighting;
1473
1474         GPUBlendMode *alphablend;
1475         GPUBlendMode alphablend_fixed[FIXEDMAT];
1476         bool use_alpha_pass, is_alpha_pass;
1477         bool use_matcaps;
1478
1479         int lastmatnr, lastretval;
1480         GPUBlendMode lastalphablend;
1481         bool is_opensubdiv;
1482 } GMS = {NULL};
1483
1484 /* fixed function material, alpha handed by caller */
1485 static void gpu_material_to_fixed(
1486         GPUMaterialFixed *smat, const Material *bmat, const int gamma, const Object *ob,
1487         const int new_shading_nodes, const bool dimdown)
1488 {
1489         if (bmat->mode & MA_SHLESS) {
1490                 copy_v3_v3(smat->diff, &bmat->r);
1491
1492                 if (gamma)
1493                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1494
1495                 zero_v3(smat->spec);
1496                 smat->alpha = 1.0f;
1497                 smat->hard = 0;
1498         }
1499         else if (new_shading_nodes) {
1500                 copy_v3_v3(smat->diff, &bmat->r);
1501                 copy_v3_v3(smat->spec, &bmat->specr);
1502                 smat->alpha = 1.0f;
1503                 smat->hard = CLAMPIS(bmat->har, 0, 128);
1504
1505                 if (dimdown) {
1506                         mul_v3_fl(smat->diff, 0.8f);
1507                         mul_v3_fl(smat->spec, 0.5f);
1508                 }
1509
1510                 if (gamma) {
1511                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1512                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1513                 }
1514         }
1515         else {
1516                 mul_v3_v3fl(smat->diff, &bmat->r, bmat->ref + bmat->emit);
1517
1518                 if (bmat->shade_flag & MA_OBCOLOR)
1519                         mul_v3_v3(smat->diff, ob->col);
1520
1521                 mul_v3_v3fl(smat->spec, &bmat->specr, bmat->spec);
1522                 smat->hard = CLAMPIS(bmat->har, 1, 128);
1523                 smat->alpha = 1.0f;
1524
1525                 if (gamma) {
1526                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1527                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1528                 }
1529         }
1530 }
1531
1532 static Material *gpu_active_node_material(Material *ma)
1533 {
1534         if (ma && ma->use_nodes && ma->nodetree) {
1535                 bNode *node = nodeGetActiveID(ma->nodetree, ID_MA);
1536
1537                 if (node)
1538                         return (Material *)node->id;
1539                 else
1540                         return NULL;
1541         }
1542
1543         return ma;
1544 }
1545
1546 void GPU_begin_dupli_object(DupliObject *dob)
1547 {
1548         GMS.dob = dob;
1549 }
1550
1551 void GPU_end_dupli_object(void)
1552 {
1553         GMS.dob = NULL;
1554 }
1555
1556 void GPU_begin_object_materials(
1557         View3D *v3d, RegionView3D *rv3d, Scene *scene, ViewLayer *view_layer, Object *ob,
1558         bool glsl, const eObjectMode object_mode, bool *do_alpha_after)
1559 {
1560         Material *ma;
1561         GPUMaterial *gpumat;
1562         GPUBlendMode alphablend;
1563         DupliObject *dob;
1564         int a;
1565         const bool gamma = BKE_scene_check_color_management_enabled(scene);
1566         const bool new_shading_nodes = BKE_scene_use_new_shading_nodes(scene);
1567         const bool use_matcap = (v3d->flag2 & V3D_SHOW_SOLID_MATCAP) != 0;  /* assumes v3d->defmaterial->preview is set */
1568         bool use_opensubdiv = false;
1569
1570 #ifdef WITH_OPENSUBDIV
1571         {
1572                 DerivedMesh *derivedFinal = NULL;
1573                 if (ob->type == OB_MESH) {
1574                         Mesh *me = ob->data;
1575                         BMEditMesh *em = me->edit_btmesh;
1576                         if (em != NULL) {
1577                                 derivedFinal = em->derivedFinal;
1578                         }
1579                         else {
1580                                 derivedFinal = ob->derivedFinal;
1581                         }
1582                 }
1583                 else {
1584                         derivedFinal = ob->derivedFinal;
1585                 }
1586
1587                 if (derivedFinal != NULL && derivedFinal->type == DM_TYPE_CCGDM) {
1588                         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) derivedFinal;
1589                         use_opensubdiv = ccgdm->useGpuBackend;
1590                 }
1591         }
1592 #endif
1593
1594 #ifdef WITH_GAMEENGINE
1595         if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1596                 ob = BKE_object_lod_matob_get(ob, view_layer, object_mode);
1597         }
1598 #else
1599         UNUSED_VARS(view_layer);
1600 #endif
1601
1602         /* initialize state */
1603         /* DupliObject must be restored */
1604         dob = GMS.dob;
1605         memset(&GMS, 0, sizeof(GMS));
1606         GMS.is_enabled = true;
1607         GMS.dob = dob;
1608         GMS.lastmatnr = -1;
1609         GMS.lastretval = -1;
1610         GMS.lastalphablend = GPU_BLEND_SOLID;
1611         GMS.use_matcaps = use_matcap;
1612
1613         GMS.backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
1614
1615         GMS.two_sided_lighting = false;
1616         if (ob && ob->type == OB_MESH)
1617                 GMS.two_sided_lighting = (((Mesh *)ob->data)->flag & ME_TWOSIDED) != 0;
1618
1619         GMS.gob = ob;
1620         GMS.gob_object_mode = object_mode;
1621         GMS.gscene = scene;
1622         GMS.is_opensubdiv = use_opensubdiv;
1623         GMS.totmat = use_matcap ? 1 : ob->totcol + 1;  /* materials start from 1, default material is 0 */
1624         GMS.glay = (v3d->localvd) ? v3d->localvd->lay : v3d->lay; /* keep lamps visible in local view */
1625         GMS.gviewmat = rv3d->viewmat;
1626         GMS.gviewinv = rv3d->viewinv;
1627         GMS.gviewcamtexcofac = rv3d->viewcamtexcofac;
1628
1629         /* alpha pass setup. there's various cases to handle here:
1630          * - object transparency on: only solid materials draw in the first pass,
1631          * and only transparent in the second 'alpha' pass.
1632          * - object transparency off: for glsl we draw both in a single pass, and
1633          * for solid we don't use transparency at all. */
1634         GMS.use_alpha_pass = (do_alpha_after != NULL);
1635         GMS.is_alpha_pass = (v3d->transp != false);
1636         if (GMS.use_alpha_pass)
1637                 *do_alpha_after = false;
1638
1639         if (GMS.totmat > FIXEDMAT) {
1640                 GMS.matbuf = MEM_callocN(sizeof(GPUMaterialFixed) * GMS.totmat, "GMS.matbuf");
1641                 GMS.gmatbuf = MEM_callocN(sizeof(*GMS.gmatbuf) * GMS.totmat, "GMS.matbuf");
1642                 GMS.alphablend = MEM_callocN(sizeof(*GMS.alphablend) * GMS.totmat, "GMS.matbuf");
1643         }
1644         else {
1645                 GMS.matbuf = GMS.matbuf_fixed;
1646                 GMS.gmatbuf = GMS.gmatbuf_fixed;
1647                 GMS.alphablend = GMS.alphablend_fixed;
1648         }
1649
1650         /* viewport material, setup in space_view3d, defaults to matcap using ma->preview now */
1651         if (use_matcap) {
1652                 GMS.gmatbuf[0] = v3d->defmaterial;
1653                 GPU_material_matcap(scene, v3d->defmaterial, use_opensubdiv);
1654
1655                 /* do material 1 too, for displists! */
1656                 memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1657
1658                 GMS.alphablend[0] = GPU_BLEND_SOLID;
1659         }
1660         else {
1661
1662                 /* no materials assigned? */
1663                 if (ob->totcol == 0) {
1664                         gpu_material_to_fixed(&GMS.matbuf[0], &defmaterial, 0, ob, new_shading_nodes, true);
1665
1666                         /* do material 1 too, for displists! */
1667                         memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1668
1669                         if (glsl) {
1670                                 GMS.gmatbuf[0] = &defmaterial;
1671                                 GPU_material_from_blender(GMS.gscene, &defmaterial, GMS.is_opensubdiv);
1672                         }
1673
1674                         GMS.alphablend[0] = GPU_BLEND_SOLID;
1675                 }
1676
1677                 /* setup materials */
1678                 for (a = 1; a <= ob->totcol; a++) {
1679                         /* find a suitable material */
1680                         ma = give_current_material(ob, a);
1681                         if (!glsl && !new_shading_nodes) ma = gpu_active_node_material(ma);
1682                         if (ma == NULL) ma = &defmaterial;
1683
1684                         /* create glsl material if requested */
1685                         gpumat = glsl ? GPU_material_from_blender(GMS.gscene, ma, GMS.is_opensubdiv) : NULL;
1686
1687                         if (gpumat) {
1688                                 /* do glsl only if creating it succeed, else fallback */
1689                                 GMS.gmatbuf[a] = ma;
1690                                 alphablend = GPU_material_alpha_blend(gpumat, ob->col);
1691                         }
1692                         else {
1693                                 /* fixed function opengl materials */
1694                                 gpu_material_to_fixed(&GMS.matbuf[a], ma, gamma, ob, new_shading_nodes, false);
1695
1696                                 if (GMS.use_alpha_pass && ((ma->mode & MA_TRANSP) || (new_shading_nodes && ma->alpha != 1.0f))) {
1697                                         GMS.matbuf[a].alpha = ma->alpha;
1698                                         alphablend = (ma->alpha == 1.0f) ? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
1699                                 }
1700                                 else {
1701                                         GMS.matbuf[a].alpha = 1.0f;
1702                                         alphablend = GPU_BLEND_SOLID;
1703                                 }
1704                         }
1705
1706                         /* setting 'do_alpha_after = true' indicates this object needs to be
1707                          * drawn in a second alpha pass for improved blending */
1708                         if (do_alpha_after && !GMS.is_alpha_pass)
1709                                 if (ELEM(alphablend, GPU_BLEND_ALPHA, GPU_BLEND_ADD, GPU_BLEND_ALPHA_SORT))
1710                                         *do_alpha_after = true;
1711
1712                         GMS.alphablend[a] = alphablend;
1713                 }
1714         }
1715
1716         /* let's start with a clean state */
1717         GPU_object_material_unbind();
1718 }
1719
1720 static int gpu_get_particle_info(GPUParticleInfo *pi)
1721 {
1722         DupliObject *dob = GMS.dob;
1723         if (dob->particle_system) {
1724                 int ind;
1725                 if (dob->persistent_id[0] < dob->particle_system->totpart)
1726                         ind = dob->persistent_id[0];
1727                 else {
1728                         ind = dob->particle_system->child[dob->persistent_id[0] - dob->particle_system->totpart].parent;
1729                 }
1730                 if (ind >= 0) {
1731                         ParticleData *p = &dob->particle_system->particles[ind];
1732
1733                         pi->scalprops[0] = BLI_hash_int_01(ind);
1734                         pi->scalprops[1] = GMS.gscene->r.cfra - p->time;
1735                         pi->scalprops[2] = p->lifetime;
1736                         pi->scalprops[3] = p->size;
1737
1738                         copy_v3_v3(pi->location, p->state.co);
1739                         copy_v3_v3(pi->velocity, p->state.vel);
1740                         copy_v3_v3(pi->angular_velocity, p->state.ave);
1741                         return 1;
1742                 }
1743                 else return 0;
1744         }
1745         else
1746                 return 0;
1747 }
1748
1749 static void GPU_get_object_info(float oi[3], Material *mat)
1750 {
1751         Object *ob = GMS.gob;
1752         oi[0] = ob->index;
1753         oi[1] = mat->index;
1754         unsigned int random;
1755         if (GMS.dob) {
1756                 random = GMS.dob->random_id;
1757         }
1758         else {
1759                 random = BLI_hash_int_2d(BLI_hash_string(GMS.gob->id.name + 2), 0);
1760         }
1761         oi[2] = random * (1.0f / (float)0xFFFFFFFF);
1762 }
1763
1764 int GPU_object_material_bind(int nr, void *attribs)
1765 {
1766         GPUVertexAttribs *gattribs = attribs;
1767
1768         /* no GPU_begin_object_materials, use default material */
1769         if (!GMS.matbuf) {
1770                 memset(&GMS, 0, sizeof(GMS));
1771
1772                 float diffuse[3], specular[3];
1773                 mul_v3_v3fl(diffuse, &defmaterial.r, defmaterial.ref + defmaterial.emit);
1774                 mul_v3_v3fl(specular, &defmaterial.specr, defmaterial.spec);
1775                 GPU_basic_shader_colors(diffuse, specular, 35, 1.0f);
1776
1777                 if (GMS.two_sided_lighting)
1778                         GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_TWO_SIDED);
1779                 else
1780                         GPU_basic_shader_bind(GPU_SHADER_LIGHTING);
1781
1782                 return 0;
1783         }
1784
1785         /* prevent index to use un-initialized array items */
1786         if (nr >= GMS.totmat)
1787                 nr = 0;
1788
1789         if (gattribs)
1790                 memset(gattribs, 0, sizeof(*gattribs));
1791
1792         /* keep current material */
1793         if (nr == GMS.lastmatnr)
1794                 return GMS.lastretval;
1795
1796         /* unbind glsl material */
1797         if (GMS.gboundmat) {
1798                 if (GMS.is_alpha_pass) glDepthMask(0);
1799                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
1800                 GMS.gboundmat = NULL;
1801         }
1802
1803         /* draw materials with alpha in alpha pass */
1804         GMS.lastmatnr = nr;
1805         GMS.lastretval = 1;
1806
1807         if (GMS.use_alpha_pass) {
1808                 GMS.lastretval = ELEM(GMS.alphablend[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
1809                 if (GMS.is_alpha_pass)
1810                         GMS.lastretval = !GMS.lastretval;
1811         }
1812         else
1813                 GMS.lastretval = !GMS.is_alpha_pass;
1814
1815         if (GMS.lastretval) {
1816                 /* for alpha pass, use alpha blend */
1817                 GPUBlendMode alphablend = GMS.alphablend[nr];
1818
1819                 if (gattribs && GMS.gmatbuf[nr]) {
1820                         /* bind glsl material and get attributes */
1821                         Material *mat = GMS.gmatbuf[nr];
1822                         GPUParticleInfo partile_info;
1823                         float object_info[3] = {0};
1824
1825                         float auto_bump_scale;
1826
1827                         GPUMaterial *gpumat = GPU_material_from_blender(GMS.gscene, mat, GMS.is_opensubdiv);
1828                         GPU_material_vertex_attributes(gpumat, gattribs);
1829
1830                         if (GMS.dob) {
1831                                 gpu_get_particle_info(&partile_info);
1832                         }
1833                         
1834                         if ((GPU_get_material_builtins(gpumat) & GPU_OBJECT_INFO) != 0) {
1835                                 GPU_get_object_info(object_info, mat);
1836                         }
1837
1838                         GPU_material_bind(
1839                                 gpumat, GMS.gob->lay, GMS.glay, 1.0, !(GMS.gob_object_mode & OB_MODE_TEXTURE_PAINT),
1840                                 GMS.gviewmat, GMS.gviewinv, GMS.gviewcamtexcofac);
1841
1842                         auto_bump_scale = GMS.gob->derivedFinal != NULL ? GMS.gob->derivedFinal->auto_bump_scale : 1.0f;
1843                         GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gob->col, auto_bump_scale, &partile_info, object_info);
1844                         GMS.gboundmat = mat;
1845
1846                         /* for glsl use alpha blend mode, unless it's set to solid and
1847                          * we are already drawing in an alpha pass */
1848                         if (mat->game.alpha_blend != GPU_BLEND_SOLID)
1849                                 alphablend = mat->game.alpha_blend;
1850
1851                         if (GMS.is_alpha_pass) glDepthMask(1);
1852
1853                         if (GMS.backface_culling) {
1854                                 if (mat->game.flag)
1855                                         glEnable(GL_CULL_FACE);
1856                                 else
1857                                         glDisable(GL_CULL_FACE);
1858                         }
1859
1860                         if (GMS.use_matcaps)
1861                                 glColor3f(1.0f, 1.0f, 1.0f);
1862                 }
1863                 else {
1864                         /* or do fixed function opengl material */
1865                         GPU_basic_shader_colors(
1866                                 GMS.matbuf[nr].diff,
1867                                 GMS.matbuf[nr].spec, GMS.matbuf[nr].hard, GMS.matbuf[nr].alpha);
1868
1869                         if (GMS.two_sided_lighting)
1870                                 GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_TWO_SIDED);
1871                         else
1872                                 GPU_basic_shader_bind(GPU_SHADER_LIGHTING);
1873                 }
1874
1875                 /* set (alpha) blending mode */
1876                 GPU_set_material_alpha_blend(alphablend);
1877         }
1878
1879         return GMS.lastretval;
1880 }
1881
1882 int GPU_object_material_visible(int nr, void *attribs)
1883 {
1884         GPUVertexAttribs *gattribs = attribs;
1885         int visible;
1886
1887         if (!GMS.matbuf)
1888                 return 0;
1889
1890         if (gattribs)
1891                 memset(gattribs, 0, sizeof(*gattribs));
1892
1893         if (nr >= GMS.totmat)
1894                 nr = 0;
1895
1896         if (GMS.use_alpha_pass) {
1897                 visible = ELEM(GMS.alphablend[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
1898                 if (GMS.is_alpha_pass)
1899                         visible = !visible;
1900         }
1901         else
1902                 visible = !GMS.is_alpha_pass;
1903
1904         return visible;
1905 }
1906
1907 void GPU_set_material_alpha_blend(int alphablend)
1908 {
1909         if (GMS.lastalphablend == alphablend)
1910                 return;
1911
1912         gpu_set_alpha_blend(alphablend);
1913         GMS.lastalphablend = alphablend;
1914 }
1915
1916 int GPU_get_material_alpha_blend(void)
1917 {
1918         return GMS.lastalphablend;
1919 }
1920
1921 void GPU_object_material_unbind(void)
1922 {
1923         GMS.lastmatnr = -1;
1924         GMS.lastretval = 1;
1925
1926         if (GMS.gboundmat) {
1927                 if (GMS.backface_culling)
1928                         glDisable(GL_CULL_FACE);
1929
1930                 if (GMS.is_alpha_pass) glDepthMask(0);
1931                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
1932                 GMS.gboundmat = NULL;
1933         }
1934         else
1935                 GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1936
1937         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
1938 }
1939
1940 void GPU_material_diffuse_get(int nr, float diff[4])
1941 {
1942         /* prevent index to use un-initialized array items */
1943         if (nr >= GMS.totmat)
1944                 nr = 0;
1945
1946         /* no GPU_begin_object_materials, use default material */
1947         if (!GMS.matbuf) {
1948                 mul_v3_v3fl(diff, &defmaterial.r, defmaterial.ref + defmaterial.emit);
1949         }
1950         else {
1951                 copy_v3_v3(diff, GMS.matbuf[nr].diff);
1952                 diff[3] = GMS.matbuf[nr].alpha;
1953         }
1954 }
1955
1956 bool GPU_material_use_matcaps_get(void)
1957 {
1958         return GMS.use_matcaps;
1959 }
1960
1961 bool GPU_object_materials_check(void)
1962 {
1963         return GMS.is_enabled;
1964 }
1965
1966 void GPU_end_object_materials(void)
1967 {
1968         GPU_object_material_unbind();
1969
1970         GMS.is_enabled = false;
1971
1972         if (GMS.matbuf && GMS.matbuf != GMS.matbuf_fixed) {
1973                 MEM_freeN(GMS.matbuf);
1974                 MEM_freeN(GMS.gmatbuf);
1975                 MEM_freeN(GMS.alphablend);
1976         }
1977
1978         GMS.matbuf = NULL;
1979         GMS.gmatbuf = NULL;
1980         GMS.alphablend = NULL;
1981         GMS.two_sided_lighting = false;
1982 }
1983
1984 /* Lights */
1985
1986 int GPU_default_lights(void)
1987 {
1988         /* initialize */
1989         if (U.light[0].flag == 0 && U.light[1].flag == 0 && U.light[2].flag == 0) {
1990                 U.light[0].flag = 1;
1991                 U.light[0].vec[0] = -0.3; U.light[0].vec[1] = 0.3; U.light[0].vec[2] = 0.9;
1992                 U.light[0].col[0] = 0.8; U.light[0].col[1] = 0.8; U.light[0].col[2] = 0.8;
1993                 U.light[0].spec[0] = 0.5; U.light[0].spec[1] = 0.5; U.light[0].spec[2] = 0.5;
1994                 U.light[0].spec[3] = 1.0;
1995
1996                 U.light[1].flag = 0;
1997                 U.light[1].vec[0] = 0.5; U.light[1].vec[1] = 0.5; U.light[1].vec[2] = 0.1;
1998                 U.light[1].col[0] = 0.4; U.light[1].col[1] = 0.4; U.light[1].col[2] = 0.8;
1999                 U.light[1].spec[0] = 0.3; U.light[1].spec[1] = 0.3; U.light[1].spec[2] = 0.5;
2000                 U.light[1].spec[3] = 1.0;
2001
2002                 U.light[2].flag = 0;
2003                 U.light[2].vec[0] = 0.3; U.light[2].vec[1] = -0.3; U.light[2].vec[2] = -0.2;
2004                 U.light[2].col[0] = 0.8; U.light[2].col[1] = 0.5; U.light[2].col[2] = 0.4;
2005                 U.light[2].spec[0] = 0.5; U.light[2].spec[1] = 0.4; U.light[2].spec[2] = 0.3;
2006                 U.light[2].spec[3] = 1.0;
2007         }
2008
2009         GPU_basic_shader_light_set_viewer(false);
2010
2011         int count = 0;
2012
2013         for (int a = 0; a < 8; a++) {
2014                 if (a < 3 && U.light[a].flag) {
2015                         GPULightData light = {0};
2016
2017                         light.type = GPU_LIGHT_SUN;
2018
2019                         normalize_v3_v3(light.direction, U.light[a].vec);
2020                         copy_v3_v3(light.diffuse, U.light[a].col);
2021                         copy_v3_v3(light.specular, U.light[a].spec);
2022
2023                         GPU_basic_shader_light_set(a, &light);
2024
2025                         count++;
2026                 }
2027                 else
2028                         GPU_basic_shader_light_set(a, NULL);
2029         }
2030
2031         return count;
2032 }
2033
2034 int GPU_scene_object_lights(ViewLayer *view_layer, float viewmat[4][4], int ortho)
2035 {
2036         /* disable all lights */
2037         for (int count = 0; count < 8; count++)
2038                 GPU_basic_shader_light_set(count, NULL);
2039
2040         /* view direction for specular is not computed correct by default in
2041          * opengl, so we set the settings ourselves */
2042         GPU_basic_shader_light_set_viewer(!ortho);
2043
2044         int count = 0;
2045
2046         for (Base *base = FIRSTBASE(view_layer); base; base = base->next) {
2047                 if (base->object->type != OB_LAMP)
2048                         continue;
2049
2050                 Lamp *la = base->object->data;
2051
2052                 /* setup lamp transform */
2053                 gpuPushMatrix();
2054                 gpuLoadMatrix(viewmat);
2055
2056                 /* setup light */
2057                 GPULightData light = {0};
2058
2059                 mul_v3_v3fl(light.diffuse, &la->r, la->energy);
2060                 mul_v3_v3fl(light.specular, &la->r, la->energy);
2061
2062                 if (la->type == LA_SUN) {
2063                         /* directional sun light */
2064                         light.type = GPU_LIGHT_SUN;
2065                         normalize_v3_v3(light.direction, base->object->obmat[2]);
2066                 }
2067                 else {
2068                         /* other lamps with position attenuation */
2069                         copy_v3_v3(light.position, base->object->obmat[3]);
2070
2071                         light.constant_attenuation = 1.0f;
2072                         light.linear_attenuation = la->att1 / la->dist;
2073                         light.quadratic_attenuation = la->att2 / (la->dist * la->dist);
2074
2075                         if (la->type == LA_SPOT) {
2076                                 light.type = GPU_LIGHT_SPOT;
2077                                 negate_v3_v3(light.direction, base->object->obmat[2]);
2078                                 normalize_v3(light.direction);
2079                                 light.spot_cutoff = RAD2DEGF(la->spotsize * 0.5f);
2080                                 light.spot_exponent = 128.0f * la->spotblend;
2081                         }
2082                         else
2083                                 light.type = GPU_LIGHT_POINT;
2084                 }
2085
2086                 GPU_basic_shader_light_set(count, &light);
2087
2088                 gpuPopMatrix();
2089
2090                 count++;
2091                 if (count == 8)
2092                         break;
2093         }
2094
2095         return count;
2096 }
2097
2098 static void gpu_disable_multisample()
2099 {
2100 #ifdef __linux__
2101         /* changing multisample from the default (enabled) causes problems on some
2102          * systems (NVIDIA/Linux) when the pixel format doesn't have a multisample buffer */
2103         bool toggle_ok = true;
2104
2105         if (GPU_type_matches(GPU_DEVICE_NVIDIA, GPU_OS_UNIX, GPU_DRIVER_ANY)) {
2106                 int samples = 0;
2107                 glGetIntegerv(GL_SAMPLES, &samples);
2108
2109                 if (samples == 0)
2110                         toggle_ok = false;
2111         }
2112
2113         if (toggle_ok) {
2114                 glDisable(GL_MULTISAMPLE);
2115         }
2116 #else
2117         glDisable(GL_MULTISAMPLE);
2118 #endif
2119 }
2120
2121 /* Default OpenGL State
2122  *
2123  * This is called on startup, for opengl offscreen render and to restore state
2124  * for the game engine. Generally we should always return to this state when
2125  * temporarily modifying the state for drawing, though that are (undocumented)
2126  * exceptions that we should try to get rid of. */
2127
2128 void GPU_state_init(void)
2129 {
2130         GPU_default_lights();
2131
2132         GPU_disable_program_point_size();
2133
2134         glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2135
2136         glDepthFunc(GL_LEQUAL);
2137
2138         glDisable(GL_BLEND);
2139         glDisable(GL_DEPTH_TEST);
2140         glDisable(GL_COLOR_LOGIC_OP);
2141         glDisable(GL_STENCIL_TEST);
2142
2143         glDepthRange(0.0, 1.0);
2144
2145         glFrontFace(GL_CCW);
2146         glCullFace(GL_BACK);
2147         glDisable(GL_CULL_FACE);
2148
2149         gpu_disable_multisample();
2150 }
2151
2152 void GPU_enable_program_point_size(void)
2153 {
2154         glEnable(GL_PROGRAM_POINT_SIZE);
2155 }
2156
2157 void GPU_disable_program_point_size(void)
2158 {
2159         glDisable(GL_PROGRAM_POINT_SIZE);
2160 }
2161
2162 #ifdef WITH_OPENSUBDIV
2163 /* Update face-varying variables offset which might be
2164  * different from mesh to mesh sharing the same material.
2165  */
2166 void GPU_draw_update_fvar_offset(DerivedMesh *dm)
2167 {
2168         /* Sanity check to be sure we only do this for OpenSubdiv draw. */
2169         BLI_assert(dm->type == DM_TYPE_CCGDM);
2170         BLI_assert(GMS.is_opensubdiv);
2171
2172         for (int i = 0; i < GMS.totmat; ++i) {
2173                 Material *material = GMS.gmatbuf[i];
2174                 GPUMaterial *gpu_material;
2175
2176                 if (material == NULL) {
2177                         continue;
2178                 }
2179
2180                 gpu_material = GPU_material_from_blender(GMS.gscene,
2181                                                          material,
2182                                                          GMS.is_opensubdiv);
2183
2184                 GPU_material_update_fvar_offset(gpu_material, dm);
2185         }
2186 }
2187 #endif
2188
2189
2190 /** \name Framebuffer color depth, for selection codes
2191  * \{ */
2192
2193 #ifdef __APPLE__
2194
2195 /* apple seems to round colors to below and up on some configs */
2196
2197 static unsigned int index_to_framebuffer(int index)
2198 {
2199         unsigned int i = index;
2200
2201         switch (GPU_color_depth()) {
2202                 case 12:
2203                         i = ((i & 0xF00) << 12) + ((i & 0xF0) << 8) + ((i & 0xF) << 4);
2204                         /* sometimes dithering subtracts! */
2205                         i |= 0x070707;
2206                         break;
2207                 case 15:
2208                 case 16:
2209                         i = ((i & 0x7C00) << 9) + ((i & 0x3E0) << 6) + ((i & 0x1F) << 3);
2210                         i |= 0x030303;
2211                         break;
2212                 case 24:
2213                         break;
2214                 default: /* 18 bits... */
2215                         i = ((i & 0x3F000) << 6) + ((i & 0xFC0) << 4) + ((i & 0x3F) << 2);
2216                         i |= 0x010101;
2217                         break;
2218         }
2219
2220         return i;
2221 }
2222
2223 #else
2224
2225 /* this is the old method as being in use for ages.... seems to work? colors are rounded to lower values */
2226
2227 static unsigned int index_to_framebuffer(int index)
2228 {
2229         unsigned int i = index;
2230
2231         switch (GPU_color_depth()) {
2232                 case 8:
2233                         i = ((i & 48) << 18) + ((i & 12) << 12) + ((i & 3) << 6);
2234                         i |= 0x3F3F3F;
2235                         break;
2236                 case 12:
2237                         i = ((i & 0xF00) << 12) + ((i & 0xF0) << 8) + ((i & 0xF) << 4);
2238                         /* sometimes dithering subtracts! */
2239                         i |= 0x0F0F0F;
2240                         break;
2241                 case 15:
2242                 case 16:
2243                         i = ((i & 0x7C00) << 9) + ((i & 0x3E0) << 6) + ((i & 0x1F) << 3);
2244                         i |= 0x070707;
2245                         break;
2246                 case 24:
2247                         break;
2248                 default:    /* 18 bits... */
2249                         i = ((i & 0x3F000) << 6) + ((i & 0xFC0) << 4) + ((i & 0x3F) << 2);
2250                         i |= 0x030303;
2251                         break;
2252         }
2253
2254         return i;
2255 }
2256
2257 #endif
2258
2259
2260 void GPU_select_index_set(int index)
2261 {
2262         const int col = index_to_framebuffer(index);
2263         glColor3ub(( (col)        & 0xFF),
2264                    (((col) >>  8) & 0xFF),
2265                    (((col) >> 16) & 0xFF));
2266 }
2267
2268 void GPU_select_index_get(int index, int *r_col)
2269 {
2270         const int col = index_to_framebuffer(index);
2271         char *c_col = (char *)r_col;
2272         c_col[0] = (col & 0xFF); /* red */
2273         c_col[1] = ((col >>  8) & 0xFF); /* green */
2274         c_col[2] = ((col >> 16) & 0xFF); /* blue */
2275         c_col[3] = 0xFF; /* alpha */
2276 }
2277
2278
2279 #define INDEX_FROM_BUF_8(col)     ((((col) & 0xC00000) >> 18) + (((col) & 0xC000) >> 12) + (((col) & 0xC0) >> 6))
2280 #define INDEX_FROM_BUF_12(col)    ((((col) & 0xF00000) >> 12) + (((col) & 0xF000) >> 8)  + (((col) & 0xF0) >> 4))
2281 #define INDEX_FROM_BUF_15_16(col) ((((col) & 0xF80000) >> 9)  + (((col) & 0xF800) >> 6)  + (((col) & 0xF8) >> 3))
2282 #define INDEX_FROM_BUF_18(col)    ((((col) & 0xFC0000) >> 6)  + (((col) & 0xFC00) >> 4)  + (((col) & 0xFC) >> 2))
2283 #define INDEX_FROM_BUF_24(col)      ((col) & 0xFFFFFF)
2284
2285 int GPU_select_to_index(unsigned int col)
2286 {
2287         if (col == 0) {
2288                 return 0;
2289         }
2290
2291         switch (GPU_color_depth()) {
2292                 case  8: return INDEX_FROM_BUF_8(col);
2293                 case 12: return INDEX_FROM_BUF_12(col);
2294                 case 15:
2295                 case 16: return INDEX_FROM_BUF_15_16(col);
2296                 case 24: return INDEX_FROM_BUF_24(col);
2297                 default: return INDEX_FROM_BUF_18(col);
2298         }
2299 }
2300
2301 void GPU_select_to_index_array(unsigned int *col, const unsigned int size)
2302 {
2303 #define INDEX_BUF_ARRAY(INDEX_FROM_BUF_BITS) \
2304         for (i = size; i--; col++) { \
2305             if ((c = *col)) { \
2306                 *col = INDEX_FROM_BUF_BITS(c); \
2307         } \
2308     } ((void)0)
2309
2310         if (size > 0) {
2311                 unsigned int i, c;
2312
2313                 switch (GPU_color_depth()) {
2314                         case  8:
2315                                 INDEX_BUF_ARRAY(INDEX_FROM_BUF_8);
2316                                 break;
2317                         case 12:
2318                                 INDEX_BUF_ARRAY(INDEX_FROM_BUF_12);
2319                                 break;
2320                         case 15:
2321                         case 16:
2322                                 INDEX_BUF_ARRAY(INDEX_FROM_BUF_15_16);
2323                                 break;
2324                         case 24:
2325                                 INDEX_BUF_ARRAY(INDEX_FROM_BUF_24);
2326                                 break;
2327                         default:
2328                                 INDEX_BUF_ARRAY(INDEX_FROM_BUF_18);
2329                                 break;
2330                 }
2331         }
2332
2333 #undef INDEX_BUF_ARRAY
2334 }
2335
2336 #define STATE_STACK_DEPTH 16
2337
2338 typedef struct {
2339         eGPUAttribMask mask;
2340
2341         /* GL_ENABLE_BIT */
2342         unsigned int is_blend : 1;
2343         unsigned int is_cull_face : 1;
2344         unsigned int is_depth_test : 1;
2345         unsigned int is_dither : 1;
2346         unsigned int is_lighting : 1;
2347         unsigned int is_line_smooth : 1;
2348         unsigned int is_color_logic_op : 1;
2349         unsigned int is_multisample : 1;
2350         unsigned int is_polygon_offset_line : 1;
2351         unsigned int is_polygon_offset_fill : 1;
2352         unsigned int is_polygon_smooth : 1;
2353         unsigned int is_sample_alpha_to_coverage : 1;
2354         unsigned int is_scissor_test : 1;
2355         unsigned int is_stencil_test : 1;
2356
2357         bool is_clip_plane[6];
2358
2359         /* GL_DEPTH_BUFFER_BIT */
2360         /* unsigned int is_depth_test : 1; */
2361         int depth_func;
2362         double depth_clear_value;
2363         bool depth_write_mask;
2364
2365         /* GL_SCISSOR_BIT */
2366         int scissor_box[4];
2367         /* unsigned int is_scissor_test : 1; */
2368
2369         /* GL_VIEWPORT_BIT */
2370         int viewport[4];
2371         double near_far[2];
2372 }  GPUAttribValues;
2373
2374 typedef struct {
2375         GPUAttribValues attrib_stack[STATE_STACK_DEPTH];
2376         unsigned int top;
2377 } GPUAttribStack;
2378
2379 static GPUAttribStack state = {
2380         .top = 0
2381 };
2382
2383 #define AttribStack state
2384 #define Gwn_VertAttr state.attrib_stack[state.top]
2385
2386 /**
2387  * Replacement for glPush/PopAttributes
2388  *
2389  * We don't need to cover all the options of legacy OpenGL
2390  * but simply the ones used by Blender.
2391  */
2392 void gpuPushAttrib(eGPUAttribMask mask)
2393 {
2394         Gwn_VertAttr.mask = mask;
2395
2396         if ((mask & GPU_DEPTH_BUFFER_BIT) != 0) {
2397                 Gwn_VertAttr.is_depth_test = glIsEnabled(GL_DEPTH_TEST);
2398                 glGetIntegerv(GL_DEPTH_FUNC, &Gwn_VertAttr.depth_func);
2399                 glGetDoublev(GL_DEPTH_CLEAR_VALUE, &Gwn_VertAttr.depth_clear_value);
2400                 glGetBooleanv(GL_DEPTH_WRITEMASK, (GLboolean *)&Gwn_VertAttr.depth_write_mask);
2401         }
2402
2403         if ((mask & GPU_ENABLE_BIT) != 0) {
2404                 Gwn_VertAttr.is_blend = glIsEnabled(GL_BLEND);
2405
2406                 for (int i = 0; i < 6; i++) {
2407                         Gwn_VertAttr.is_clip_plane[i] = glIsEnabled(GL_CLIP_PLANE0 + i);
2408                 }
2409
2410                 Gwn_VertAttr.is_cull_face = glIsEnabled(GL_CULL_FACE);
2411                 Gwn_VertAttr.is_depth_test = glIsEnabled(GL_DEPTH_TEST);
2412                 Gwn_VertAttr.is_dither = glIsEnabled(GL_DITHER);
2413                 Gwn_VertAttr.is_line_smooth = glIsEnabled(GL_LINE_SMOOTH);
2414                 Gwn_VertAttr.is_color_logic_op = glIsEnabled(GL_COLOR_LOGIC_OP);
2415                 Gwn_VertAttr.is_multisample = glIsEnabled(GL_MULTISAMPLE);
2416                 Gwn_VertAttr.is_polygon_offset_line = glIsEnabled(GL_POLYGON_OFFSET_LINE);
2417                 Gwn_VertAttr.is_polygon_offset_fill = glIsEnabled(GL_POLYGON_OFFSET_FILL);
2418                 Gwn_VertAttr.is_polygon_smooth = glIsEnabled(GL_POLYGON_SMOOTH);
2419                 Gwn_VertAttr.is_sample_alpha_to_coverage = glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE);
2420                 Gwn_VertAttr.is_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
2421                 Gwn_VertAttr.is_stencil_test = glIsEnabled(GL_STENCIL_TEST);
2422         }
2423
2424         if ((mask & GPU_SCISSOR_BIT) != 0) {
2425                 Gwn_VertAttr.is_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
2426                 glGetIntegerv(GL_SCISSOR_BOX, (GLint *)&Gwn_VertAttr.scissor_box);
2427         }
2428
2429         if ((mask & GPU_VIEWPORT_BIT) != 0) {
2430                 glGetDoublev(GL_DEPTH_RANGE, (GLdouble *)&Gwn_VertAttr.near_far);
2431                 glGetIntegerv(GL_VIEWPORT, (GLint *)&Gwn_VertAttr.viewport);
2432         }
2433
2434         if ((mask & GPU_BLEND_BIT) != 0) {
2435                 Gwn_VertAttr.is_blend = glIsEnabled(GL_BLEND);
2436         }
2437
2438         BLI_assert(AttribStack.top < STATE_STACK_DEPTH);
2439         AttribStack.top++;
2440 }
2441
2442 static void restore_mask(GLenum cap, const bool value)
2443 {
2444         if (value) {
2445                 glEnable(cap);
2446         }
2447         else {
2448                 glDisable(cap);
2449         }
2450 }
2451
2452 void gpuPopAttrib(void)
2453 {
2454         BLI_assert(AttribStack.top > 0);
2455         AttribStack.top--;
2456
2457         GLint mask = Gwn_VertAttr.mask;
2458
2459         if ((mask & GPU_DEPTH_BUFFER_BIT) != 0) {
2460                 restore_mask(GL_DEPTH_TEST, Gwn_VertAttr.is_depth_test);
2461                 glDepthFunc(Gwn_VertAttr.depth_func);
2462                 glClearDepth(Gwn_VertAttr.depth_clear_value);
2463                 glDepthMask(Gwn_VertAttr.depth_write_mask);
2464         }
2465
2466         if ((mask & GPU_ENABLE_BIT) != 0) {
2467                 restore_mask(GL_BLEND, Gwn_VertAttr.is_blend);
2468
2469                 for (int i = 0; i < 6; i++) {
2470                         restore_mask(GL_CLIP_PLANE0 + i, Gwn_VertAttr.is_clip_plane[i]);
2471                 }
2472
2473                 restore_mask(GL_CULL_FACE, Gwn_VertAttr.is_cull_face);
2474                 restore_mask(GL_DEPTH_TEST, Gwn_VertAttr.is_depth_test);
2475                 restore_mask(GL_DITHER, Gwn_VertAttr.is_dither);
2476                 restore_mask(GL_LINE_SMOOTH, Gwn_VertAttr.is_line_smooth);
2477                 restore_mask(GL_COLOR_LOGIC_OP, Gwn_VertAttr.is_color_logic_op);
2478                 restore_mask(GL_MULTISAMPLE, Gwn_VertAttr.is_multisample);
2479                 restore_mask(GL_POLYGON_OFFSET_LINE, Gwn_VertAttr.is_polygon_offset_line);
2480                 restore_mask(GL_POLYGON_OFFSET_FILL, Gwn_VertAttr.is_polygon_offset_fill);
2481                 restore_mask(GL_POLYGON_SMOOTH, Gwn_VertAttr.is_polygon_smooth);
2482                 restore_mask(GL_SAMPLE_ALPHA_TO_COVERAGE, Gwn_VertAttr.is_sample_alpha_to_coverage);
2483                 restore_mask(GL_SCISSOR_TEST, Gwn_VertAttr.is_scissor_test);
2484                 restore_mask(GL_STENCIL_TEST, Gwn_VertAttr.is_stencil_test);
2485         }
2486
2487         if ((mask & GPU_VIEWPORT_BIT) != 0) {
2488                 glViewport(Gwn_VertAttr.viewport[0], Gwn_VertAttr.viewport[1], Gwn_VertAttr.viewport[2], Gwn_VertAttr.viewport[3]);
2489                 glDepthRange(Gwn_VertAttr.near_far[0], Gwn_VertAttr.near_far[1]);
2490         }
2491
2492         if ((mask & GPU_SCISSOR_BIT) != 0) {
2493                 restore_mask(GL_SCISSOR_TEST, Gwn_VertAttr.is_scissor_test);
2494                 glScissor(Gwn_VertAttr.scissor_box[0], Gwn_VertAttr.scissor_box[1], Gwn_VertAttr.scissor_box[2], Gwn_VertAttr.scissor_box[3]);
2495         }
2496
2497         if ((mask & GPU_BLEND_BIT) != 0) {
2498                 restore_mask(GL_BLEND, Gwn_VertAttr.is_blend);
2499         }
2500 }
2501
2502 #undef Gwn_VertAttr
2503 #undef AttribStack
2504
2505 /** \} */