ef000a4f79106ee96ee2a8d8a4056d79f8774c57
[blender.git] / source / blender / draw / intern / draw_manager.c
1 /*
2  * Copyright 2016, Blender Foundation.
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  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file blender/draw/intern/draw_manager.c
23  *  \ingroup draw
24  */
25
26 #include <stdio.h>
27
28 #include "BLI_dynstr.h"
29 #include "BLI_listbase.h"
30 #include "BLI_rect.h"
31 #include "BLI_string.h"
32
33 #include "BIF_glutil.h"
34
35 #include "BKE_global.h"
36 #include "BKE_mesh.h"
37 #include "BKE_object.h"
38 #include "BKE_pbvh.h"
39 #include "BKE_paint.h"
40
41 #include "BLT_translation.h"
42 #include "BLF_api.h"
43
44 #include "DRW_engine.h"
45 #include "DRW_render.h"
46
47 #include "DNA_camera_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_screen_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meshdata_types.h"
52
53 #include "ED_space_api.h"
54 #include "ED_screen.h"
55
56 #include "intern/gpu_codegen.h"
57 #include "GPU_batch.h"
58 #include "GPU_draw.h"
59 #include "GPU_extensions.h"
60 #include "GPU_framebuffer.h"
61 #include "GPU_immediate.h"
62 #include "GPU_lamp.h"
63 #include "GPU_material.h"
64 #include "GPU_shader.h"
65 #include "GPU_texture.h"
66 #include "GPU_uniformbuffer.h"
67 #include "GPU_viewport.h"
68 #include "GPU_matrix.h"
69
70 #include "IMB_colormanagement.h"
71
72 #include "PIL_time.h"
73
74 #include "RE_engine.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 #include "draw_manager_text.h"
83
84 /* only for callbacks */
85 #include "draw_cache_impl.h"
86
87 #include "draw_mode_engines.h"
88 #include "engines/clay/clay_engine.h"
89 #include "engines/eevee/eevee_engine.h"
90 #include "engines/basic/basic_engine.h"
91 #include "engines/external/external_engine.h"
92
93 #include "DEG_depsgraph.h"
94 #include "DEG_depsgraph_query.h"
95
96 #define MAX_ATTRIB_NAME 32
97 #define MAX_PASS_NAME 32
98 #define MAX_CLIP_PLANES 6 /* GL_MAX_CLIP_PLANES is at least 6 */
99
100 /* Use draw manager to call GPU_select, see: DRW_draw_select_loop */
101 #define USE_GPU_SELECT
102
103 #ifdef USE_GPU_SELECT
104 #  include "ED_view3d.h"
105 #  include "ED_armature.h"
106 #  include "GPU_select.h"
107 #endif
108
109 extern char datatoc_gpu_shader_2D_vert_glsl[];
110 extern char datatoc_gpu_shader_3D_vert_glsl[];
111 extern char datatoc_gpu_shader_fullscreen_vert_glsl[];
112
113 /* Prototypes. */
114 static void DRW_engines_enable_external(void);
115
116 /* Structures */
117 typedef enum {
118         DRW_UNIFORM_BOOL,
119         DRW_UNIFORM_SHORT_TO_INT,
120         DRW_UNIFORM_SHORT_TO_FLOAT,
121         DRW_UNIFORM_INT,
122         DRW_UNIFORM_FLOAT,
123         DRW_UNIFORM_TEXTURE,
124         DRW_UNIFORM_BUFFER,
125         DRW_UNIFORM_MAT3,
126         DRW_UNIFORM_MAT4,
127         DRW_UNIFORM_BLOCK
128 } DRWUniformType;
129
130 typedef enum {
131         DRW_ATTRIB_INT,
132         DRW_ATTRIB_FLOAT,
133 } DRWAttribType;
134
135 struct DRWUniform {
136         struct DRWUniform *next, *prev;
137         DRWUniformType type;
138         int location;
139         int length;
140         int arraysize;
141         int bindloc;
142         const void *value;
143 };
144
145 typedef struct DRWAttrib {
146         struct DRWAttrib *next, *prev;
147         char name[MAX_ATTRIB_NAME];
148         int location;
149         int format_id;
150         int size; /* number of component */
151         int type;
152 } DRWAttrib;
153
154 struct DRWInterface {
155         ListBase uniforms;   /* DRWUniform */
156         ListBase attribs;    /* DRWAttrib */
157         int attribs_count;
158         int attribs_stride;
159         int attribs_size[16];
160         int attribs_loc[16];
161         /* matrices locations */
162         int model;
163         int modelinverse;
164         int modelview;
165         int modelviewinverse;
166         int projection;
167         int projectioninverse;
168         int view;
169         int viewinverse;
170         int modelviewprojection;
171         int viewprojection;
172         int viewprojectioninverse;
173         int normal;
174         int worldnormal;
175         int camtexfac;
176         int orcotexfac;
177         int eye;
178         int clipplanes;
179         /* Textures */
180         int tex_bind; /* next texture binding point */
181         /* UBO */
182         int ubo_bind; /* next ubo binding point */
183         /* Dynamic batch */
184         Gwn_Batch *instance_batch; /* contains instances attributes */
185         GLuint instance_vbo; /* same as instance_batch but generated from DRWCalls */
186         int instance_count;
187         Gwn_VertFormat vbo_format;
188 };
189
190 struct DRWPass {
191         ListBase shgroups; /* DRWShadingGroup */
192         DRWState state;
193         char name[MAX_PASS_NAME];
194         /* use two query to not stall the cpu waiting for queries to complete */
195         unsigned int timer_queries[2];
196         /* alternate between front and back query */
197         unsigned int front_idx;
198         unsigned int back_idx;
199         bool wasdrawn; /* if it was drawn during this frame */
200 };
201
202 typedef struct DRWCallHeader {
203         void *next, *prev;
204 #ifdef USE_GPU_SELECT
205         int select_id;
206 #endif
207         uchar type;
208 } DRWCallHeader;
209
210 typedef struct DRWCall {
211         DRWCallHeader head;
212
213         float obmat[4][4];
214         Gwn_Batch *geometry;
215
216         Object *ob; /* Optional */
217         ID *ob_data; /* Optional. */
218 } DRWCall;
219
220 typedef struct DRWCallGenerate {
221         DRWCallHeader head;
222
223         float obmat[4][4];
224
225         DRWCallGenerateFn *geometry_fn;
226         void *user_data;
227 } DRWCallGenerate;
228
229 typedef struct DRWCallDynamic {
230         DRWCallHeader head;
231
232         const void *data[];
233 } DRWCallDynamic;
234
235 struct DRWShadingGroup {
236         struct DRWShadingGroup *next, *prev;
237
238         GPUShader *shader;               /* Shader to bind */
239         DRWInterface *interface;         /* Uniforms pointers */
240         ListBase calls;                  /* DRWCall or DRWCallDynamic depending of type */
241         DRWState state_extra;            /* State changes for this batch only (or'd with the pass's state) */
242         DRWState state_extra_disable;    /* State changes for this batch only (and'd with the pass's state) */
243         int type;
244
245         Gwn_Batch *instance_geom;  /* Geometry to instance */
246         Gwn_Batch *batch_geom;     /* Result of call batching */
247
248 #ifdef USE_GPU_SELECT
249         /* backlink to pass we're in */
250         DRWPass *pass_parent;
251 #endif
252 };
253
254 /* Used by DRWShadingGroup.type */
255 enum {
256         DRW_SHG_NORMAL,
257         DRW_SHG_POINT_BATCH,
258         DRW_SHG_LINE_BATCH,
259         DRW_SHG_TRIANGLE_BATCH,
260         DRW_SHG_INSTANCE,
261 };
262
263 /* Used by DRWCall.type */
264 enum {
265         /* A single batch */
266         DRW_CALL_SINGLE,
267         /* Uses a callback to draw with any number of batches. */
268         DRW_CALL_GENERATE,
269         /* Arbitrary number of multiple args. */
270         DRW_CALL_DYNAMIC,
271 };
272
273 /* only 16 bits long */
274 enum {
275         STENCIL_SELECT          = (1 << 0),
276         STENCIL_ACTIVE          = (1 << 1),
277 };
278
279 /* Render State */
280 static struct DRWGlobalState {
281         /* Rendering state */
282         GPUShader *shader;
283         ListBase bound_texs;
284         int tex_bind_id;
285
286         /* Managed by `DRW_state_set`, `DRW_state_reset` */
287         DRWState state;
288
289         /* Per viewport */
290         GPUViewport *viewport;
291         struct GPUFrameBuffer *default_framebuffer;
292         float size[2];
293         float screenvecs[2][3];
294         float pixsize;
295
296         GLenum backface, frontface;
297
298         /* Clip planes */
299         int num_clip_planes;
300         float clip_planes_eq[MAX_CLIP_PLANES][4];
301
302         struct {
303                 unsigned int is_select : 1;
304                 unsigned int is_depth : 1;
305                 unsigned int is_image_render : 1;
306                 unsigned int is_scene_render : 1;
307         } options;
308
309         /* Current rendering context */
310         DRWContextState draw_ctx;
311
312         /* Convenience pointer to text_store owned by the viewport */
313         struct DRWTextStore **text_store_p;
314
315         ListBase enabled_engines; /* RenderEngineType */
316 } DST = {NULL};
317
318 static struct DRWMatrixOveride {
319         float mat[6][4][4];
320         bool override[6];
321 } viewport_matrix_override = {{{{0}}}};
322
323 ListBase DRW_engines = {NULL, NULL};
324
325 #ifdef USE_GPU_SELECT
326 static unsigned int g_DRW_select_id = (unsigned int)-1;
327
328 void DRW_select_load_id(unsigned int id)
329 {
330         BLI_assert(G.f & G_PICKSEL);
331         g_DRW_select_id = id;
332 }
333 #endif
334
335
336 /* -------------------------------------------------------------------- */
337
338 /** \name Textures (DRW_texture)
339  * \{ */
340
341 static void drw_texture_get_format(DRWTextureFormat format, GPUTextureFormat *data_type, int *channels)
342 {
343         switch (format) {
344                 case DRW_TEX_RGBA_8: *data_type = GPU_RGBA8; break;
345                 case DRW_TEX_RGBA_16: *data_type = GPU_RGBA16F; break;
346                 case DRW_TEX_RGB_16: *data_type = GPU_RGB16F; break;
347                 case DRW_TEX_RGB_11_11_10: *data_type = GPU_R11F_G11F_B10F; break;
348                 case DRW_TEX_RG_16: *data_type = GPU_RG16F; break;
349                 case DRW_TEX_RG_32: *data_type = GPU_RG32F; break;
350                 case DRW_TEX_R_8: *data_type = GPU_R8; break;
351                 case DRW_TEX_R_16: *data_type = GPU_R16F; break;
352                 case DRW_TEX_R_32: *data_type = GPU_R32F; break;
353 #if 0
354                 case DRW_TEX_RGBA_32: *data_type = GPU_RGBA32F; break;
355                 case DRW_TEX_RGB_8: *data_type = GPU_RGB8; break;
356                 case DRW_TEX_RGB_32: *data_type = GPU_RGB32F; break;
357                 case DRW_TEX_RG_8: *data_type = GPU_RG8; break;
358 #endif
359                 case DRW_TEX_DEPTH_16: *data_type = GPU_DEPTH_COMPONENT16; break;
360                 case DRW_TEX_DEPTH_24: *data_type = GPU_DEPTH_COMPONENT24; break;
361                 case DRW_TEX_DEPTH_32: *data_type = GPU_DEPTH_COMPONENT32F; break;
362                 default :
363                         /* file type not supported you must uncomment it from above */
364                         BLI_assert(false);
365                         break;
366         }
367
368         switch (format) {
369                 case DRW_TEX_RGBA_8:
370                 case DRW_TEX_RGBA_16:
371                 case DRW_TEX_RGBA_32:
372                         *channels = 4;
373                         break;
374                 case DRW_TEX_RGB_8:
375                 case DRW_TEX_RGB_16:
376                 case DRW_TEX_RGB_32:
377                 case DRW_TEX_RGB_11_11_10:
378                         *channels = 3;
379                         break;
380                 case DRW_TEX_RG_8:
381                 case DRW_TEX_RG_16:
382                 case DRW_TEX_RG_32:
383                         *channels = 2;
384                         break;
385                 default:
386                         *channels = 1;
387                         break;
388         }
389 }
390
391 static void drw_texture_set_parameters(GPUTexture *tex, DRWTextureFlag flags)
392 {
393         GPU_texture_bind(tex, 0);
394         if (flags & DRW_TEX_MIPMAP) {
395                 GPU_texture_mipmap_mode(tex, true, flags & DRW_TEX_FILTER);
396                 DRW_texture_generate_mipmaps(tex);
397         }
398         else {
399                 GPU_texture_filter_mode(tex, flags & DRW_TEX_FILTER);
400         }
401         GPU_texture_wrap_mode(tex, flags & DRW_TEX_WRAP);
402         GPU_texture_compare_mode(tex, flags & DRW_TEX_COMPARE);
403         GPU_texture_unbind(tex);
404 }
405
406 GPUTexture *DRW_texture_create_1D(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
407 {
408         GPUTexture *tex;
409         GPUTextureFormat data_type;
410         int channels;
411
412         drw_texture_get_format(format, &data_type, &channels);
413         tex = GPU_texture_create_1D_custom(w, channels, data_type, fpixels, NULL);
414         drw_texture_set_parameters(tex, flags);
415
416         return tex;
417 }
418
419 GPUTexture *DRW_texture_create_2D(int w, int h, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
420 {
421         GPUTexture *tex;
422         GPUTextureFormat data_type;
423         int channels;
424
425         drw_texture_get_format(format, &data_type, &channels);
426         tex = GPU_texture_create_2D_custom(w, h, channels, data_type, fpixels, NULL);
427         drw_texture_set_parameters(tex, flags);
428
429         return tex;
430 }
431
432 GPUTexture *DRW_texture_create_2D_array(
433         int w, int h, int d, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
434 {
435         GPUTexture *tex;
436         GPUTextureFormat data_type;
437         int channels;
438
439         drw_texture_get_format(format, &data_type, &channels);
440         tex = GPU_texture_create_2D_array_custom(w, h, d, channels, data_type, fpixels, NULL);
441         drw_texture_set_parameters(tex, flags);
442
443         return tex;
444 }
445
446 GPUTexture *DRW_texture_create_cube(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
447 {
448         GPUTexture *tex;
449         GPUTextureFormat data_type;
450         int channels;
451
452         drw_texture_get_format(format, &data_type, &channels);
453         tex = GPU_texture_create_cube_custom(w, channels, data_type, fpixels, NULL);
454         drw_texture_set_parameters(tex, flags);
455
456         return tex;
457 }
458
459 void DRW_texture_generate_mipmaps(GPUTexture *tex)
460 {
461         GPU_texture_bind(tex, 0);
462         GPU_texture_generate_mipmap(tex);
463         GPU_texture_unbind(tex);
464 }
465
466 void DRW_texture_free(GPUTexture *tex)
467 {
468         GPU_texture_free(tex);
469 }
470
471 /** \} */
472
473
474 /* -------------------------------------------------------------------- */
475
476 /** \name Uniform Buffer Object (DRW_uniformbuffer)
477  * \{ */
478
479 GPUUniformBuffer *DRW_uniformbuffer_create(int size, const void *data)
480 {
481         return GPU_uniformbuffer_create(size, data, NULL);
482 }
483
484 void DRW_uniformbuffer_update(GPUUniformBuffer *ubo, const void *data)
485 {
486         GPU_uniformbuffer_update(ubo, data);
487 }
488
489 void DRW_uniformbuffer_free(GPUUniformBuffer *ubo)
490 {
491         GPU_uniformbuffer_free(ubo);
492 }
493
494 /** \} */
495
496
497 /* -------------------------------------------------------------------- */
498
499 /** \name Shaders (DRW_shader)
500  * \{ */
501
502 GPUShader *DRW_shader_create(const char *vert, const char *geom, const char *frag, const char *defines)
503 {
504         return GPU_shader_create(vert, frag, geom, NULL, defines);
505 }
506
507 GPUShader *DRW_shader_create_with_lib(
508         const char *vert, const char *geom, const char *frag, const char *lib, const char *defines)
509 {
510         GPUShader *sh;
511         char *vert_with_lib = NULL;
512         char *frag_with_lib = NULL;
513         char *geom_with_lib = NULL;
514
515         DynStr *ds_vert = BLI_dynstr_new();
516         BLI_dynstr_append(ds_vert, lib);
517         BLI_dynstr_append(ds_vert, vert);
518         vert_with_lib = BLI_dynstr_get_cstring(ds_vert);
519         BLI_dynstr_free(ds_vert);
520
521         DynStr *ds_frag = BLI_dynstr_new();
522         BLI_dynstr_append(ds_frag, lib);
523         BLI_dynstr_append(ds_frag, frag);
524         frag_with_lib = BLI_dynstr_get_cstring(ds_frag);
525         BLI_dynstr_free(ds_frag);
526
527         if (geom) {
528                 DynStr *ds_geom = BLI_dynstr_new();
529                 BLI_dynstr_append(ds_geom, lib);
530                 BLI_dynstr_append(ds_geom, geom);
531                 geom_with_lib = BLI_dynstr_get_cstring(ds_geom);
532                 BLI_dynstr_free(ds_geom);
533         }
534
535         sh = GPU_shader_create(vert_with_lib, frag_with_lib, geom_with_lib, NULL, defines);
536
537         MEM_freeN(vert_with_lib);
538         MEM_freeN(frag_with_lib);
539         if (geom) {
540                 MEM_freeN(geom_with_lib);
541         }
542
543         return sh;
544 }
545
546 GPUShader *DRW_shader_create_2D(const char *frag, const char *defines)
547 {
548         return GPU_shader_create(datatoc_gpu_shader_2D_vert_glsl, frag, NULL, NULL, defines);
549 }
550
551 GPUShader *DRW_shader_create_3D(const char *frag, const char *defines)
552 {
553         return GPU_shader_create(datatoc_gpu_shader_3D_vert_glsl, frag, NULL, NULL, defines);
554 }
555
556 GPUShader *DRW_shader_create_fullscreen(const char *frag, const char *defines)
557 {
558         return GPU_shader_create(datatoc_gpu_shader_fullscreen_vert_glsl, frag, NULL, NULL, defines);
559 }
560
561 GPUShader *DRW_shader_create_3D_depth_only(void)
562 {
563         return GPU_shader_get_builtin_shader(GPU_SHADER_3D_DEPTH_ONLY);
564 }
565
566 void DRW_shader_free(GPUShader *shader)
567 {
568         GPU_shader_free(shader);
569 }
570
571 /** \} */
572
573
574 /* -------------------------------------------------------------------- */
575
576 /** \name Interface (DRW_interface)
577  * \{ */
578
579 static DRWInterface *DRW_interface_create(GPUShader *shader)
580 {
581         DRWInterface *interface = MEM_mallocN(sizeof(DRWInterface), "DRWInterface");
582
583         interface->model = GPU_shader_get_uniform(shader, "ModelMatrix");
584         interface->modelinverse = GPU_shader_get_uniform(shader, "ModelMatrixInverse");
585         interface->modelview = GPU_shader_get_uniform(shader, "ModelViewMatrix");
586         interface->modelviewinverse = GPU_shader_get_uniform(shader, "ModelViewMatrixInverse");
587         interface->projection = GPU_shader_get_uniform(shader, "ProjectionMatrix");
588         interface->projectioninverse = GPU_shader_get_uniform(shader, "ProjectionMatrixInverse");
589         interface->view = GPU_shader_get_uniform(shader, "ViewMatrix");
590         interface->viewinverse = GPU_shader_get_uniform(shader, "ViewMatrixInverse");
591         interface->viewprojection = GPU_shader_get_uniform(shader, "ViewProjectionMatrix");
592         interface->viewprojectioninverse = GPU_shader_get_uniform(shader, "ViewProjectionMatrixInverse");
593         interface->modelviewprojection = GPU_shader_get_uniform(shader, "ModelViewProjectionMatrix");
594         interface->normal = GPU_shader_get_uniform(shader, "NormalMatrix");
595         interface->worldnormal = GPU_shader_get_uniform(shader, "WorldNormalMatrix");
596         interface->camtexfac = GPU_shader_get_uniform(shader, "CameraTexCoFactors");
597         interface->orcotexfac = GPU_shader_get_uniform(shader, "OrcoTexCoFactors[0]");
598         interface->eye = GPU_shader_get_uniform(shader, "eye");
599         interface->clipplanes = GPU_shader_get_uniform(shader, "ClipPlanes[0]");
600         interface->instance_count = 0;
601         interface->attribs_count = 0;
602         interface->attribs_stride = 0;
603         interface->instance_vbo = 0;
604         interface->instance_batch = NULL;
605         interface->tex_bind = GPU_max_textures() - 1;
606         interface->ubo_bind = GPU_max_ubo_binds() - 1;
607
608         memset(&interface->vbo_format, 0, sizeof(Gwn_VertFormat));
609
610         BLI_listbase_clear(&interface->uniforms);
611         BLI_listbase_clear(&interface->attribs);
612
613         return interface;
614 }
615
616 #ifdef USE_GPU_SELECT
617 static DRWInterface *DRW_interface_duplicate(DRWInterface *interface_src)
618 {
619         DRWInterface *interface_dst = MEM_dupallocN(interface_src);
620         BLI_duplicatelist(&interface_dst->uniforms, &interface_src->uniforms);
621         BLI_duplicatelist(&interface_dst->attribs, &interface_src->attribs);
622         return interface_dst;
623 }
624 #endif
625
626 static void DRW_interface_uniform(DRWShadingGroup *shgroup, const char *name,
627                                   DRWUniformType type, const void *value, int length, int arraysize, int bindloc)
628 {
629         DRWUniform *uni = MEM_mallocN(sizeof(DRWUniform), "DRWUniform");
630
631         if (type == DRW_UNIFORM_BLOCK) {
632                 uni->location = GPU_shader_get_uniform_block(shgroup->shader, name);
633         }
634         else {
635                 uni->location = GPU_shader_get_uniform(shgroup->shader, name);
636         }
637
638         BLI_assert(arraysize > 0);
639
640         uni->type = type;
641         uni->value = value;
642         uni->length = length;
643         uni->arraysize = arraysize;
644         uni->bindloc = bindloc; /* for textures */
645
646         if (uni->location == -1) {
647                 if (G.debug & G_DEBUG)
648                         fprintf(stderr, "Uniform '%s' not found!\n", name);
649                 /* Nice to enable eventually, for now eevee uses uniforms that might not exist. */
650                 // BLI_assert(0);
651                 MEM_freeN(uni);
652                 return;
653         }
654
655         BLI_addtail(&shgroup->interface->uniforms, uni);
656 }
657
658 static void DRW_interface_attrib(DRWShadingGroup *shgroup, const char *name, DRWAttribType type, int size, bool dummy)
659 {
660         DRWAttrib *attrib = MEM_mallocN(sizeof(DRWAttrib), "DRWAttrib");
661         GLuint program = GPU_shader_get_program(shgroup->shader);
662
663         attrib->location = glGetAttribLocation(program, name);
664         attrib->type = type;
665         attrib->size = size;
666
667 /* Adding attribute even if not found for now (to keep memory alignment).
668  * Should ideally take vertex format automatically from batch eventually */
669 #if 0
670         if (attrib->location == -1 && !dummy) {
671                 if (G.debug & G_DEBUG)
672                         fprintf(stderr, "Attribute '%s' not found!\n", name);
673                 BLI_assert(0);
674                 MEM_freeN(attrib);
675                 return;
676         }
677 #else
678         UNUSED_VARS(dummy);
679 #endif
680
681         BLI_assert(BLI_strnlen(name, 32) < 32);
682         BLI_strncpy(attrib->name, name, 32);
683
684         shgroup->interface->attribs_count += 1;
685
686         BLI_addtail(&shgroup->interface->attribs, attrib);
687 }
688
689 /** \} */
690
691
692 /* -------------------------------------------------------------------- */
693
694 /** \name Shading Group (DRW_shgroup)
695  * \{ */
696
697 DRWShadingGroup *DRW_shgroup_create(struct GPUShader *shader, DRWPass *pass)
698 {
699         DRWShadingGroup *shgroup = MEM_mallocN(sizeof(DRWShadingGroup), "DRWShadingGroup");
700
701         shgroup->type = DRW_SHG_NORMAL;
702         shgroup->shader = shader;
703         shgroup->interface = DRW_interface_create(shader);
704         shgroup->state_extra = 0;
705         shgroup->state_extra_disable = ~0x0;
706         shgroup->batch_geom = NULL;
707         shgroup->instance_geom = NULL;
708
709         BLI_addtail(&pass->shgroups, shgroup);
710         BLI_listbase_clear(&shgroup->calls);
711
712 #ifdef USE_GPU_SELECT
713         shgroup->pass_parent = pass;
714 #endif
715
716         return shgroup;
717 }
718
719 DRWShadingGroup *DRW_shgroup_material_create(struct GPUMaterial *material, DRWPass *pass)
720 {
721         double time = 0.0; /* TODO make time variable */
722
723         /* TODO : Ideally we should not convert. But since the whole codegen
724          * is relying on GPUPass we keep it as is for now. */
725         GPUPass *gpupass = GPU_material_get_pass(material);
726
727         if (!gpupass) {
728                 /* Shader compilation error */
729                 return NULL;
730         }
731
732         struct GPUShader *shader = GPU_pass_shader(gpupass);
733
734         DRWShadingGroup *grp = DRW_shgroup_create(shader, pass);
735
736         /* Converting dynamic GPUInput to DRWUniform */
737         ListBase *inputs = &gpupass->inputs;
738
739         for (GPUInput *input = inputs->first; input; input = input->next) {
740                 /* Textures */
741                 if (input->ima) {
742                         GPUTexture *tex = GPU_texture_from_blender(input->ima, input->iuser, input->textarget, input->image_isdata, time, 1);
743
744                         if (input->bindtex) {
745                                 DRW_shgroup_uniform_texture(grp, input->shadername, tex);
746                         }
747                 }
748                 /* Color Ramps */
749                 else if (input->tex) {
750                         DRW_shgroup_uniform_texture(grp, input->shadername, input->tex);
751                 }
752                 /* Floats */
753                 else {
754                         switch (input->type) {
755                                 case GPU_FLOAT:
756                                         DRW_shgroup_uniform_float(grp, input->shadername, (float *)input->dynamicvec, 1);
757                                         break;
758                                 case GPU_VEC2:
759                                         DRW_shgroup_uniform_vec2(grp, input->shadername, (float *)input->dynamicvec, 1);
760                                         break;
761                                 case GPU_VEC3:
762                                         DRW_shgroup_uniform_vec3(grp, input->shadername, (float *)input->dynamicvec, 1);
763                                         break;
764                                 case GPU_VEC4:
765                                         DRW_shgroup_uniform_vec4(grp, input->shadername, (float *)input->dynamicvec, 1);
766                                         break;
767                                 case GPU_MAT3:
768                                         DRW_shgroup_uniform_mat3(grp, input->shadername, (float *)input->dynamicvec);
769                                         break;
770                                 case GPU_MAT4:
771                                         DRW_shgroup_uniform_mat4(grp, input->shadername, (float *)input->dynamicvec);
772                                         break;
773                                 default:
774                                         break;
775                         }
776                 }
777         }
778
779         return grp;
780 }
781
782 DRWShadingGroup *DRW_shgroup_material_instance_create(struct GPUMaterial *material, DRWPass *pass, Gwn_Batch *geom)
783 {
784         DRWShadingGroup *shgroup = DRW_shgroup_material_create(material, pass);
785
786         if (shgroup) {
787                 shgroup->type = DRW_SHG_INSTANCE;
788                 shgroup->instance_geom = geom;
789         }
790
791         return shgroup;
792 }
793
794 DRWShadingGroup *DRW_shgroup_instance_create(struct GPUShader *shader, DRWPass *pass, Gwn_Batch *geom)
795 {
796         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
797
798         shgroup->type = DRW_SHG_INSTANCE;
799         shgroup->instance_geom = geom;
800
801         return shgroup;
802 }
803
804 DRWShadingGroup *DRW_shgroup_point_batch_create(struct GPUShader *shader, DRWPass *pass)
805 {
806         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
807
808         shgroup->type = DRW_SHG_POINT_BATCH;
809         DRW_shgroup_attrib_float(shgroup, "pos", 3);
810
811         return shgroup;
812 }
813
814 DRWShadingGroup *DRW_shgroup_line_batch_create(struct GPUShader *shader, DRWPass *pass)
815 {
816         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
817
818         shgroup->type = DRW_SHG_LINE_BATCH;
819         DRW_shgroup_attrib_float(shgroup, "pos", 3);
820
821         return shgroup;
822 }
823
824 /* Very special batch. Use this if you position
825  * your vertices with the vertex shader
826  * and dont need any VBO attrib */
827 DRWShadingGroup *DRW_shgroup_empty_tri_batch_create(struct GPUShader *shader, DRWPass *pass, int size)
828 {
829         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
830
831         shgroup->type = DRW_SHG_TRIANGLE_BATCH;
832         shgroup->interface->instance_count = size * 3;
833         DRW_interface_attrib(shgroup, "dummy", DRW_ATTRIB_FLOAT, 1, true);
834
835         return shgroup;
836 }
837
838 void DRW_shgroup_free(struct DRWShadingGroup *shgroup)
839 {
840         BLI_freelistN(&shgroup->calls);
841         BLI_freelistN(&shgroup->interface->uniforms);
842         BLI_freelistN(&shgroup->interface->attribs);
843
844         if (shgroup->interface->instance_vbo &&
845                 (shgroup->interface->instance_batch == 0))
846         {
847                 glDeleteBuffers(1, &shgroup->interface->instance_vbo);
848         }
849
850         MEM_freeN(shgroup->interface);
851
852         BATCH_DISCARD_ALL_SAFE(shgroup->batch_geom);
853 }
854
855 void DRW_shgroup_instance_batch(DRWShadingGroup *shgroup, struct Gwn_Batch *instances)
856 {
857         BLI_assert(shgroup->type == DRW_SHG_INSTANCE);
858         BLI_assert(shgroup->interface->instance_batch == NULL);
859
860         shgroup->interface->instance_batch = instances;
861 }
862
863 void DRW_shgroup_call_add(DRWShadingGroup *shgroup, Gwn_Batch *geom, float (*obmat)[4])
864 {
865         BLI_assert(geom != NULL);
866
867         DRWCall *call = MEM_callocN(sizeof(DRWCall), "DRWCall");
868
869         call->head.type = DRW_CALL_SINGLE;
870 #ifdef USE_GPU_SELECT
871         call->head.select_id = g_DRW_select_id;
872 #endif
873
874         if (obmat != NULL) {
875                 copy_m4_m4(call->obmat, obmat);
876         }
877
878         call->geometry = geom;
879
880         BLI_addtail(&shgroup->calls, call);
881 }
882
883 void DRW_shgroup_call_object_add(DRWShadingGroup *shgroup, Gwn_Batch *geom, Object *ob)
884 {
885         BLI_assert(geom != NULL);
886
887         DRWCall *call = MEM_callocN(sizeof(DRWCall), "DRWCall");
888
889         call->head.type = DRW_CALL_SINGLE;
890 #ifdef USE_GPU_SELECT
891         call->head.select_id = g_DRW_select_id;
892 #endif
893
894         copy_m4_m4(call->obmat, ob->obmat);
895         call->geometry = geom;
896         call->ob_data = ob->data;
897
898         BLI_addtail(&shgroup->calls, call);
899 }
900
901 void DRW_shgroup_call_generate_add(
902         DRWShadingGroup *shgroup,
903         DRWCallGenerateFn *geometry_fn, void *user_data,
904         float (*obmat)[4])
905 {
906         BLI_assert(geometry_fn != NULL);
907
908         DRWCallGenerate *call = MEM_callocN(sizeof(DRWCallGenerate), "DRWCallGenerate");
909
910         call->head.type = DRW_CALL_GENERATE;
911 #ifdef USE_GPU_SELECT
912         call->head.select_id = g_DRW_select_id;
913 #endif
914
915         if (obmat != NULL) {
916                 copy_m4_m4(call->obmat, obmat);
917         }
918
919         call->geometry_fn = geometry_fn;
920         call->user_data = user_data;
921
922         BLI_addtail(&shgroup->calls, call);
923 }
924
925 static void sculpt_draw_cb(
926         DRWShadingGroup *shgroup,
927         void (*draw_fn)(DRWShadingGroup *shgroup, Gwn_Batch *geom),
928         void *user_data)
929 {
930         Object *ob = user_data;
931         PBVH *pbvh = ob->sculpt->pbvh;
932
933         if (pbvh) {
934                 BKE_pbvh_draw_cb(
935                         pbvh, NULL, NULL, false,
936                         (void (*)(void *, Gwn_Batch *))draw_fn, shgroup);
937         }
938 }
939
940 void DRW_shgroup_call_sculpt_add(DRWShadingGroup *shgroup, Object *ob, float (*obmat)[4])
941 {
942         DRW_shgroup_call_generate_add(shgroup, sculpt_draw_cb, ob, obmat);
943 }
944
945 void DRW_shgroup_call_dynamic_add_array(DRWShadingGroup *shgroup, const void *attr[], unsigned int attr_len)
946 {
947         DRWInterface *interface = shgroup->interface;
948
949 #ifdef USE_GPU_SELECT
950         if ((G.f & G_PICKSEL) && (interface->instance_count > 0)) {
951                 shgroup = MEM_dupallocN(shgroup);
952                 BLI_listbase_clear(&shgroup->calls);
953
954                 shgroup->interface = interface = DRW_interface_duplicate(interface);
955                 interface->instance_count = 0;
956
957                 BLI_addtail(&shgroup->pass_parent->shgroups, shgroup);
958         }
959 #endif
960
961         unsigned int data_size = sizeof(void *) * interface->attribs_count;
962         int size = sizeof(DRWCallDynamic) + data_size;
963
964         DRWCallDynamic *call = MEM_callocN(size, "DRWCallDynamic");
965
966         BLI_assert(attr_len == interface->attribs_count);
967         UNUSED_VARS_NDEBUG(attr_len);
968
969         call->head.type = DRW_CALL_DYNAMIC;
970 #ifdef USE_GPU_SELECT
971         call->head.select_id = g_DRW_select_id;
972 #endif
973
974         if (data_size != 0) {
975                 memcpy((void *)call->data, attr, data_size);
976         }
977
978         interface->instance_count += 1;
979
980         BLI_addtail(&shgroup->calls, call);
981 }
982
983 /* Used for instancing with no attributes */
984 void DRW_shgroup_set_instance_count(DRWShadingGroup *shgroup, int count)
985 {
986         DRWInterface *interface = shgroup->interface;
987
988         BLI_assert(interface->attribs_count == 0);
989
990         interface->instance_count = count;
991 }
992
993 /**
994  * State is added to #Pass.state while drawing.
995  * Use to temporarily enable draw options.
996  */
997 void DRW_shgroup_state_enable(DRWShadingGroup *shgroup, DRWState state)
998 {
999         shgroup->state_extra |= state;
1000 }
1001
1002 void DRW_shgroup_state_disable(DRWShadingGroup *shgroup, DRWState state)
1003 {
1004         shgroup->state_extra_disable &= ~state;
1005 }
1006
1007 void DRW_shgroup_attrib_float(DRWShadingGroup *shgroup, const char *name, int size)
1008 {
1009         DRW_interface_attrib(shgroup, name, DRW_ATTRIB_FLOAT, size, false);
1010 }
1011
1012 void DRW_shgroup_uniform_texture(DRWShadingGroup *shgroup, const char *name, const GPUTexture *tex)
1013 {
1014         DRWInterface *interface = shgroup->interface;
1015
1016         if (interface->tex_bind < 0) {
1017                 /* TODO alert user */
1018                 printf("Not enough texture slot for %s\n", name);
1019                 return;
1020         }
1021
1022         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_TEXTURE, tex, 0, 1, interface->tex_bind--);
1023 }
1024
1025 void DRW_shgroup_uniform_block(DRWShadingGroup *shgroup, const char *name, const GPUUniformBuffer *ubo)
1026 {
1027         DRWInterface *interface = shgroup->interface;
1028
1029         /* Be carefull: there is also a limit per shader stage. Usually 1/3 of normal limit. */
1030         if (interface->ubo_bind < 0) {
1031                 /* TODO alert user */
1032                 printf("Not enough ubo slots for %s\n", name);
1033                 return;
1034         }
1035
1036         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BLOCK, ubo, 0, 1, interface->ubo_bind--);
1037 }
1038
1039 void DRW_shgroup_uniform_buffer(DRWShadingGroup *shgroup, const char *name, GPUTexture **tex)
1040 {
1041         DRWInterface *interface = shgroup->interface;
1042
1043         if (interface->tex_bind < 0) {
1044                 /* TODO alert user */
1045                 printf("Not enough texture slot for %s\n", name);
1046                 return;
1047         }
1048
1049         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BUFFER, tex, 0, 1, interface->tex_bind--);
1050 }
1051
1052 void DRW_shgroup_uniform_bool(DRWShadingGroup *shgroup, const char *name, const bool *value, int arraysize)
1053 {
1054         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BOOL, value, 1, arraysize, 0);
1055 }
1056
1057 void DRW_shgroup_uniform_float(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1058 {
1059         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 1, arraysize, 0);
1060 }
1061
1062 void DRW_shgroup_uniform_vec2(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1063 {
1064         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 2, arraysize, 0);
1065 }
1066
1067 void DRW_shgroup_uniform_vec3(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1068 {
1069         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 3, arraysize, 0);
1070 }
1071
1072 void DRW_shgroup_uniform_vec4(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1073 {
1074         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 4, arraysize, 0);
1075 }
1076
1077 void DRW_shgroup_uniform_short_to_int(DRWShadingGroup *shgroup, const char *name, const short *value, int arraysize)
1078 {
1079         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_SHORT_TO_INT, value, 1, arraysize, 0);
1080 }
1081
1082 void DRW_shgroup_uniform_short_to_float(DRWShadingGroup *shgroup, const char *name, const short *value, int arraysize)
1083 {
1084         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_SHORT_TO_FLOAT, value, 1, arraysize, 0);
1085 }
1086
1087 void DRW_shgroup_uniform_int(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1088 {
1089         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 1, arraysize, 0);
1090 }
1091
1092 void DRW_shgroup_uniform_ivec2(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1093 {
1094         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 2, arraysize, 0);
1095 }
1096
1097 void DRW_shgroup_uniform_ivec3(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1098 {
1099         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 3, arraysize, 0);
1100 }
1101
1102 void DRW_shgroup_uniform_mat3(DRWShadingGroup *shgroup, const char *name, const float *value)
1103 {
1104         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT3, value, 9, 1, 0);
1105 }
1106
1107 void DRW_shgroup_uniform_mat4(DRWShadingGroup *shgroup, const char *name, const float *value)
1108 {
1109         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT4, value, 16, 1, 0);
1110 }
1111
1112 /* Creates a VBO containing OGL primitives for all DRWCallDynamic */
1113 static void shgroup_dynamic_batch(DRWShadingGroup *shgroup)
1114 {
1115         DRWInterface *interface = shgroup->interface;
1116         int nbr = interface->instance_count;
1117
1118         Gwn_PrimType type = (shgroup->type == DRW_SHG_POINT_BATCH) ? GWN_PRIM_POINTS :
1119                              (shgroup->type == DRW_SHG_TRIANGLE_BATCH) ? GWN_PRIM_TRIS : GWN_PRIM_LINES;
1120
1121         if (nbr == 0)
1122                 return;
1123
1124         /* Upload Data */
1125         if (interface->vbo_format.attrib_ct == 0) {
1126                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next) {
1127                         BLI_assert(attrib->size <= 4); /* matrices have no place here for now */
1128                         if (attrib->type == DRW_ATTRIB_FLOAT) {
1129                                 attrib->format_id = GWN_vertformat_attr_add(
1130                                         &interface->vbo_format, attrib->name, GWN_COMP_F32, attrib->size, GWN_FETCH_FLOAT);
1131                         }
1132                         else if (attrib->type == DRW_ATTRIB_INT) {
1133                                 attrib->format_id = GWN_vertformat_attr_add(
1134                                         &interface->vbo_format, attrib->name, GWN_COMP_I8, attrib->size, GWN_FETCH_INT);
1135                         }
1136                         else {
1137                                 BLI_assert(false);
1138                         }
1139                 }
1140         }
1141
1142         Gwn_VertBuf *vbo = GWN_vertbuf_create_with_format(&interface->vbo_format);
1143         GWN_vertbuf_data_alloc(vbo, nbr);
1144
1145         int j = 0;
1146         for (DRWCallDynamic *call = shgroup->calls.first; call; call = call->head.next, j++) {
1147                 int i = 0;
1148                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
1149                         GWN_vertbuf_attr_set(vbo, attrib->format_id, j, call->data[i]);
1150                 }
1151         }
1152
1153         /* TODO make the batch dynamic instead of freeing it every times */
1154         if (shgroup->batch_geom)
1155                 GWN_batch_discard_all(shgroup->batch_geom);
1156
1157         shgroup->batch_geom = GWN_batch_create(type, vbo, NULL);
1158 }
1159
1160 static void shgroup_dynamic_instance(DRWShadingGroup *shgroup)
1161 {
1162         int i = 0;
1163         int offset = 0;
1164         DRWInterface *interface = shgroup->interface;
1165         int buffer_size = 0;
1166
1167         if (interface->instance_batch != NULL) {
1168                 return;
1169         }
1170
1171         /* TODO We still need this because gawain does not support Matrix attribs. */
1172         if (interface->instance_count == 0) {
1173                 if (interface->instance_vbo) {
1174                         glDeleteBuffers(1, &interface->instance_vbo);
1175                         interface->instance_vbo = 0;
1176                 }
1177                 return;
1178         }
1179
1180         /* only once */
1181         if (interface->attribs_stride == 0) {
1182                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
1183                         BLI_assert(attrib->type == DRW_ATTRIB_FLOAT); /* Only float for now */
1184                         interface->attribs_stride += attrib->size;
1185                         interface->attribs_size[i] = attrib->size;
1186                         interface->attribs_loc[i] = attrib->location;
1187                 }
1188         }
1189
1190         /* Gather Data */
1191         buffer_size = sizeof(float) * interface->attribs_stride * interface->instance_count;
1192         float *data = MEM_mallocN(buffer_size, "Instance VBO data");
1193
1194         for (DRWCallDynamic *call = shgroup->calls.first; call; call = call->head.next) {
1195                 for (int j = 0; j < interface->attribs_count; ++j) {
1196                         memcpy(data + offset, call->data[j], sizeof(float) * interface->attribs_size[j]);
1197                         offset += interface->attribs_size[j];
1198                 }
1199         }
1200
1201         /* TODO poke mike to add this to gawain */
1202         if (interface->instance_vbo) {
1203                 glDeleteBuffers(1, &interface->instance_vbo);
1204                 interface->instance_vbo = 0;
1205         }
1206
1207         glGenBuffers(1, &interface->instance_vbo);
1208         glBindBuffer(GL_ARRAY_BUFFER, interface->instance_vbo);
1209         glBufferData(GL_ARRAY_BUFFER, buffer_size, data, GL_STATIC_DRAW);
1210
1211         MEM_freeN(data);
1212 }
1213
1214 static void shgroup_dynamic_batch_from_calls(DRWShadingGroup *shgroup)
1215 {
1216         if ((shgroup->interface->instance_vbo || shgroup->batch_geom) &&
1217             (G.debug_value == 667))
1218         {
1219                 return;
1220         }
1221
1222         if (shgroup->type == DRW_SHG_INSTANCE) {
1223                 shgroup_dynamic_instance(shgroup);
1224         }
1225         else {
1226                 shgroup_dynamic_batch(shgroup);
1227         }
1228 }
1229
1230 /** \} */
1231
1232
1233 /* -------------------------------------------------------------------- */
1234
1235 /** \name Passes (DRW_pass)
1236  * \{ */
1237
1238 DRWPass *DRW_pass_create(const char *name, DRWState state)
1239 {
1240         DRWPass *pass = MEM_callocN(sizeof(DRWPass), name);
1241         pass->state = state;
1242         BLI_strncpy(pass->name, name, MAX_PASS_NAME);
1243
1244         BLI_listbase_clear(&pass->shgroups);
1245
1246         return pass;
1247 }
1248
1249 void DRW_pass_free(DRWPass *pass)
1250 {
1251         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
1252                 DRW_shgroup_free(shgroup);
1253         }
1254
1255         glDeleteQueries(2, pass->timer_queries);
1256         BLI_freelistN(&pass->shgroups);
1257 }
1258
1259 void DRW_pass_foreach_shgroup(DRWPass *pass, void (*callback)(void *userData, DRWShadingGroup *shgrp), void *userData)
1260 {
1261         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
1262                 callback(userData, shgroup);
1263         }
1264 }
1265
1266 typedef struct ZSortData {
1267         float *axis;
1268         float *origin;
1269 } ZSortData;
1270
1271 static int pass_shgroup_dist_sort(void *thunk, const void *a, const void *b)
1272 {
1273         const DRWCall *call_a = (DRWCall *)((const DRWShadingGroup *)a)->calls.first;
1274         const DRWCall *call_b = (DRWCall *)((const DRWShadingGroup *)b)->calls.first;
1275         const ZSortData *zsortdata = (ZSortData *)thunk;
1276
1277         float tmp[3];
1278         sub_v3_v3v3(tmp, zsortdata->origin, call_a->obmat[3]);
1279         const float a_sq = dot_v3v3(zsortdata->axis, tmp);
1280         sub_v3_v3v3(tmp, zsortdata->origin, call_b->obmat[3]);
1281         const float b_sq = dot_v3v3(zsortdata->axis, tmp);
1282
1283         if      (a_sq < b_sq) return  1;
1284         else if (a_sq > b_sq) return -1;
1285         else                  return  0;
1286 }
1287
1288 /**
1289  * Sort Shading groups by decreasing Z between
1290  * the first call object center and a given world space point.
1291  **/
1292 void DRW_pass_sort_shgroup_z(DRWPass *pass)
1293 {
1294         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1295
1296         float (*viewinv)[4];
1297         viewinv = (viewport_matrix_override.override[DRW_MAT_VIEWINV])
1298                   ? viewport_matrix_override.mat[DRW_MAT_VIEWINV] : rv3d->viewinv;
1299
1300         ZSortData zsortdata = {viewinv[2], viewinv[3]};
1301         BLI_listbase_sort_r(&pass->shgroups, pass_shgroup_dist_sort, &zsortdata);
1302 }
1303
1304 /** \} */
1305
1306
1307 /* -------------------------------------------------------------------- */
1308
1309 /** \name Draw (DRW_draw)
1310  * \{ */
1311
1312 static void DRW_state_set(DRWState state)
1313 {
1314         if (DST.state == state) {
1315                 return;
1316         }
1317
1318
1319 #define CHANGED_TO(f) \
1320         ((DST.state & (f)) ? \
1321                 ((state & (f)) ?  0 : -1) : \
1322                 ((state & (f)) ?  1 :  0))
1323
1324 #define CHANGED_ANY(f) \
1325         ((DST.state & (f)) != (state & (f)))
1326
1327 #define CHANGED_ANY_STORE_VAR(f, enabled) \
1328         ((DST.state & (f)) != (enabled = (state & (f))))
1329
1330         /* Depth Write */
1331         {
1332                 int test;
1333                 if ((test = CHANGED_TO(DRW_STATE_WRITE_DEPTH))) {
1334                         if (test == 1) {
1335                                 glDepthMask(GL_TRUE);
1336                         }
1337                         else {
1338                                 glDepthMask(GL_FALSE);
1339                         }
1340                 }
1341         }
1342
1343         /* Color Write */
1344         {
1345                 int test;
1346                 if ((test = CHANGED_TO(DRW_STATE_WRITE_COLOR))) {
1347                         if (test == 1) {
1348                                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1349                         }
1350                         else {
1351                                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1352                         }
1353                 }
1354         }
1355
1356         /* Cull */
1357         {
1358                 DRWState test;
1359                 if (CHANGED_ANY_STORE_VAR(
1360                         DRW_STATE_CULL_BACK | DRW_STATE_CULL_FRONT,
1361                         test))
1362                 {
1363                         if (test) {
1364                                 glEnable(GL_CULL_FACE);
1365
1366                                 if ((state & DRW_STATE_CULL_BACK) != 0) {
1367                                         glCullFace(GL_BACK);
1368                                 }
1369                                 else if ((state & DRW_STATE_CULL_FRONT) != 0) {
1370                                         glCullFace(GL_FRONT);
1371                                 }
1372                                 else {
1373                                         BLI_assert(0);
1374                                 }
1375                         }
1376                         else {
1377                                 glDisable(GL_CULL_FACE);
1378                         }
1379                 }
1380         }
1381
1382         /* Depth Test */
1383         {
1384                 DRWState test;
1385                 if (CHANGED_ANY_STORE_VAR(
1386                         DRW_STATE_DEPTH_LESS | DRW_STATE_DEPTH_EQUAL | DRW_STATE_DEPTH_GREATER | DRW_STATE_DEPTH_ALWAYS,
1387                         test))
1388                 {
1389                         if (test) {
1390                                 glEnable(GL_DEPTH_TEST);
1391
1392                                 if (state & DRW_STATE_DEPTH_LESS) {
1393                                         glDepthFunc(GL_LEQUAL);
1394                                 }
1395                                 else if (state & DRW_STATE_DEPTH_EQUAL) {
1396                                         glDepthFunc(GL_EQUAL);
1397                                 }
1398                                 else if (state & DRW_STATE_DEPTH_GREATER) {
1399                                         glDepthFunc(GL_GREATER);
1400                                 }
1401                                 else if (state & DRW_STATE_DEPTH_ALWAYS) {
1402                                         glDepthFunc(GL_ALWAYS);
1403                                 }
1404                                 else {
1405                                         BLI_assert(0);
1406                                 }
1407                         }
1408                         else {
1409                                 glDisable(GL_DEPTH_TEST);
1410                         }
1411                 }
1412         }
1413
1414         /* Wire Width */
1415         {
1416                 if (CHANGED_ANY(DRW_STATE_WIRE | DRW_STATE_WIRE_LARGE)) {
1417                         if ((state & DRW_STATE_WIRE) != 0) {
1418                                 glLineWidth(1.0f);
1419                         }
1420                         else if ((state & DRW_STATE_WIRE_LARGE) != 0) {
1421                                 glLineWidth(UI_GetThemeValuef(TH_OUTLINE_WIDTH) * 2.0f);
1422                         }
1423                         else {
1424                                 /* do nothing */
1425                         }
1426                 }
1427         }
1428
1429         /* Points Size */
1430         {
1431                 int test;
1432                 if ((test = CHANGED_TO(DRW_STATE_POINT))) {
1433                         if (test == 1) {
1434                                 GPU_enable_program_point_size();
1435                                 glPointSize(5.0f);
1436                         }
1437                         else {
1438                                 GPU_disable_program_point_size();
1439                         }
1440                 }
1441         }
1442
1443         /* Blending (all buffer) */
1444         {
1445                 int test;
1446                 if (CHANGED_ANY_STORE_VAR(
1447                         DRW_STATE_BLEND | DRW_STATE_ADDITIVE | DRW_STATE_MULTIPLY | DRW_STATE_TRANSMISSION,
1448                         test))
1449                 {
1450                         if (test) {
1451                                 glEnable(GL_BLEND);
1452
1453                                 if ((state & DRW_STATE_BLEND) != 0) {
1454                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1455                                 }
1456                                 else if ((state & DRW_STATE_MULTIPLY) != 0) {
1457                                         glBlendFunc(GL_DST_COLOR, GL_ZERO);
1458                                 }
1459                                 else if ((state & DRW_STATE_TRANSMISSION) != 0) {
1460                                         glBlendFunc(GL_ONE, GL_SRC_ALPHA);
1461                                 }
1462                                 else if ((state & DRW_STATE_ADDITIVE) != 0) {
1463                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1464                                 }
1465                                 else {
1466                                         BLI_assert(0);
1467                                 }
1468                         }
1469                         else {
1470                                 glDisable(GL_BLEND);
1471                         }
1472                 }
1473         }
1474
1475         /* Clip Planes */
1476         {
1477                 int test;
1478                 if ((test = CHANGED_TO(DRW_STATE_CLIP_PLANES))) {
1479                         if (test == 1) {
1480                                 for (int i = 0; i < DST.num_clip_planes; ++i) {
1481                                         glEnable(GL_CLIP_DISTANCE0 + i);
1482                                 }
1483                         }
1484                         else {
1485                                 for (int i = 0; i < MAX_CLIP_PLANES; ++i) {
1486                                         glDisable(GL_CLIP_DISTANCE0 + i);
1487                                 }
1488                         }
1489                 }
1490         }
1491
1492         /* Line Stipple */
1493         {
1494                 int test;
1495                 if (CHANGED_ANY_STORE_VAR(
1496                         DRW_STATE_STIPPLE_2 | DRW_STATE_STIPPLE_3 | DRW_STATE_STIPPLE_4,
1497                         test))
1498                 {
1499                         if (test) {
1500                                 if ((state & DRW_STATE_STIPPLE_2) != 0) {
1501                                         setlinestyle(2);
1502                                 }
1503                                 else if ((state & DRW_STATE_STIPPLE_3) != 0) {
1504                                         setlinestyle(3);
1505                                 }
1506                                 else if ((state & DRW_STATE_STIPPLE_4) != 0) {
1507                                         setlinestyle(4);
1508                                 }
1509                                 else {
1510                                         BLI_assert(0);
1511                                 }
1512                         }
1513                         else {
1514                                 setlinestyle(0);
1515                         }
1516                 }
1517         }
1518
1519         /* Stencil */
1520         {
1521                 DRWState test;
1522                 if (CHANGED_ANY_STORE_VAR(
1523                         DRW_STATE_WRITE_STENCIL_SELECT |
1524                         DRW_STATE_WRITE_STENCIL_ACTIVE |
1525                         DRW_STATE_TEST_STENCIL_SELECT |
1526                         DRW_STATE_TEST_STENCIL_ACTIVE,
1527                         test))
1528                 {
1529                         if (test) {
1530                                 glEnable(GL_STENCIL_TEST);
1531
1532                                 /* Stencil Write */
1533                                 if ((state & DRW_STATE_WRITE_STENCIL_SELECT) != 0) {
1534                                         glStencilMask(STENCIL_SELECT);
1535                                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1536                                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_SELECT);
1537                                 }
1538                                 else if ((state & DRW_STATE_WRITE_STENCIL_ACTIVE) != 0) {
1539                                         glStencilMask(STENCIL_ACTIVE);
1540                                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1541                                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_ACTIVE);
1542                                 }
1543                                 /* Stencil Test */
1544                                 else if ((state & DRW_STATE_TEST_STENCIL_SELECT) != 0) {
1545                                         glStencilMask(0x00); /* disable write */
1546                                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_SELECT);
1547                                 }
1548                                 else if ((state & DRW_STATE_TEST_STENCIL_ACTIVE) != 0) {
1549                                         glStencilMask(0x00); /* disable write */
1550                                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_ACTIVE);
1551                                 }
1552                                 else {
1553                                         BLI_assert(0);
1554                                 }
1555                         }
1556                         else {
1557                                 /* disable write & test */
1558                                 glStencilMask(0x00);
1559                                 glStencilFunc(GL_ALWAYS, 1, 0xFF);
1560                                 glDisable(GL_STENCIL_TEST);
1561                         }
1562                 }
1563         }
1564
1565 #undef CHANGED_TO
1566 #undef CHANGED_ANY
1567 #undef CHANGED_ANY_STORE_VAR
1568
1569         DST.state = state;
1570 }
1571
1572 typedef struct DRWBoundTexture {
1573         struct DRWBoundTexture *next, *prev;
1574         GPUTexture *tex;
1575 } DRWBoundTexture;
1576
1577 static void draw_geometry_prepare(
1578         DRWShadingGroup *shgroup, const float (*obmat)[4], const float *texcoloc, const float *texcosize)
1579 {
1580         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1581         DRWInterface *interface = shgroup->interface;
1582
1583         float mvp[4][4], mv[4][4], mi[4][4], mvi[4][4], pi[4][4], n[3][3], wn[3][3];
1584         float orcofacs[2][3] = {{0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f}};
1585         float eye[3] = { 0.0f, 0.0f, 1.0f }; /* looking into the screen */
1586
1587         bool do_pi = (interface->projectioninverse != -1);
1588         bool do_mvp = (interface->modelviewprojection != -1);
1589         bool do_mi = (interface->modelinverse != -1);
1590         bool do_mv = (interface->modelview != -1);
1591         bool do_mvi = (interface->modelviewinverse != -1);
1592         bool do_n = (interface->normal != -1);
1593         bool do_wn = (interface->worldnormal != -1);
1594         bool do_eye = (interface->eye != -1);
1595         bool do_orco = (interface->orcotexfac != -1) && (texcoloc != NULL) && (texcosize != NULL);
1596
1597         /* Matrix override */
1598         float (*persmat)[4];
1599         float (*persinv)[4];
1600         float (*viewmat)[4];
1601         float (*viewinv)[4];
1602         float (*winmat)[4];
1603         float (*wininv)[4];
1604
1605         persmat = (viewport_matrix_override.override[DRW_MAT_PERS])
1606                   ? viewport_matrix_override.mat[DRW_MAT_PERS] : rv3d->persmat;
1607         persinv = (viewport_matrix_override.override[DRW_MAT_PERSINV])
1608                   ? viewport_matrix_override.mat[DRW_MAT_PERSINV] : rv3d->persinv;
1609         viewmat = (viewport_matrix_override.override[DRW_MAT_VIEW])
1610                   ? viewport_matrix_override.mat[DRW_MAT_VIEW] : rv3d->viewmat;
1611         viewinv = (viewport_matrix_override.override[DRW_MAT_VIEWINV])
1612                   ? viewport_matrix_override.mat[DRW_MAT_VIEWINV] : rv3d->viewinv;
1613         winmat = (viewport_matrix_override.override[DRW_MAT_WIN])
1614                   ? viewport_matrix_override.mat[DRW_MAT_WIN] : rv3d->winmat;
1615
1616         if (do_pi) {
1617                 if (viewport_matrix_override.override[DRW_MAT_WININV]) {
1618                         wininv = viewport_matrix_override.mat[DRW_MAT_WININV];
1619                 }
1620                 else {
1621                         invert_m4_m4(pi, winmat);
1622                         wininv = pi;
1623                 }
1624         }
1625         if (do_mi) {
1626                 invert_m4_m4(mi, obmat);
1627         }
1628         if (do_mvp) {
1629                 mul_m4_m4m4(mvp, persmat, obmat);
1630         }
1631         if (do_mv || do_mvi || do_n || do_eye) {
1632                 mul_m4_m4m4(mv, viewmat, obmat);
1633         }
1634         if (do_mvi) {
1635                 invert_m4_m4(mvi, mv);
1636         }
1637         if (do_n || do_eye) {
1638                 copy_m3_m4(n, mv);
1639                 invert_m3(n);
1640                 transpose_m3(n);
1641         }
1642         if (do_wn) {
1643                 copy_m3_m4(wn, obmat);
1644                 invert_m3(wn);
1645                 transpose_m3(wn);
1646         }
1647         if (do_eye) {
1648                 /* Used by orthographic wires */
1649                 float tmp[3][3];
1650                 invert_m3_m3(tmp, n);
1651                 /* set eye vector, transformed to object coords */
1652                 mul_m3_v3(tmp, eye);
1653         }
1654         if (do_orco) {
1655                 mul_v3_v3fl(orcofacs[1], texcosize, 2.0f);
1656                 invert_v3(orcofacs[1]);
1657                 sub_v3_v3v3(orcofacs[0], texcoloc, texcosize);
1658                 negate_v3(orcofacs[0]);
1659                 mul_v3_v3(orcofacs[0], orcofacs[1]); /* result in a nice MADD in the shader */
1660         }
1661
1662         /* Should be really simple */
1663         /* step 1 : bind object dependent matrices */
1664         /* TODO : Some of these are not object dependant.
1665          * They should be grouped inside a UBO updated once per redraw.
1666          * The rest can also go into a UBO to reduce API calls. */
1667         GPU_shader_uniform_vector(shgroup->shader, interface->model, 16, 1, (float *)obmat);
1668         GPU_shader_uniform_vector(shgroup->shader, interface->modelinverse, 16, 1, (float *)mi);
1669         GPU_shader_uniform_vector(shgroup->shader, interface->modelviewprojection, 16, 1, (float *)mvp);
1670         GPU_shader_uniform_vector(shgroup->shader, interface->viewinverse, 16, 1, (float *)viewinv);
1671         GPU_shader_uniform_vector(shgroup->shader, interface->viewprojection, 16, 1, (float *)persmat);
1672         GPU_shader_uniform_vector(shgroup->shader, interface->viewprojectioninverse, 16, 1, (float *)persinv);
1673         GPU_shader_uniform_vector(shgroup->shader, interface->projection, 16, 1, (float *)winmat);
1674         GPU_shader_uniform_vector(shgroup->shader, interface->projectioninverse, 16, 1, (float *)wininv);
1675         GPU_shader_uniform_vector(shgroup->shader, interface->view, 16, 1, (float *)viewmat);
1676         GPU_shader_uniform_vector(shgroup->shader, interface->modelview, 16, 1, (float *)mv);
1677         GPU_shader_uniform_vector(shgroup->shader, interface->modelviewinverse, 16, 1, (float *)mvi);
1678         GPU_shader_uniform_vector(shgroup->shader, interface->normal, 9, 1, (float *)n);
1679         GPU_shader_uniform_vector(shgroup->shader, interface->worldnormal, 9, 1, (float *)wn);
1680         GPU_shader_uniform_vector(shgroup->shader, interface->camtexfac, 4, 1, (float *)rv3d->viewcamtexcofac);
1681         GPU_shader_uniform_vector(shgroup->shader, interface->orcotexfac, 3, 2, (float *)orcofacs);
1682         GPU_shader_uniform_vector(shgroup->shader, interface->eye, 3, 1, (float *)eye);
1683         GPU_shader_uniform_vector(shgroup->shader, interface->clipplanes, 4, DST.num_clip_planes, (float *)DST.clip_planes_eq);
1684 }
1685
1686 static void draw_geometry_execute(DRWShadingGroup *shgroup, Gwn_Batch *geom)
1687 {
1688         DRWInterface *interface = shgroup->interface;
1689         /* step 2 : bind vertex array & draw */
1690         GWN_batch_program_set(geom, GPU_shader_get_program(shgroup->shader), GPU_shader_get_interface(shgroup->shader));
1691         if (interface->instance_batch) {
1692                 GWN_batch_draw_stupid_instanced_with_batch(geom, interface->instance_batch);
1693         }
1694         else if (interface->instance_vbo) {
1695                 GWN_batch_draw_stupid_instanced(geom, interface->instance_vbo, interface->instance_count, interface->attribs_count,
1696                                             interface->attribs_stride, interface->attribs_size, interface->attribs_loc);
1697         }
1698         else {
1699                 GWN_batch_draw_stupid(geom);
1700         }
1701 }
1702
1703 static void draw_geometry(DRWShadingGroup *shgroup, Gwn_Batch *geom, const float (*obmat)[4], ID *ob_data)
1704 {
1705         float *texcoloc = NULL;
1706         float *texcosize = NULL;
1707
1708         if (ob_data != NULL) {
1709                 switch (GS(ob_data->name)) {
1710                         case OB_MESH:
1711                                 BKE_mesh_texspace_get_reference((Mesh *)ob_data, NULL, &texcoloc, NULL, &texcosize);
1712                                 /* TODO, curve, metaball? */
1713                         default:
1714                                 break;
1715                 }
1716         }
1717
1718         draw_geometry_prepare(shgroup, obmat, texcoloc, texcosize);
1719
1720         draw_geometry_execute(shgroup, geom);
1721 }
1722
1723 static void draw_shgroup(DRWShadingGroup *shgroup, DRWState pass_state)
1724 {
1725         BLI_assert(shgroup->shader);
1726         BLI_assert(shgroup->interface);
1727
1728         DRWInterface *interface = shgroup->interface;
1729         GPUTexture *tex;
1730         int val;
1731         float fval;
1732
1733         if (DST.shader != shgroup->shader) {
1734                 if (DST.shader) GPU_shader_unbind();
1735                 GPU_shader_bind(shgroup->shader);
1736                 DST.shader = shgroup->shader;
1737         }
1738
1739         const bool is_normal = ELEM(shgroup->type, DRW_SHG_NORMAL);
1740
1741         if (!is_normal) {
1742                 shgroup_dynamic_batch_from_calls(shgroup);
1743         }
1744
1745         DRW_state_set((pass_state & shgroup->state_extra_disable) | shgroup->state_extra);
1746
1747         /* Binding Uniform */
1748         /* Don't check anything, Interface should already contain the least uniform as possible */
1749         for (DRWUniform *uni = interface->uniforms.first; uni; uni = uni->next) {
1750                 DRWBoundTexture *bound_tex;
1751
1752                 switch (uni->type) {
1753                         case DRW_UNIFORM_SHORT_TO_INT:
1754                                 val = (int)*((short *)uni->value);
1755                                 GPU_shader_uniform_vector_int(
1756                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)&val);
1757                                 break;
1758                         case DRW_UNIFORM_SHORT_TO_FLOAT:
1759                                 fval = (float)*((short *)uni->value);
1760                                 GPU_shader_uniform_vector(
1761                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)&fval);
1762                                 break;
1763                         case DRW_UNIFORM_BOOL:
1764                         case DRW_UNIFORM_INT:
1765                                 GPU_shader_uniform_vector_int(
1766                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)uni->value);
1767                                 break;
1768                         case DRW_UNIFORM_FLOAT:
1769                         case DRW_UNIFORM_MAT3:
1770                         case DRW_UNIFORM_MAT4:
1771                                 GPU_shader_uniform_vector(
1772                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)uni->value);
1773                                 break;
1774                         case DRW_UNIFORM_TEXTURE:
1775                                 tex = (GPUTexture *)uni->value;
1776                                 BLI_assert(tex);
1777                                 GPU_texture_bind(tex, uni->bindloc);
1778
1779                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1780                                 bound_tex->tex = tex;
1781                                 BLI_addtail(&DST.bound_texs, bound_tex);
1782
1783                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1784                                 break;
1785                         case DRW_UNIFORM_BUFFER:
1786                                 if (!DRW_state_is_fbo()) {
1787                                         break;
1788                                 }
1789                                 tex = *((GPUTexture **)uni->value);
1790                                 BLI_assert(tex);
1791                                 GPU_texture_bind(tex, uni->bindloc);
1792
1793                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1794                                 bound_tex->tex = tex;
1795                                 BLI_addtail(&DST.bound_texs, bound_tex);
1796
1797                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1798                                 break;
1799                         case DRW_UNIFORM_BLOCK:
1800                                 GPU_uniformbuffer_bind((GPUUniformBuffer *)uni->value, uni->bindloc);
1801                                 GPU_shader_uniform_buffer(shgroup->shader, uni->location, (GPUUniformBuffer *)uni->value);
1802                                 break;
1803                 }
1804         }
1805
1806 #ifdef USE_GPU_SELECT
1807         /* use the first item because of selection we only ever add one */
1808 #  define GPU_SELECT_LOAD_IF_PICKSEL(_call) \
1809         if ((G.f & G_PICKSEL) && (_call)) { \
1810                 GPU_select_load_id((_call)->head.select_id); \
1811         } ((void)0)
1812 #  define GPU_SELECT_LOAD_IF_PICKSEL_LIST(_call_ls) \
1813         if ((G.f & G_PICKSEL) && (_call_ls)->first) { \
1814                 BLI_assert(BLI_listbase_is_single(_call_ls)); \
1815                 GPU_select_load_id(((DRWCall *)(_call_ls)->first)->head.select_id); \
1816         } ((void)0)
1817 #else
1818 #  define GPU_SELECT_LOAD_IF_PICKSEL(call)
1819 #  define GPU_SELECT_LOAD_IF_PICKSEL_LIST(call)
1820 #endif
1821
1822         /* Rendering Calls */
1823         if (!is_normal) {
1824                 /* Replacing multiple calls with only one */
1825                 float obmat[4][4];
1826                 unit_m4(obmat);
1827
1828                 if (shgroup->type == DRW_SHG_INSTANCE &&
1829                         (interface->instance_count > 0 || interface->instance_batch != NULL))
1830                 {
1831                         GPU_SELECT_LOAD_IF_PICKSEL_LIST(&shgroup->calls);
1832                         draw_geometry(shgroup, shgroup->instance_geom, obmat, NULL);
1833                 }
1834                 else {
1835                         /* Some dynamic batch can have no geom (no call to aggregate) */
1836                         if (shgroup->batch_geom) {
1837                                 GPU_SELECT_LOAD_IF_PICKSEL_LIST(&shgroup->calls);
1838                                 draw_geometry(shgroup, shgroup->batch_geom, obmat, NULL);
1839                         }
1840                 }
1841         }
1842         else {
1843                 for (DRWCall *call = shgroup->calls.first; call; call = call->head.next) {
1844                         bool neg_scale = is_negative_m4(call->obmat);
1845
1846                         /* Negative scale objects */
1847                         if (neg_scale) {
1848                                 glFrontFace(DST.backface);
1849                         }
1850
1851                         GPU_SELECT_LOAD_IF_PICKSEL(call);
1852
1853                         if (call->head.type == DRW_CALL_SINGLE) {
1854                                 draw_geometry(shgroup, call->geometry, call->obmat, call->ob_data);
1855                         }
1856                         else {
1857                                 BLI_assert(call->head.type == DRW_CALL_GENERATE);
1858                                 DRWCallGenerate *callgen = ((DRWCallGenerate *)call);
1859                                 draw_geometry_prepare(shgroup, callgen->obmat, NULL, NULL);
1860                                 callgen->geometry_fn(shgroup, draw_geometry_execute, callgen->user_data);
1861                         }
1862
1863                         /* Reset state */
1864                         if (neg_scale) {
1865                                 glFrontFace(DST.frontface);
1866                         }
1867                 }
1868         }
1869
1870         /* TODO: remove, (currently causes alpha issue with sculpt, need to investigate) */
1871         DRW_state_reset();
1872 }
1873
1874 static void DRW_draw_pass_ex(DRWPass *pass, DRWShadingGroup *start_group, DRWShadingGroup *end_group)
1875 {
1876         /* Start fresh */
1877         DST.shader = NULL;
1878         DST.tex_bind_id = 0;
1879
1880         DRW_state_set(pass->state);
1881         BLI_listbase_clear(&DST.bound_texs);
1882
1883         /* Init Timer queries */
1884         if (pass->timer_queries[0] == 0) {
1885                 pass->front_idx = 0;
1886                 pass->back_idx = 1;
1887
1888                 glGenQueries(2, pass->timer_queries);
1889
1890                 /* dummy query, avoid gl error */
1891                 glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->front_idx]);
1892                 glEndQuery(GL_TIME_ELAPSED);
1893         }
1894         else {
1895                 /* swap indices */
1896                 unsigned int tmp = pass->back_idx;
1897                 pass->back_idx = pass->front_idx;
1898                 pass->front_idx = tmp;
1899         }
1900
1901         if (!pass->wasdrawn) {
1902                 /* issue query for the next frame */
1903                 glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->back_idx]);
1904         }
1905
1906         for (DRWShadingGroup *shgroup = start_group; shgroup; shgroup = shgroup->next) {
1907                 draw_shgroup(shgroup, pass->state);
1908                 /* break if upper limit */
1909                 if (shgroup == end_group) {
1910                         break;
1911                 }
1912         }
1913
1914         /* Clear Bound textures */
1915         for (DRWBoundTexture *bound_tex = DST.bound_texs.first; bound_tex; bound_tex = bound_tex->next) {
1916                 GPU_texture_unbind(bound_tex->tex);
1917         }
1918         DST.tex_bind_id = 0;
1919         BLI_freelistN(&DST.bound_texs);
1920
1921         if (DST.shader) {
1922                 GPU_shader_unbind();
1923                 DST.shader = NULL;
1924         }
1925
1926         if (!pass->wasdrawn) {
1927                 glEndQuery(GL_TIME_ELAPSED);
1928         }
1929
1930         pass->wasdrawn = true;
1931 }
1932
1933 void DRW_draw_pass(DRWPass *pass)
1934 {
1935         DRW_draw_pass_ex(pass, pass->shgroups.first, pass->shgroups.last);
1936 }
1937
1938 /* Draw only a subset of shgroups. Used in special situations as grease pencil strokes */
1939 void DRW_draw_pass_subset(DRWPass *pass, DRWShadingGroup *start_group, DRWShadingGroup *end_group)
1940 {
1941         DRW_draw_pass_ex(pass, start_group, end_group);
1942 }
1943
1944 void DRW_draw_callbacks_pre_scene(void)
1945 {
1946         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1947
1948         gpuLoadProjectionMatrix(rv3d->winmat);
1949         gpuLoadMatrix(rv3d->viewmat);
1950 }
1951
1952 void DRW_draw_callbacks_post_scene(void)
1953 {
1954         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1955
1956         gpuLoadProjectionMatrix(rv3d->winmat);
1957         gpuLoadMatrix(rv3d->viewmat);
1958 }
1959
1960 /* Reset state to not interfer with other UI drawcall */
1961 void DRW_state_reset_ex(DRWState state)
1962 {
1963         DST.state = ~state;
1964         DRW_state_set(state);
1965 }
1966
1967 void DRW_state_reset(void)
1968 {
1969         /* Reset blending function */
1970         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1971
1972         DRW_state_reset_ex(DRW_STATE_DEFAULT);
1973 }
1974
1975 /* NOTE : Make sure to reset after use! */
1976 void DRW_state_invert_facing(void)
1977 {
1978         SWAP(GLenum, DST.backface, DST.frontface);
1979         glFrontFace(DST.frontface);
1980 }
1981
1982 /**
1983  * This only works if DRWPasses have been tagged with DRW_STATE_CLIP_PLANES,
1984  * and if the shaders have support for it (see usage of gl_ClipDistance).
1985  * Be sure to call DRW_state_clip_planes_reset() after you finish drawing.
1986  **/
1987 void DRW_state_clip_planes_add(float plane_eq[4])
1988 {
1989         copy_v4_v4(DST.clip_planes_eq[DST.num_clip_planes++], plane_eq);
1990 }
1991
1992 void DRW_state_clip_planes_reset(void)
1993 {
1994         DST.num_clip_planes = 0;
1995 }
1996
1997 /** \} */
1998
1999
2000 struct DRWTextStore *DRW_text_cache_ensure(void)
2001 {
2002         BLI_assert(DST.text_store_p);
2003         if (*DST.text_store_p == NULL) {
2004                 *DST.text_store_p = DRW_text_cache_create();
2005         }
2006         return *DST.text_store_p;
2007 }
2008
2009
2010 /* -------------------------------------------------------------------- */
2011
2012 /** \name Settings
2013  * \{ */
2014
2015 bool DRW_object_is_renderable(Object *ob)
2016 {
2017         Scene *scene = DST.draw_ctx.scene;
2018         Object *obedit = scene->obedit;
2019
2020         if (ob->type == OB_MESH) {
2021                 if (ob == obedit) {
2022                         IDProperty *props = BKE_layer_collection_engine_evaluated_get(ob, COLLECTION_MODE_EDIT, "");
2023                         bool do_show_occlude_wire = BKE_collection_engine_property_value_get_bool(props, "show_occlude_wire");
2024                         if (do_show_occlude_wire) {
2025                                 return false;
2026                         }
2027                         bool do_show_weight = BKE_collection_engine_property_value_get_bool(props, "show_weight");
2028                         if (do_show_weight) {
2029                                 return false;
2030                         }
2031                 }
2032         }
2033
2034         return true;
2035 }
2036
2037
2038 bool DRW_object_is_flat_normal(Object *ob)
2039 {
2040         if (ob->type == OB_MESH) {
2041                 Mesh *me = ob->data;
2042                 if (me->mpoly && me->mpoly[0].flag & ME_SMOOTH) {
2043                         return false;
2044                 }
2045         }
2046         return true;
2047 }
2048
2049 /** \} */
2050
2051
2052 /* -------------------------------------------------------------------- */
2053
2054 /** \name Framebuffers (DRW_framebuffer)
2055  * \{ */
2056
2057 static GPUTextureFormat convert_tex_format(int fbo_format, int *channels, bool *is_depth)
2058 {
2059         *is_depth = ELEM(fbo_format, DRW_TEX_DEPTH_16, DRW_TEX_DEPTH_24);
2060
2061         switch (fbo_format) {
2062                 case DRW_TEX_R_16:     *channels = 1; return GPU_R16F;
2063                 case DRW_TEX_R_32:     *channels = 1; return GPU_R32F;
2064                 case DRW_TEX_RG_16:    *channels = 2; return GPU_RG16F;
2065                 case DRW_TEX_RG_32:    *channels = 2; return GPU_RG32F;
2066                 case DRW_TEX_RGBA_8:   *channels = 4; return GPU_RGBA8;
2067                 case DRW_TEX_RGBA_16:  *channels = 4; return GPU_RGBA16F;
2068                 case DRW_TEX_RGBA_32:  *channels = 4; return GPU_RGBA32F;
2069                 case DRW_TEX_DEPTH_24: *channels = 1; return GPU_DEPTH_COMPONENT24;
2070                 case DRW_TEX_RGB_11_11_10: *channels = 3; return GPU_R11F_G11F_B10F;
2071                 default:
2072                         BLI_assert(false && "Texture format unsupported as render target!");
2073                         *channels = 4; return GPU_RGBA8;
2074         }
2075 }
2076
2077 void DRW_framebuffer_init(
2078         struct GPUFrameBuffer **fb, void *engine_type, int width, int height,
2079         DRWFboTexture textures[MAX_FBO_TEX], int textures_len)
2080 {
2081         BLI_assert(textures_len <= MAX_FBO_TEX);
2082
2083         bool create_fb = false;
2084         int color_attachment = -1;
2085
2086         if (!*fb) {
2087                 *fb = GPU_framebuffer_create();
2088                 create_fb = true;
2089         }
2090
2091         for (int i = 0; i < textures_len; ++i) {
2092                 int channels;
2093                 bool is_depth;
2094
2095                 DRWFboTexture fbotex = textures[i];
2096                 bool is_temp = (fbotex.flag & DRW_TEX_TEMP) != 0;
2097
2098                 GPUTextureFormat gpu_format = convert_tex_format(fbotex.format, &channels, &is_depth);
2099
2100                 if (!*fbotex.tex || is_temp) {
2101                         /* Temp textures need to be queried each frame, others not. */
2102                         if (is_temp) {
2103                                 *fbotex.tex = GPU_viewport_texture_pool_query(DST.viewport, engine_type, width, height, channels, gpu_format);
2104                         }
2105                         else if (create_fb) {
2106                                 *fbotex.tex = GPU_texture_create_2D_custom(width, height, channels, gpu_format, NULL, NULL);
2107                         }
2108                 }
2109
2110                 if (create_fb) {
2111                         if (!is_depth) {
2112                                 ++color_attachment;
2113                         }
2114                         drw_texture_set_parameters(*fbotex.tex, fbotex.flag);
2115                         GPU_framebuffer_texture_attach(*fb, *fbotex.tex, color_attachment, 0);
2116                 }
2117         }
2118
2119         if (create_fb) {
2120                 if (!GPU_framebuffer_check_valid(*fb, NULL)) {
2121                         printf("Error invalid framebuffer\n");
2122                 }
2123
2124                 /* Detach temp textures */
2125                 for (int i = 0; i < textures_len; ++i) {
2126                         DRWFboTexture fbotex = textures[i];
2127
2128                         if ((fbotex.flag & DRW_TEX_TEMP) != 0) {
2129                                 GPU_framebuffer_texture_detach(*fbotex.tex);
2130                         }
2131                 }
2132
2133                 GPU_framebuffer_bind(DST.default_framebuffer);
2134         }
2135 }
2136
2137 void DRW_framebuffer_free(struct GPUFrameBuffer *fb)
2138 {
2139         GPU_framebuffer_free(fb);
2140 }
2141
2142 void DRW_framebuffer_bind(struct GPUFrameBuffer *fb)
2143 {
2144         GPU_framebuffer_bind(fb);
2145 }
2146
2147 void DRW_framebuffer_clear(bool color, bool depth, bool stencil, float clear_col[4], float clear_depth)
2148 {
2149         if (color) {
2150                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2151                 glClearColor(clear_col[0], clear_col[1], clear_col[2], clear_col[3]);
2152         }
2153         if (depth) {
2154                 glDepthMask(GL_TRUE);
2155                 glClearDepth(clear_depth);
2156         }
2157         if (stencil) {
2158                 glStencilMask(0xFF);
2159         }
2160         glClear(((color) ? GL_COLOR_BUFFER_BIT : 0) |
2161                 ((depth) ? GL_DEPTH_BUFFER_BIT : 0) |
2162                 ((stencil) ? GL_STENCIL_BUFFER_BIT : 0));
2163 }
2164
2165 void DRW_framebuffer_read_data(int x, int y, int w, int h, int channels, int slot, float *data)
2166 {
2167         GLenum type;
2168         switch (channels) {
2169                 case 1: type = GL_RED; break;
2170                 case 2: type = GL_RG; break;
2171                 case 3: type = GL_RGB; break;
2172                 case 4: type = GL_RGBA; break;
2173                 default:
2174                         BLI_assert(false && "wrong number of read channels");
2175                         return;
2176         }
2177         glReadBuffer(GL_COLOR_ATTACHMENT0 + slot);
2178         glReadPixels(x, y, w, h, type, GL_FLOAT, data);
2179 }
2180
2181 void DRW_framebuffer_texture_attach(struct GPUFrameBuffer *fb, GPUTexture *tex, int slot, int mip)
2182 {
2183         GPU_framebuffer_texture_attach(fb, tex, slot, mip);
2184 }
2185
2186 void DRW_framebuffer_texture_layer_attach(struct GPUFrameBuffer *fb, struct GPUTexture *tex, int slot, int layer, int mip)
2187 {
2188         GPU_framebuffer_texture_layer_attach(fb, tex, slot, layer, mip);
2189 }
2190
2191 void DRW_framebuffer_cubeface_attach(struct GPUFrameBuffer *fb, GPUTexture *tex, int slot, int face, int mip)
2192 {
2193         GPU_framebuffer_texture_cubeface_attach(fb, tex, slot, face, mip);
2194 }
2195
2196 void DRW_framebuffer_texture_detach(GPUTexture *tex)
2197 {
2198         GPU_framebuffer_texture_detach(tex);
2199 }
2200
2201 void DRW_framebuffer_blit(struct GPUFrameBuffer *fb_read, struct GPUFrameBuffer *fb_write, bool depth)
2202 {
2203         GPU_framebuffer_blit(fb_read, 0, fb_write, 0, depth);
2204 }
2205
2206 void DRW_framebuffer_recursive_downsample(
2207         struct GPUFrameBuffer *fb, struct GPUTexture *tex, int num_iter,
2208         void (*callback)(void *userData, int level), void *userData)
2209 {
2210         GPU_framebuffer_recursive_downsample(fb, tex, num_iter, callback, userData);
2211 }
2212
2213 void DRW_framebuffer_viewport_size(struct GPUFrameBuffer *UNUSED(fb_read), int x, int y, int w, int h)
2214 {
2215         glViewport(x, y, w, h);
2216 }
2217
2218 /* Use color management profile to draw texture to framebuffer */
2219 void DRW_transform_to_display(GPUTexture *tex)
2220 {
2221         DRW_state_set(DRW_STATE_WRITE_COLOR);
2222
2223         Gwn_VertFormat *vert_format = immVertexFormat();
2224         unsigned int pos = GWN_vertformat_attr_add(vert_format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2225         unsigned int texco = GWN_vertformat_attr_add(vert_format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2226
2227         const float dither = 1.0f;
2228
2229         bool use_ocio = false;
2230
2231         if (DST.draw_ctx.evil_C != NULL) {
2232                 use_ocio = IMB_colormanagement_setup_glsl_draw_from_space_ctx(DST.draw_ctx.evil_C, NULL, dither, false);
2233         }
2234
2235         if (!use_ocio) {
2236                 immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_LINEAR_TO_SRGB);
2237                 immUniform1i("image", 0);
2238         }
2239
2240         GPU_texture_bind(tex, 0); /* OCIO texture bind point is 0 */
2241
2242         float mat[4][4];
2243         unit_m4(mat);
2244         immUniformMatrix4fv("ModelViewProjectionMatrix", mat);
2245
2246         /* Full screen triangle */
2247         immBegin(GWN_PRIM_TRIS, 3);
2248         immAttrib2f(texco, 0.0f, 0.0f);
2249         immVertex2f(pos, -1.0f, -1.0f);
2250
2251         immAttrib2f(texco, 2.0f, 0.0f);
2252         immVertex2f(pos, 3.0f, -1.0f);
2253
2254         immAttrib2f(texco, 0.0f, 2.0f);
2255         immVertex2f(pos, -1.0f, 3.0f);
2256         immEnd();
2257
2258         GPU_texture_unbind(tex);
2259
2260         if (use_ocio) {
2261                 IMB_colormanagement_finish_glsl_draw();
2262         }
2263         else {
2264                 immUnbindProgram();
2265         }
2266 }
2267
2268 /** \} */
2269
2270
2271 /* -------------------------------------------------------------------- */
2272
2273 /** \name Viewport (DRW_viewport)
2274  * \{ */
2275
2276 static void *DRW_viewport_engine_data_get(void *engine_type)
2277 {
2278         void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
2279
2280         if (data == NULL) {
2281                 data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
2282         }
2283         return data;
2284 }
2285
2286 void DRW_engine_viewport_data_size_get(
2287         const void *engine_type_v,
2288         int *r_fbl_len, int *r_txl_len, int *r_psl_len, int *r_stl_len)
2289 {
2290         const DrawEngineType *engine_type = engine_type_v;
2291
2292         if (r_fbl_len) {
2293                 *r_fbl_len = engine_type->vedata_size->fbl_len;
2294         }
2295         if (r_txl_len) {
2296                 *r_txl_len = engine_type->vedata_size->txl_len;
2297         }
2298         if (r_psl_len) {
2299                 *r_psl_len = engine_type->vedata_size->psl_len;
2300         }
2301         if (r_stl_len) {
2302                 *r_stl_len = engine_type->vedata_size->stl_len;
2303         }
2304 }
2305
2306 const float *DRW_viewport_size_get(void)
2307 {
2308         return &DST.size[0];
2309 }
2310
2311 const float *DRW_viewport_screenvecs_get(void)
2312 {
2313         return &DST.screenvecs[0][0];
2314 }
2315
2316 const float *DRW_viewport_pixelsize_get(void)
2317 {
2318         return &DST.pixsize;
2319 }
2320
2321 /* It also stores viewport variable to an immutable place: DST
2322  * This is because a cache uniform only store reference
2323  * to its value. And we don't want to invalidate the cache
2324  * if this value change per viewport */
2325 static void DRW_viewport_var_init(void)
2326 {
2327         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2328
2329         /* Refresh DST.size */
2330         if (DST.viewport) {
2331                 int size[2];
2332                 GPU_viewport_size_get(DST.viewport, size);
2333                 DST.size[0] = size[0];
2334                 DST.size[1] = size[1];
2335
2336                 DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
2337                 DST.default_framebuffer = fbl->default_fb;
2338         }
2339         else {
2340                 DST.size[0] = 0;
2341                 DST.size[1] = 0;
2342
2343                 DST.default_framebuffer = NULL;
2344         }
2345         /* Refresh DST.screenvecs */
2346         copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
2347         copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
2348         normalize_v3(DST.screenvecs[0]);
2349         normalize_v3(DST.screenvecs[1]);
2350
2351         /* Refresh DST.pixelsize */
2352         DST.pixsize = rv3d->pixsize;
2353
2354         /* Reset facing */
2355         DST.frontface = GL_CCW;
2356         DST.backface = GL_CW;
2357         glFrontFace(DST.frontface);
2358 }
2359
2360 void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
2361 {
2362         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2363
2364         switch (type) {
2365                 case DRW_MAT_PERS:
2366                         copy_m4_m4(mat, rv3d->persmat);
2367                         break;
2368                 case DRW_MAT_PERSINV:
2369                         copy_m4_m4(mat, rv3d->persinv);
2370                         break;
2371                 case DRW_MAT_VIEW:
2372                         copy_m4_m4(mat, rv3d->viewmat);
2373                         break;
2374                 case DRW_MAT_VIEWINV:
2375                         copy_m4_m4(mat, rv3d->viewinv);
2376                         break;
2377                 case DRW_MAT_WIN:
2378                         copy_m4_m4(mat, rv3d->winmat);
2379                         break;
2380                 case DRW_MAT_WININV:
2381                         invert_m4_m4(mat, rv3d->winmat);
2382                         break;
2383                 default:
2384                         BLI_assert(!"Matrix type invalid");
2385                         break;
2386         }
2387 }
2388
2389 void DRW_viewport_matrix_override_set(float mat[4][4], DRWViewportMatrixType type)
2390 {
2391         copy_m4_m4(viewport_matrix_override.mat[type], mat);
2392         viewport_matrix_override.override[type] = true;
2393 }
2394
2395 void DRW_viewport_matrix_override_unset(DRWViewportMatrixType type)
2396 {
2397         viewport_matrix_override.override[type] = false;
2398 }
2399
2400 bool DRW_viewport_is_persp_get(void)
2401 {
2402         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2403         return rv3d->is_persp;
2404 }
2405
2406 DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
2407 {
2408         return GPU_viewport_framebuffer_list_get(DST.viewport);
2409 }
2410
2411 DefaultTextureList *DRW_viewport_texture_list_get(void)
2412 {
2413         return GPU_viewport_texture_list_get(DST.viewport);
2414 }
2415
2416 void DRW_viewport_request_redraw(void)
2417 {
2418         /* XXXXXXXXXXX HAAAAAAAACKKKK */
2419         WM_main_add_notifier(NC_MATERIAL | ND_SHADING_DRAW, NULL);
2420 }
2421
2422 /** \} */
2423
2424
2425 /* -------------------------------------------------------------------- */
2426 /** \name SceneLayers (DRW_scenelayer)
2427  * \{ */
2428
2429 void **DRW_scene_layer_engine_data_get(DrawEngineType *engine_type, void (*callback)(void *storage))
2430 {
2431         SceneLayerEngineData *sled;
2432
2433         for (sled = DST.draw_ctx.sl->drawdata.first; sled; sled = sled->next) {
2434                 if (sled->engine_type == engine_type) {
2435                         return &sled->storage;
2436                 }
2437         }
2438
2439         sled = MEM_callocN(sizeof(SceneLayerEngineData), "SceneLayerEngineData");
2440         sled->engine_type = engine_type;
2441         sled->free = callback;
2442         BLI_addtail(&DST.draw_ctx.sl->drawdata, sled);
2443
2444         return &sled->storage;
2445 }
2446
2447 /** \} */
2448
2449
2450 /* -------------------------------------------------------------------- */
2451
2452 /** \name Objects (DRW_object)
2453  * \{ */
2454
2455 void **DRW_object_engine_data_get(
2456         Object *ob, DrawEngineType *engine_type, void (*callback)(void *storage))
2457 {
2458         ObjectEngineData *oed;
2459
2460         for (oed = ob->drawdata.first; oed; oed = oed->next) {
2461                 if (oed->engine_type == engine_type) {
2462                         return &oed->storage;
2463                 }
2464         }
2465
2466         oed = MEM_callocN(sizeof(ObjectEngineData), "ObjectEngineData");
2467         oed->engine_type = engine_type;
2468         oed->free = callback;
2469         BLI_addtail(&ob->drawdata, oed);
2470
2471         return &oed->storage;
2472 }
2473
2474 /* XXX There is definitly some overlap between this and DRW_object_engine_data_get.
2475  * We should get rid of one of the two. */
2476 LampEngineData *DRW_lamp_engine_data_get(Object *ob, RenderEngineType *engine_type)
2477 {
2478         BLI_assert(ob->type == OB_LAMP);
2479
2480         Scene *scene = DST.draw_ctx.scene;
2481
2482         /* TODO Dupliobjects */
2483         /* TODO Should be per scenelayer */
2484         return GPU_lamp_engine_data_get(scene, ob, NULL, engine_type);
2485 }
2486
2487 void DRW_lamp_engine_data_free(LampEngineData *led)
2488 {
2489         GPU_lamp_engine_data_free(led);
2490 }
2491
2492 /** \} */
2493
2494
2495 /* -------------------------------------------------------------------- */
2496
2497 /** \name Rendering (DRW_engines)
2498  * \{ */
2499
2500 #define TIMER_FALLOFF 0.1f
2501
2502 static void DRW_engines_init(void)
2503 {
2504         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2505                 DrawEngineType *engine = link->data;
2506                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2507                 double stime = PIL_check_seconds_timer();
2508
2509                 if (engine->engine_init) {
2510                         engine->engine_init(data);
2511                 }
2512
2513                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2514                 data->init_time = data->init_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2515         }
2516 }
2517
2518 static void DRW_engines_cache_init(void)
2519 {
2520         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2521                 DrawEngineType *engine = link->data;
2522                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2523
2524                 if (data->text_draw_cache) {
2525                         DRW_text_cache_destroy(data->text_draw_cache);
2526                         data->text_draw_cache = NULL;
2527                 }
2528                 if (DST.text_store_p == NULL) {
2529                         DST.text_store_p = &data->text_draw_cache;
2530                 }
2531
2532                 double stime = PIL_check_seconds_timer();
2533                 data->cache_time = 0.0;
2534
2535                 if (engine->cache_init) {
2536                         engine->cache_init(data);
2537                 }
2538
2539                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2540         }
2541 }
2542
2543 static void DRW_engines_cache_populate(Object *ob)
2544 {
2545         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2546                 DrawEngineType *engine = link->data;
2547                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2548                 double stime = PIL_check_seconds_timer();
2549
2550                 if (engine->cache_populate) {
2551                         engine->cache_populate(data, ob);
2552                 }
2553
2554                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2555         }
2556 }
2557
2558 static void DRW_engines_cache_finish(void)
2559 {
2560         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2561                 DrawEngineType *engine = link->data;
2562                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2563                 double stime = PIL_check_seconds_timer();
2564
2565                 if (engine->cache_finish) {
2566                         engine->cache_finish(data);
2567                 }
2568
2569                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2570         }
2571 }
2572
2573 static void DRW_engines_draw_background(void)
2574 {
2575         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2576                 DrawEngineType *engine = link->data;
2577                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2578                 double stime = PIL_check_seconds_timer();
2579
2580                 if (engine->draw_background) {
2581                         engine->draw_background(data);
2582                         return;
2583                 }
2584
2585                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2586                 data->background_time = data->background_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2587         }
2588
2589         /* No draw_background found, doing default background */
2590         DRW_draw_background();
2591 }
2592
2593 static void DRW_engines_draw_scene(void)
2594 {
2595         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2596                 DrawEngineType *engine = link->data;
2597                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2598                 double stime = PIL_check_seconds_timer();
2599
2600                 if (engine->draw_scene) {
2601                         engine->draw_scene(data);
2602                 }
2603
2604                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2605                 data->render_time = data->render_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2606         }
2607 }
2608
2609 static void DRW_engines_draw_text(void)
2610 {
2611         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2612                 DrawEngineType *engine = link->data;
2613                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2614                 double stime = PIL_check_seconds_timer();
2615
2616                 if (data->text_draw_cache) {
2617                         DRW_text_cache_draw(data->text_draw_cache, DST.draw_ctx.v3d, DST.draw_ctx.ar, false);
2618                 }
2619
2620                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2621                 data->render_time = data->render_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2622         }
2623 }
2624
2625 #define MAX_INFO_LINES 10
2626
2627 /**
2628  * Returns the offset required for the drawing of engines info.
2629  */
2630 int DRW_draw_region_engine_info_offset(void)
2631 {
2632         int lines = 0;
2633         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2634                 DrawEngineType *engine = link->data;
2635                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2636
2637                 /* Count the number of lines. */
2638                 if (data->info[0] != '\0') {
2639                         lines++;
2640                         char *c = data->info;
2641                         while (*c++ != '\0') {
2642                                 if (*c == '\n') {
2643                                         lines++;
2644                                 }
2645                         }
2646                 }
2647         }
2648         return MIN2(MAX_INFO_LINES, lines) * UI_UNIT_Y;
2649 }
2650
2651 /**
2652  * Actual drawing;
2653  */
2654 void DRW_draw_region_engine_info(void)
2655 {
2656         const char *info_array_final[MAX_INFO_LINES + 1];
2657         char info_array[MAX_INFO_LINES][GPU_INFO_SIZE]; /* This should be maxium number of engines running at the same time. */
2658         int i = 0;
2659
2660         const DRWContextState *draw_ctx = DRW_context_state_get();
2661         ARegion *ar = draw_ctx->ar;
2662         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
2663
2664         UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
2665         mul_v3_fl(fill_color, fill_color[3]);
2666
2667         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2668                 DrawEngineType *engine = link->data;
2669                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2670
2671                 if (data->info[0] != '\0') {
2672                         char *chr_current = data->info;
2673                         char *chr_start = chr_current;
2674                         int line_len = 0;
2675
2676                         while (*chr_current++ != '\0') {
2677                                 line_len++;
2678                                 if (*chr_current == '\n') {
2679                                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
2680                                         /* Re-start counting. */
2681                                         chr_start = chr_current + 1;
2682                                         line_len = -1;
2683                                 }
2684                         }
2685
2686                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
2687
2688                         if (i >= MAX_INFO_LINES) {
2689                                 break;
2690                         }
2691                 }
2692         }
2693
2694         for (int j = 0; j < i; j++) {
2695                 info_array_final[j] = info_array[j];
2696         }
2697         info_array_final[i] = NULL;
2698
2699         if (info_array[0] != NULL) {
2700                 ED_region_info_draw_multiline(ar, info_array_final, fill_color, true);
2701         }
2702 }
2703
2704 #undef MAX_INFO_LINES
2705
2706 static void use_drw_engine(DrawEngineType *engine)
2707 {
2708         LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
2709         ld->data = engine;
2710         BLI_addtail(&DST.enabled_engines, ld);
2711 }
2712
2713 /* TODO revisit this when proper layering is implemented */
2714 /* Gather all draw engines needed and store them in DST.enabled_engines
2715  * That also define the rendering order of engines */
2716 static void DRW_engines_enable_from_engine(const Scene *scene)
2717 {
2718         /* TODO layers */
2719         RenderEngineType *type = RE_engines_find(scene->r.engine);
2720         if (type->draw_engine != NULL) {
2721                 use_drw_engine(type->draw_engine);
2722         }
2723
2724         if ((type->flag & RE_INTERNAL) == 0) {
2725                 DRW_engines_enable_external();
2726         }
2727 }
2728
2729 static void DRW_engines_enable_from_object_mode(void)
2730 {
2731         use_drw_engine(&draw_engine_object_type);
2732 }
2733
2734 static void DRW_engines_enable_from_mode(int mode)
2735 {
2736         switch (mode) {
2737                 case CTX_MODE_EDIT_MESH:
2738                         use_drw_engine(&draw_engine_edit_mesh_type);
2739                         break;
2740                 case CTX_MODE_EDIT_CURVE:
2741                         use_drw_engine(&draw_engine_edit_curve_type);
2742                         break;
2743                 case CTX_MODE_EDIT_SURFACE:
2744                         use_drw_engine(&draw_engine_edit_surface_type);
2745                         break;
2746                 case CTX_MODE_EDIT_TEXT:
2747                         use_drw_engine(&draw_engine_edit_text_type);
2748                         break;
2749                 case CTX_MODE_EDIT_ARMATURE:
2750                         use_drw_engine(&draw_engine_edit_armature_type);
2751                         break;
2752                 case CTX_MODE_EDIT_METABALL:
2753                         use_drw_engine(&draw_engine_edit_metaball_type);
2754                         break;
2755                 case CTX_MODE_EDIT_LATTICE:
2756                         use_drw_engine(&draw_engine_edit_lattice_type);
2757                         break;
2758                 case CTX_MODE_POSE:
2759                         use_drw_engine(&draw_engine_pose_type);
2760                         break;
2761                 case CTX_MODE_SCULPT:
2762                         use_drw_engine(&draw_engine_sculpt_type);
2763                         break;
2764                 case CTX_MODE_PAINT_WEIGHT:
2765                         use_drw_engine(&draw_engine_pose_type);
2766                         use_drw_engine(&draw_engine_paint_weight_type);
2767                         break;
2768                 case CTX_MODE_PAINT_VERTEX:
2769                         use_drw_engine(&draw_engine_paint_vertex_type);
2770                         break;
2771                 case CTX_MODE_PAINT_TEXTURE:
2772                         use_drw_engine(&draw_engine_paint_texture_type);
2773                         break;
2774                 case CTX_MODE_PARTICLE:
2775                         use_drw_engine(&draw_engine_particle_type);
2776                         break;
2777                 case CTX_MODE_OBJECT:
2778                         break;
2779                 default:
2780                         BLI_assert(!"Draw mode invalid");
2781                         break;
2782         }
2783 }
2784
2785 /**
2786  * Use for select and depth-drawing.
2787  */
2788 static void DRW_engines_enable_basic(void)
2789 {
2790         use_drw_engine(DRW_engine_viewport_basic_type.draw_engine);
2791 }
2792
2793 /**
2794  * Use for external render engines.
2795  */
2796 static void DRW_engines_enable_external(void)
2797 {
2798         use_drw_engine(DRW_engine_viewport_external_type.draw_engine);
2799 }
2800
2801 static void DRW_engines_enable(const Scene *scene, SceneLayer *sl)
2802 {
2803         const int mode = CTX_data_mode_enum_ex(scene->obedit, OBACT_NEW);
2804         DRW_engines_enable_from_engine(scene);
2805
2806         if (DRW_state_draw_support()) {
2807                 DRW_engines_enable_from_object_mode();
2808                 DRW_engines_enable_from_mode(mode);
2809         }
2810 }
2811
2812 static void DRW_engines_disable(void)
2813 {
2814         BLI_freelistN(&DST.enabled_engines);
2815 }
2816
2817 static unsigned int DRW_engines_get_hash(void)
2818 {
2819         unsigned int hash = 0;
2820         /* The cache depends on enabled engines */
2821         /* FIXME : if collision occurs ... segfault */
2822         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2823                 DrawEngineType *engine = link->data;
2824                 hash += BLI_ghashutil_strhash_p(engine->idname);
2825         }
2826
2827         return hash;
2828 }
2829
2830 static void draw_stat(rcti *rect, int u, int v, const char *txt, const int size)
2831 {
2832         BLF_draw_default_ascii(rect->xmin + (1 + u * 5) * U.widget_unit,
2833                                rect->ymax - (3 + v++) * U.widget_unit, 0.0f,
2834                                txt, size);
2835 }
2836
2837 /* CPU stats */
2838 static void DRW_debug_cpu_stats(void)
2839 {
2840         int u, v;
2841         double cache_tot_time = 0.0, init_tot_time = 0.0, background_tot_time = 0.0, render_tot_time = 0.0, tot_time = 0.0;
2842         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2843         rcti rect;
2844         struct ARegion *ar = DST.draw_ctx.ar;
2845         ED_region_visible_rect(ar, &rect);
2846
2847         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2848
2849         /* row by row */
2850         v = 0; u = 0;
2851         /* Label row */
2852         char col_label[32];
2853         sprintf(col_label, "Engine");
2854         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2855         sprintf(col_label, "Cache");
2856         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2857         sprintf(col_label, "Init");
2858         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2859         sprintf(col_label, "Background");
2860         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2861         sprintf(col_label, "Render");
2862         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2863         sprintf(col_label, "Total (w/o cache)");
2864         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2865         v++;
2866
2867         /* Engines rows */
2868         char time_to_txt[16];
2869         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2870                 u = 0;
2871                 DrawEngineType *engine = link->data;
2872                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2873
2874                 draw_stat(&rect, u++, v, engine->idname, sizeof(engine->idname));
2875
2876                 cache_tot_time += data->cache_time;
2877                 sprintf(time_to_txt, "%.2fms", data->cache_time);
2878                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2879
2880                 init_tot_time += data->init_time;
2881                 sprintf(time_to_txt, "%.2fms", data->init_time);
2882                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2883
2884                 background_tot_time += data->background_time;
2885                 sprintf(time_to_txt, "%.2fms", data->background_time);
2886                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2887
2888                 render_tot_time += data->render_time;
2889                 sprintf(time_to_txt, "%.2fms", data->render_time);
2890                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2891
2892                 tot_time += data->init_time + data->background_time + data->render_time;
2893                 sprintf(time_to_txt, "%.2fms", data->init_time + data->background_time + data->render_time);
2894                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2895                 v++;
2896         }
2897
2898         /* Totals row */
2899         u = 0;
2900         sprintf(col_label, "Sub Total");
2901         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2902         sprintf(time_to_txt, "%.2fms", cache_tot_time);
2903         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2904         sprintf(time_to_txt, "%.2fms", init_tot_time);
2905         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2906         sprintf(time_to_txt, "%.2fms", background_tot_time);
2907         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2908         sprintf(time_to_txt, "%.2fms", render_tot_time);
2909         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2910         sprintf(time_to_txt, "%.2fms", tot_time);
2911         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2912 }
2913
2914 /* Display GPU time for each passes */
2915 static void DRW_debug_gpu_stats(void)
2916 {
2917         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2918         rcti rect;
2919         struct ARegion *ar = DST.draw_ctx.ar;
2920         ED_region_visible_rect(ar, &rect);
2921
2922         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2923
2924         char time_to_txt[16];
2925         char pass_name[MAX_PASS_NAME + 16];
2926         int v = BLI_listbase_count(&DST.enabled_engines) + 3;
2927         GLuint64 tot_time = 0;
2928
2929         if (G.debug_value > 666) {
2930                 for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2931                         GLuint64 engine_time = 0;
2932                         DrawEngineType *engine = link->data;
2933                         ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2934                         int vsta = v;
2935
2936                         draw_stat(&rect, 0, v, engine->idname, sizeof(engine->idname));
2937                         v++;
2938
2939                         for (int i = 0; i < engine->vedata_size->psl_len; ++i) {
2940                                 DRWPass *pass = data->psl->passes[i];
2941                                 if (pass != NULL && pass->wasdrawn) {
2942                                         GLuint64 time;
2943                                         glGetQueryObjectui64v(pass->timer_queries[pass->front_idx], GL_QUERY_RESULT, &time);
2944
2945                                         sprintf(pass_name, "   |--> %s", pass->name);
2946                                         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2947
2948                                         sprintf(time_to_txt, "%.2fms", time / 1000000.0);
2949                                         engine_time += time;
2950                                         tot_time += time;
2951
2952                                         draw_stat(&rect, 2, v++, time_to_txt, sizeof(time_to_txt));
2953
2954                                         pass->wasdrawn = false;
2955                                 }
2956                         }
2957                         /* engine total time */
2958                         sprintf(time_to_txt, "%.2fms", engine_time / 1000000.0);
2959                         draw_stat(&rect, 2, vsta, time_to_txt, sizeof(time_to_txt));
2960                         v++;
2961                 }
2962
2963                 sprintf(pass_name, "Total GPU time %.2fms (%.1f fps)", tot_time / 1000000.0, 1000000000.0 / tot_time);
2964                 draw_stat(&rect, 0, v++, pass_name, sizeof(pass_name));
2965                 v++;
2966         }
2967
2968         /* Memory Stats */
2969         unsigned int tex_mem = GPU_texture_memory_usage_get();
2970         unsigned int vbo_mem = GWN_vertbuf_get_memory_usage();
2971
2972         sprintf(pass_name, "GPU Memory");
2973         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2974         sprintf(pass_name, "%.2fMB", (float)(tex_mem + vbo_mem) / 1000000.0);
2975         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2976         sprintf(pass_name, "   |--> Textures");
2977         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2978         sprintf(pass_name, "%.2fMB", (float)tex_mem / 1000000.0);
2979         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2980         sprintf(pass_name, "   |--> Meshes");
2981         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2982         sprintf(pass_name, "%.2fMB", (float)vbo_mem / 1000000.0);
2983         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2984 }
2985
2986
2987 /* -------------------------------------------------------------------- */
2988
2989 /** \name Main Draw Loops (DRW_draw)
2990  * \{ */
2991
2992 /* Everything starts here.
2993  * This function takes care of calling all cache and rendering functions
2994  * for each relevant engine / mode engine. */
2995 void DRW_draw_view(const bContext *C)
2996 {
2997         struct Depsgraph *graph = CTX_data_depsgraph(C);
2998         ARegion *ar = CTX_wm_region(C);
2999         View3D *v3d = CTX_wm_view3d(C);
3000
3001         /* Reset before using it. */
3002         memset(&DST, 0x0, sizeof(DST));
3003         DRW_draw_render_loop_ex(graph, ar, v3d, C);
3004 }
3005
3006 /**
3007  * Used for both regular and off-screen drawing.
3008  * Need to reset DST before calling this function
3009  */
3010 void DRW_draw_render_loop_ex(
3011         struct Depsgraph *graph,
3012         ARegion *ar, View3D *v3d,
3013         const bContext *evil_C)
3014 {
3015         Scene *scene = DEG_get_scene(graph);
3016         SceneLayer *sl = DEG_get_scene_layer(graph);
3017         RegionView3D *rv3d = ar->regiondata;
3018
3019         DST.draw_ctx.evil_C = evil_C;
3020
3021         bool cache_is_dirty;
3022         DST.viewport = rv3d->viewport;
3023         v3d->zbuf = true;
3024
3025         /* Setup viewport */
3026         cache_is_dirty = GPU_viewport_cache_validate(DST.viewport, DRW_engines_get_hash());
3027
3028         DST.draw_ctx = (DRWContextState){
3029                 ar, rv3d, v3d, scene, sl, OBACT_NEW,
3030                 /* reuse if caller sets */
3031                 DST.draw_ctx.evil_C,
3032         };
3033
3034         DRW_viewport_var_init();
3035
3036         /* Get list of enabled engines */
3037         DRW_engines_enable(scene, sl);
3038
3039         /* Update ubos */
3040         DRW_globals_update();
3041
3042         /* Init engines */
3043         DRW_engines_init();
3044
3045         /* TODO : tag to refresh by the deps graph */
3046         /* ideally only refresh when objects are added/removed */
3047         /* or render properties / materials change */
3048         if (cache_is_dirty) {
3049                 DRW_engines_cache_init();
3050
3051                 DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_ALL);
3052                 {
3053                         DRW_engines_cache_populate(ob);
3054                         /* XXX find a better place for this. maybe Depsgraph? */
3055                         ob->deg_update_flag = 0;
3056                 }
3057                 DEG_OBJECT_ITER_END
3058
3059                 DRW_engines_cache_finish();
3060         }
3061
3062         /* Start Drawing */
3063         DRW_state_reset();
3064         DRW_engines_draw_background();
3065
3066         DRW_draw_callbacks_pre_scene();
3067         if (DST.draw_ctx.evil_C) {
3068                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_PRE_VIEW);
3069         }
3070
3071         DRW_engines_draw_scene();
3072
3073         DRW_draw_callbacks_post_scene();
3074         if (DST.draw_ctx.evil_C) {
3075                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_POST_VIEW);
3076         }
3077
3078         DRW_state_reset();
3079
3080         DRW_engines_draw_text();
3081
3082         if (DST.draw_ctx.evil_C) {
3083                 /* needed so manipulator isn't obscured */
3084                 glDisable(GL_DEPTH_TEST);
3085
3086                 DRW_draw_manipulator();
3087                 glEnable(GL_DEPTH_TEST);
3088
3089                 DRW_draw_region_info();
3090         }
3091
3092         if (G.debug_value > 20) {
3093                 DRW_debug_cpu_stats();
3094                 DRW_debug_gpu_stats();
3095         }
3096
3097         DRW_state_reset();
3098         DRW_engines_disable();
3099
3100 #ifdef DEBUG
3101         /* Avoid accidental reuse. */
3102         memset(&DST, 0xFF, sizeof(DST));
3103 #endif
3104 }
3105
3106 void DRW_draw_render_loop(
3107         struct Depsgraph *graph,
3108         ARegion *ar, View3D *v3d)
3109 {
3110         /* Reset before using it. */
3111         memset(&DST, 0x0, sizeof(DST));
3112         DRW_draw_render_loop_ex(graph, ar, v3d, NULL);
3113 }
3114
3115 void DRW_draw_render_loop_offscreen(
3116         struct Depsgraph *graph,
3117         ARegion *ar, View3D *v3d, GPUOffScreen *ofs)
3118 {
3119         RegionView3D *rv3d = ar->regiondata;
3120
3121         /* backup */
3122         void *backup_viewport = rv3d->viewport;
3123         {
3124                 /* backup (_never_ use rv3d->viewport) */
3125                 rv3d->viewport = GPU_viewport_create_from_offscreen(ofs);
3126         }
3127
3128         /* Reset before using it. */
3129         memset(&DST, 0x0, sizeof(DST));
3130         DST.options.is_image_render = true;
3131         DRW_draw_render_loop_ex(graph, ar, v3d, NULL);
3132
3133         /* restore */
3134         {
3135                 /* don't free data owned by 'ofs' */
3136                 GPU_viewport_clear_from_offscreen(rv3d->viewport);
3137                 GPU_viewport_free(rv3d->viewport);
3138                 MEM_freeN(rv3d->viewport);
3139
3140                 rv3d->viewport = backup_viewport;
3141         }
3142
3143         /* we need to re-bind (annoying!) */
3144         GPU_offscreen_bind(ofs, false);
3145 }
3146
3147 /**
3148  * object mode select-loop, see: ED_view3d_draw_select_loop (legacy drawing).
3149  */
3150 void DRW_draw_select_loop(
3151         struct Depsgraph *graph,
3152         ARegion *ar, View3D *v3d,
3153         bool UNUSED(use_obedit_skip), bool UNUSED(use_nearest), const rcti *rect)
3154 {
3155         Scene *scene = DEG_get_scene(graph);
3156         SceneLayer *sl = DEG_get_scene_layer(graph);
3157 #ifndef USE_GPU_SELECT
3158         UNUSED_VARS(vc, scene, sl, v3d, ar, rect);
3159 #else
3160         RegionView3D *rv3d = ar->regiondata;
3161
3162         /* Reset before using it. */
3163         memset(&DST, 0x0, sizeof(DST));
3164
3165         /* backup (_never_ use rv3d->viewport) */
3166         void *backup_viewport = rv3d->viewport;
3167         rv3d->viewport = NULL;
3168
3169         bool use_obedit = false;
3170         int obedit_mode = 0;
3171         if (scene->obedit && scene->obedit->type == OB_MBALL) {
3172                 use_obedit = true;
3173                 DRW_engines_cache_populate(scene->obedit);
3174                 obedit_mode = CTX_MODE_EDIT_METABALL;
3175         }
3176         else if ((scene->obedit && scene->obedit->type == OB_ARMATURE)) {
3177                 /* if not drawing sketch, draw bones */
3178                 // if (!BDR_drawSketchNames(vc))
3179                 {
3180                         use_obedit = true;
3181                         obedit_mode = CTX_MODE_EDIT_ARMATURE;
3182                 }
3183         }
3184
3185         struct GPUViewport *viewport = GPU_viewport_create();
3186         GPU_viewport_size_set(viewport, (const int[2]){BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)});
3187
3188         bool cache_is_dirty;
3189         DST.viewport = viewport;
3190         v3d->zbuf = true;
3191
3192         DST.options.is_select = true;
3193
3194         /* Get list of enabled engines */
3195         if (use_obedit) {
3196                 DRW_engines_enable_from_mode(obedit_mode);
3197         }
3198         else {
3199                 DRW_engines_enable_basic();
3200                 DRW_engines_enable_from_object_mode();
3201         }
3202
3203         /* Setup viewport */
3204         cache_is_dirty = true;
3205
3206         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
3207         DST.draw_ctx = (DRWContextState){
3208                 ar, rv3d, v3d, scene, sl, OBACT_NEW, (bContext *)NULL,
3209         };
3210
3211         DRW_viewport_var_init();
3212
3213         /* Update ubos */
3214         DRW_globals_update();
3215
3216         /* Init engines */
3217         DRW_engines_init();
3218
3219         /* TODO : tag to refresh by the deps graph */
3220         /* ideally only refresh when objects are added/removed */
3221         /* or render properties / materials change */
3222         if (cache_is_dirty) {
3223
3224                 DRW_engines_cache_init();
3225
3226                 if (use_obedit) {
3227                         DRW_engines_cache_populate(scene->obedit);
3228                 }
3229                 else {
3230                         DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_DUPLI)
3231                         {
3232                                 if ((ob->base_flag & BASE_SELECTABLED) != 0) {
3233                                         DRW_select_load_id(ob->select_color);
3234                                         DRW_engines_cache_populate(ob);
3235                                 }
3236                         }
3237                         DEG_OBJECT_ITER_END
3238                 }
3239
3240                 DRW_engines_cache_finish();
3241         }
3242
3243         /* Start Drawing */
3244         DRW_state_reset();
3245         DRW_draw_callbacks_pre_scene();
3246         DRW_engines_draw_scene();
3247         DRW_draw_callbacks_post_scene();
3248
3249         DRW_state_reset();
3250         DRW_engines_disable();
3251
3252 #ifdef DEBUG
3253         /* Avoid accidental reuse. */
3254         memset(&DST, 0xFF, sizeof(DST));
3255 #endif
3256
3257         /* Cleanup for selection state */
3258         GPU_viewport_free(viewport);
3259         MEM_freeN(viewport);
3260
3261         /* restore */
3262         rv3d->viewport = backup_viewport;
3263 #endif  /* USE_GPU_SELECT */
3264 }
3265
3266 /**
3267  * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
3268  */
3269 void DRW_draw_depth_loop(
3270         Depsgraph *graph,
3271         ARegion *ar, View3D *v3d)
3272 {
3273         Scene *scene = DEG_get_scene(graph);
3274         SceneLayer *sl = DEG_get_scene_layer(graph);
3275         RegionView3D *rv3d = ar->regiondata;
3276
3277         /* backup (_never_ use rv3d->viewport) */
3278         void *backup_viewport = rv3d->viewport;
3279         rv3d->viewport = NULL;
3280
3281         /* Reset before using it. */
3282         memset(&DST, 0x0, sizeof(DST));
3283
3284         struct GPUViewport *viewport = GPU_viewport_create();
3285         GPU_viewport_size_set(viewport, (const int[2]){ar->winx, ar->winy});
3286
3287         bool cache_is_dirty;
3288         DST.viewport = viewport;
3289         v3d->zbuf = true;
3290
3291         DST.options.is_depth = true;
3292
3293         /* Get list of enabled engines */
3294         {
3295                 DRW_engines_enable_basic();
3296                 DRW_engines_enable_from_object_mode();
3297         }
3298
3299         /* Setup viewport */
3300         cache_is_dirty = true;
3301
3302         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
3303         DST.draw_ctx = (DRWContextState){
3304                 ar, rv3d, v3d, scene, sl, OBACT_NEW, (bContext *)NULL,
3305         };
3306
3307         DRW_viewport_var_init();
3308
3309         /* Update ubos */
3310         DRW_globals_update();
3311
3312         /* Init engines */
3313         DRW_engines_init();
3314
3315         /* TODO : tag to refresh by the deps graph */
3316         /* ideally only refresh when objects are added/removed */
3317         /* or render properties / materials change */
3318         if (cache_is_dirty) {
3319
3320                 DRW_engines_cache_init();
3321
3322                 DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_ALL)
3323                 {
3324                         DRW_engines_cache_populate(ob);
3325                 }
3326                 DEG_OBJECT_ITER_END
3327
3328                 DRW_engines_cache_finish();
3329         }
3330
3331         /* Start Drawing */
3332         DRW_state_reset();
3333         DRW_draw_callbacks_pre_scene();
3334         DRW_engines_draw_scene();
3335         DRW_draw_callbacks_post_scene();
3336
3337         DRW_state_reset();
3338         DRW_engines_disable();
3339
3340 #ifdef DEBUG
3341         /* Avoid accidental reuse. */
3342         memset(&DST, 0xFF, sizeof(DST));
3343 #endif
3344
3345         /* Cleanup for selection state */
3346         GPU_viewport_free(viewport);
3347         MEM_freeN(viewport);
3348
3349         /* restore */
3350         rv3d->viewport = backup_viewport;
3351 }
3352
3353 /** \} */
3354
3355
3356 /* -------------------------------------------------------------------- */
3357
3358 /** \name Draw Manager State (DRW_state)
3359  * \{ */
3360
3361 void DRW_state_dfdy_factors_get(float dfdyfac[2])
3362 {
3363         GPU_get_dfdy_factors(dfdyfac);
3364 }
3365
3366 /**
3367  * When false, drawing doesn't output to a pixel buffer
3368  * eg: Occlusion queries, or when we have setup a context to draw in already.
3369  */
3370 bool DRW_state_is_fbo(void)
3371 {
3372         return (DST.default_framebuffer != NULL);
3373 }
3374
3375 /**
3376  * For when engines need to know if this is drawing for selection or not.
3377  */
3378 bool DRW_state_is_select(void)
3379 {
3380         return DST.options.is_select;
3381 }
3382
3383 bool DRW_state_is_depth(void)
3384 {
3385         return DST.options.is_depth;
3386 }
3387
3388 /**
3389  * Whether we are rendering for an image
3390  */
3391 bool DRW_state_is_image_render(void)
3392 {
3393         return DST.options.is_image_render;
3394 }
3395
3396 /**
3397  * Whether we are rendering only the render engine,
3398  * or if we should also render the mode engines.
3399  */
3400 bool DRW_state_is_scene_render(void)
3401 {
3402         BLI_assert(DST.options.is_scene_render ?
3403                    DST.options.is_image_render : true);
3404         return DST.options.is_scene_render;
3405 }
3406
3407 /**
3408  * Should text draw in this mode?
3409  */
3410 bool DRW_state_show_text(void)
3411 {
3412         return (DST.options.is_select) == 0 &&
3413                (DST.options.is_depth) == 0 &&
3414                (DST.options.is_scene_render) == 0;
3415 }
3416
3417 /**
3418  * Should draw support elements
3419  * Objects center, selection outline, probe data, ...
3420  */