Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw_legacy.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_draw_legacy.c
28  *  \ingroup spview3d
29  */
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <math.h>
34
35 #include "DNA_armature_types.h"
36 #include "DNA_camera_types.h"
37 #include "DNA_customdata_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_world_types.h"
45 #include "DNA_brush_types.h"
46
47 #include "MEM_guardedalloc.h"
48
49 #include "BLI_blenlib.h"
50 #include "BLI_math.h"
51 #include "BLI_jitter.h"
52 #include "BLI_utildefines.h"
53 #include "BLI_endian_switch.h"
54 #include "BLI_threads.h"
55
56 #include "BKE_anim.h"
57 #include "BKE_camera.h"
58 #include "BKE_context.h"
59 #include "BKE_customdata.h"
60 #include "BKE_DerivedMesh.h"
61 #include "BKE_image.h"
62 #include "BKE_key.h"
63 #include "BKE_layer.h"
64 #include "BKE_main.h"
65 #include "BKE_object.h"
66 #include "BKE_global.h"
67 #include "BKE_paint.h"
68 #include "BKE_scene.h"
69 #include "BKE_screen.h"
70 #include "BKE_unit.h"
71 #include "BKE_movieclip.h"
72
73 #include "DEG_depsgraph.h"
74
75 #include "RE_engine.h"
76
77 #include "IMB_imbuf_types.h"
78 #include "IMB_imbuf.h"
79 #include "IMB_colormanagement.h"
80
81 #include "BIF_glutil.h"
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "BLF_api.h"
87 #include "BLT_translation.h"
88
89 #include "ED_armature.h"
90 #include "ED_keyframing.h"
91 #include "ED_gpencil.h"
92 #include "ED_screen.h"
93 #include "ED_space_api.h"
94 #include "ED_screen_types.h"
95 #include "ED_transform.h"
96
97 #include "UI_interface.h"
98 #include "UI_interface_icons.h"
99 #include "UI_resources.h"
100
101 #include "GPU_draw.h"
102 #include "GPU_framebuffer.h"
103 #include "GPU_lamp.h"
104 #include "GPU_material.h"
105 #include "GPU_compositing.h"
106 #include "GPU_extensions.h"
107 #include "GPU_immediate.h"
108 #include "GPU_immediate_util.h"
109 #include "GPU_select.h"
110 #include "GPU_matrix.h"
111
112 #include "RE_engine.h"
113
114 #include "DRW_engine.h"
115
116 #include "view3d_intern.h"  /* own include */
117
118 /* ********* custom clipping *********** */
119
120 static void view3d_draw_clipping(RegionView3D *rv3d)
121 {
122         BoundBox *bb = rv3d->clipbb;
123
124         if (bb) {
125                 const unsigned int clipping_index[6][4] = {
126                         {0, 1, 2, 3},
127                         {0, 4, 5, 1},
128                         {4, 7, 6, 5},
129                         {7, 3, 2, 6},
130                         {1, 5, 6, 2},
131                         {7, 4, 0, 3}
132                 };
133
134                 /* fill in zero alpha for rendering & re-projection [#31530] */
135                 unsigned char col[4];
136                 UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
137                 glColor4ubv(col);
138
139                 glEnable(GL_BLEND);
140                 glEnableClientState(GL_VERTEX_ARRAY);
141                 glVertexPointer(3, GL_FLOAT, 0, bb->vec);
142                 glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
143                 glDisableClientState(GL_VERTEX_ARRAY);
144                 glDisable(GL_BLEND);
145         }
146 }
147
148 void ED_view3d_clipping_set(RegionView3D *rv3d)
149 {
150         double plane[4];
151         const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
152
153         for (unsigned a = 0; a < tot; a++) {
154                 copy_v4db_v4fl(plane, rv3d->clip[a]);
155                 glClipPlane(GL_CLIP_PLANE0 + a, plane);
156                 glEnable(GL_CLIP_PLANE0 + a);
157         }
158 }
159
160 /* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
161 void ED_view3d_clipping_disable(void)
162 {
163         for (unsigned a = 0; a < 6; a++) {
164                 glDisable(GL_CLIP_PLANE0 + a);
165         }
166 }
167 void ED_view3d_clipping_enable(void)
168 {
169         for (unsigned a = 0; a < 6; a++) {
170                 glEnable(GL_CLIP_PLANE0 + a);
171         }
172 }
173
174 static bool view3d_clipping_test(const float co[3], const float clip[6][4])
175 {
176         if (plane_point_side_v3(clip[0], co) > 0.0f)
177                 if (plane_point_side_v3(clip[1], co) > 0.0f)
178                         if (plane_point_side_v3(clip[2], co) > 0.0f)
179                                 if (plane_point_side_v3(clip[3], co) > 0.0f)
180                                         return false;
181
182         return true;
183 }
184
185 /* for 'local' ED_view3d_clipping_local must run first
186  * then all comparisons can be done in localspace */
187 bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
188 {
189         return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
190 }
191
192 /* ********* end custom clipping *********** */
193
194 static void draw_view_icon(RegionView3D *rv3d, rcti *rect)
195 {
196         BIFIconID icon;
197         
198         if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
199                 icon = ICON_AXIS_TOP;
200         else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK))
201                 icon = ICON_AXIS_FRONT;
202         else if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
203                 icon = ICON_AXIS_SIDE;
204         else return;
205         
206         glEnable(GL_BLEND);
207         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
208         
209         UI_icon_draw(5.0 + rect->xmin, 5.0 + rect->ymin, icon);
210         
211         glDisable(GL_BLEND);
212 }
213
214 /* *********************** backdraw for selection *************** */
215
216 static void backdrawview3d(const struct EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, wmWindow *win, ARegion *ar, View3D *v3d)
217 {
218         RegionView3D *rv3d = ar->regiondata;
219         struct Base *base = sl->basact;
220         int multisample_enabled;
221
222         BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
223
224         if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
225                      BKE_paint_select_face_test(base->object)))
226         {
227                 /* do nothing */
228         }
229         /* texture paint mode sampling */
230         else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
231                  (v3d->drawtype > OB_WIRE))
232         {
233                 /* do nothing */
234         }
235         else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
236                  V3D_IS_ZBUF(v3d))
237         {
238                 /* do nothing */
239         }
240         else if (scene->obedit &&
241                  V3D_IS_ZBUF(v3d))
242         {
243                 /* do nothing */
244         }
245         else {
246                 v3d->flag &= ~V3D_INVALID_BACKBUF;
247                 return;
248         }
249
250         if (!(v3d->flag & V3D_INVALID_BACKBUF))
251                 return;
252
253 #if 0
254         if (test) {
255                 if (qtest()) {
256                         addafterqueue(ar->win, BACKBUFDRAW, 1);
257                         return;
258                 }
259         }
260 #endif
261
262         if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
263         
264         /* dithering and AA break color coding, so disable */
265         glDisable(GL_DITHER);
266
267         multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
268         if (multisample_enabled)
269                 glDisable(GL_MULTISAMPLE);
270
271         if (win->multisamples != USER_MULTISAMPLE_NONE) {
272                 /* for multisample we use an offscreen FBO. multisample drawing can fail
273                  * with color coded selection drawing, and reading back depths from such
274                  * a buffer can also cause a few seconds freeze on OS X / NVidia. */
275                 int w = BLI_rcti_size_x(&ar->winrct);
276                 int h = BLI_rcti_size_y(&ar->winrct);
277                 char error[256];
278
279                 if (rv3d->gpuoffscreen) {
280                         if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
281                             GPU_offscreen_height(rv3d->gpuoffscreen) != h)
282                         {
283                                 GPU_offscreen_free(rv3d->gpuoffscreen);
284                                 rv3d->gpuoffscreen = NULL;
285                         }
286                 }
287
288                 if (!rv3d->gpuoffscreen) {
289                         rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
290
291                         if (!rv3d->gpuoffscreen)
292                                 fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
293                 }
294         }
295
296         if (rv3d->gpuoffscreen)
297                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
298         else
299                 glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
300
301         glClearColor(0.0, 0.0, 0.0, 0.0);
302         if (v3d->zbuf) {
303                 glEnable(GL_DEPTH_TEST);
304                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
305         }
306         else {
307                 glClear(GL_COLOR_BUFFER_BIT);
308                 glDisable(GL_DEPTH_TEST);
309         }
310         
311         if (rv3d->rflag & RV3D_CLIPPING)
312                 ED_view3d_clipping_set(rv3d);
313         
314         G.f |= G_BACKBUFSEL;
315         
316         if (base && ((base->flag & BASE_VISIBLED) != 0))
317                 draw_object_backbufsel(eval_ctx, scene, v3d, rv3d, base->object);
318         
319         if (rv3d->gpuoffscreen)
320                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
321         else
322                 ar->swap = 0; /* mark invalid backbuf for wm draw */
323
324         v3d->flag &= ~V3D_INVALID_BACKBUF;
325
326         G.f &= ~G_BACKBUFSEL;
327         v3d->zbuf = false;
328         glDisable(GL_DEPTH_TEST);
329         glEnable(GL_DITHER);
330         if (multisample_enabled)
331                 glEnable(GL_MULTISAMPLE);
332
333         if (rv3d->rflag & RV3D_CLIPPING)
334                 ED_view3d_clipping_disable();
335 }
336
337 void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
338 {
339         RegionView3D *rv3d = ar->regiondata;
340
341         if (rv3d->gpuoffscreen) {
342                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
343                 glReadBuffer(GL_COLOR_ATTACHMENT0);
344                 glReadPixels(x, y, w, h, format, type, data);
345                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
346         }
347         else {
348                 glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
349         }
350 }
351
352 /* XXX depth reading exception, for code not using gpu offscreen */
353 static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
354 {
355         glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
356 }
357
358 void ED_view3d_backbuf_validate(const struct EvaluationContext *eval_ctx, ViewContext *vc)
359 {
360         if (vc->v3d->flag & V3D_INVALID_BACKBUF) {
361                 backdrawview3d(eval_ctx, vc->scene, vc->scene_layer, vc->win, vc->ar, vc->v3d);
362         }
363 }
364
365 /**
366  * allow for small values [0.5 - 2.5],
367  * and large values, FLT_MAX by clamping by the area size
368  */
369 int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
370 {
371         return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
372 }
373
374 /* samples a single pixel (copied from vpaint) */
375 unsigned int ED_view3d_backbuf_sample(
376         const EvaluationContext *eval_ctx, ViewContext *vc, int x, int y)
377 {
378         if (x >= vc->ar->winx || y >= vc->ar->winy) {
379                 return 0;
380         }
381
382         ED_view3d_backbuf_validate(eval_ctx, vc);
383
384         unsigned int col;
385         view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
386         glReadBuffer(GL_BACK);
387
388         if (ENDIAN_ORDER == B_ENDIAN) {
389                 BLI_endian_switch_uint32(&col);
390         }
391
392         return GPU_select_to_index(col);
393 }
394
395 /* reads full rect, converts indices */
396 ImBuf *ED_view3d_backbuf_read(
397         const EvaluationContext *eval_ctx, ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
398 {
399         /* clip */
400         const rcti clip = {
401             max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
402             max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
403         const int size_clip[2] = {
404             BLI_rcti_size_x(&clip) + 1,
405             BLI_rcti_size_y(&clip) + 1};
406
407         if (UNLIKELY((clip.xmin > clip.xmax) ||
408                      (clip.ymin > clip.ymax)))
409         {
410                 return NULL;
411         }
412
413         ImBuf *ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
414
415         ED_view3d_backbuf_validate(eval_ctx, vc);
416
417         view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
418
419         glReadBuffer(GL_BACK);
420
421         if (ENDIAN_ORDER == B_ENDIAN) {
422                 IMB_convert_rgba_to_abgr(ibuf_clip);
423         }
424
425         GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
426         
427         if ((clip.xmin == xmin) &&
428             (clip.xmax == xmax) &&
429             (clip.ymin == ymin) &&
430             (clip.ymax == ymax))
431         {
432                 return ibuf_clip;
433         }
434         else {
435                 /* put clipped result into a non-clipped buffer */
436                 const int size[2] = {
437                     (xmax - xmin + 1),
438                     (ymax - ymin + 1)};
439
440                 ImBuf *ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
441
442                 IMB_rectcpy(
443                         ibuf_full, ibuf_clip,
444                         clip.xmin - xmin, clip.ymin - ymin,
445                         0, 0,
446                         size_clip[0], size_clip[1]);
447                 IMB_freeImBuf(ibuf_clip);
448                 return ibuf_full;
449         }
450 }
451
452 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
453 unsigned int ED_view3d_backbuf_sample_rect(
454         const EvaluationContext *eval_ctx, ViewContext *vc, const int mval[2], int size,
455         unsigned int min, unsigned int max, float *r_dist)
456 {
457         int dirvec[4][2];
458
459         const int amount = (size - 1) / 2;
460
461         const int minx = mval[0] - (amount + 1);
462         const int miny = mval[1] - (amount + 1);
463         ImBuf *buf = ED_view3d_backbuf_read(eval_ctx, vc, minx, miny, minx + size - 1, miny + size - 1);
464         if (!buf) return 0;
465
466         unsigned index = 0;
467         int rc = 0;
468         
469         dirvec[0][0] = 1; dirvec[0][1] = 0;
470         dirvec[1][0] = 0; dirvec[1][1] = -size;
471         dirvec[2][0] = -1; dirvec[2][1] = 0;
472         dirvec[3][0] = 0; dirvec[3][1] = size;
473         
474         const unsigned *bufmin = buf->rect;
475         const unsigned *tbuf = buf->rect;
476         const unsigned *bufmax = buf->rect + size * size;
477         tbuf += amount * size + amount;
478         
479         for (int nr = 1; nr <= size; nr++) {
480                 for (int a = 0; a < 2; a++) {
481                         for (int b = 0; b < nr; b++) {
482                                 if (*tbuf && *tbuf >= min && *tbuf < max) {
483                                         /* we got a hit */
484
485                                         /* get x,y pixel coords from the offset
486                                          * (manhatten distance in keeping with other screen-based selection) */
487                                         *r_dist = (float)(
488                                                 abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
489                                                 abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
490
491                                         /* indices start at 1 here */
492                                         index = (*tbuf - min) + 1;
493                                         goto exit;
494                                 }
495                                 
496                                 tbuf += (dirvec[rc][0] + dirvec[rc][1]);
497                                 
498                                 if (tbuf < bufmin || tbuf >= bufmax) {
499                                         goto exit;
500                                 }
501                         }
502                         rc++;
503                         rc &= 3;
504                 }
505         }
506
507 exit:
508         IMB_freeImBuf(buf);
509         return index;
510 }
511
512
513 /* ************************************************************* */
514
515 static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
516 {
517         if (BKE_image_is_stereo(ima)) {
518                 iuser->flag |= IMA_SHOW_STEREO;
519
520                 if ((scene->r.scemode & R_MULTIVIEW) == 0) {
521                         iuser->multiview_eye = STEREO_LEFT_ID;
522                 }
523                 else if (v3d->stereo3d_camera != STEREO_3D_ID) {
524                         /* show only left or right camera */
525                         iuser->multiview_eye = v3d->stereo3d_camera;
526                 }
527
528                 BKE_image_multiview_index(ima, iuser);
529         }
530         else {
531                 iuser->flag &= ~IMA_SHOW_STEREO;
532         }
533 }
534
535 static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
536                               const bool do_foreground, const bool do_camera_frame)
537 {
538         RegionView3D *rv3d = ar->regiondata;
539         int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
540
541         for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
542                 bgpic->iuser.scene = scene;  /* Needed for render results. */
543
544                 if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
545                         continue;
546
547                 if ((bgpic->view == 0) || /* zero for any */
548                     (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
549                     (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
550                 {
551                         float image_aspect[2];
552                         float x1, y1, x2, y2, centx, centy;
553
554                         void *lock;
555
556                         Image *ima = NULL;
557
558                         /* disable individual images */
559                         if ((bgpic->flag & V3D_BGPIC_DISABLED))
560                                 continue;
561
562                         ImBuf *ibuf = NULL;
563                         ImBuf *freeibuf = NULL;
564                         ImBuf *releaseibuf = NULL;
565                         if (bgpic->source == V3D_BGPIC_IMAGE) {
566                                 ima = bgpic->ima;
567                                 if (ima == NULL)
568                                         continue;
569                                 BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
570                                 if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
571                                         ibuf = NULL; /* frame is out of range, dont show */
572                                 }
573                                 else {
574                                         view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
575                                         ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
576                                         releaseibuf = ibuf;
577                                 }
578
579                                 image_aspect[0] = ima->aspx;
580                                 image_aspect[1] = ima->aspy;
581                         }
582                         else if (bgpic->source == V3D_BGPIC_MOVIE) {
583                                 /* TODO: skip drawing when out of frame range (as image sequences do above) */
584                                 MovieClip *clip = NULL;
585
586                                 if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
587                                         if (scene->camera)
588                                                 clip = BKE_object_movieclip_get(scene, scene->camera, true);
589                                 }
590                                 else {
591                                         clip = bgpic->clip;
592                                 }
593
594                                 if (clip == NULL)
595                                         continue;
596
597                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
598                                 ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
599
600                                 image_aspect[0] = clip->aspx;
601                                 image_aspect[1] = clip->aspy;
602
603                                 /* working with ibuf from image and clip has got different workflow now.
604                                  * ibuf acquired from clip is referenced by cache system and should
605                                  * be dereferenced after usage. */
606                                 freeibuf = ibuf;
607                         }
608                         else {
609                                 /* perhaps when loading future files... */
610                                 BLI_assert(0);
611                                 copy_v2_fl(image_aspect, 1.0f);
612                         }
613
614                         if (ibuf == NULL)
615                                 continue;
616
617                         if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
618                                 if (freeibuf)
619                                         IMB_freeImBuf(freeibuf);
620                                 if (releaseibuf)
621                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
622
623                                 continue;
624                         }
625
626                         if (ibuf->rect == NULL)
627                                 IMB_rect_from_float(ibuf);
628
629                         if (rv3d->persp == RV3D_CAMOB) {
630
631                                 if (do_camera_frame) {
632                                         rctf vb;
633                                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
634                                         x1 = vb.xmin;
635                                         y1 = vb.ymin;
636                                         x2 = vb.xmax;
637                                         y2 = vb.ymax;
638                                 }
639                                 else {
640                                         x1 = ar->winrct.xmin;
641                                         y1 = ar->winrct.ymin;
642                                         x2 = ar->winrct.xmax;
643                                         y2 = ar->winrct.ymax;
644                                 }
645
646                                 /* apply offset last - camera offset is different to offset in blender units */
647                                 /* so this has some sane way of working - this matches camera's shift _exactly_ */
648                                 {
649                                         const float max_dim = max_ff(x2 - x1, y2 - y1);
650                                         const float xof_scale = bgpic->xof * max_dim;
651                                         const float yof_scale = bgpic->yof * max_dim;
652
653                                         x1 += xof_scale;
654                                         y1 += yof_scale;
655                                         x2 += xof_scale;
656                                         y2 += yof_scale;
657                                 }
658
659                                 centx = (x1 + x2) * 0.5f;
660                                 centy = (y1 + y2) * 0.5f;
661
662                                 /* aspect correction */
663                                 if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
664                                         /* apply aspect from clip */
665                                         const float w_src = ibuf->x * image_aspect[0];
666                                         const float h_src = ibuf->y * image_aspect[1];
667
668                                         /* destination aspect is already applied from the camera frame */
669                                         const float w_dst = x1 - x2;
670                                         const float h_dst = y1 - y2;
671
672                                         const float asp_src = w_src / h_src;
673                                         const float asp_dst = w_dst / h_dst;
674
675                                         if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
676                                                 if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
677                                                         /* fit X */
678                                                         const float div = asp_src / asp_dst;
679                                                         x1 = ((x1 - centx) * div) + centx;
680                                                         x2 = ((x2 - centx) * div) + centx;
681                                                 }
682                                                 else {
683                                                         /* fit Y */
684                                                         const float div = asp_dst / asp_src;
685                                                         y1 = ((y1 - centy) * div) + centy;
686                                                         y2 = ((y2 - centy) * div) + centy;
687                                                 }
688                                         }
689                                 }
690                         }
691                         else {
692                                 float tvec[3];
693                                 float sco[2];
694                                 const float mval_f[2] = {1.0f, 0.0f};
695                                 const float co_zero[3] = {0};
696
697                                 /* calc window coord */
698                                 float zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
699                                 ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
700                                 float fac = 1.0f / max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
701                                 float asp = (float)ibuf->y / (float)ibuf->x;
702
703                                 zero_v3(tvec);
704                                 ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
705
706                                 x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
707                                 y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
708                                 x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
709                                 y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
710
711                                 centx = (x1 + x2) / 2.0f;
712                                 centy = (y1 + y2) / 2.0f;
713                         }
714
715                         /* complete clip? */
716                         rctf clip_rect;
717                         BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
718                         if (bgpic->rotation) {
719                                 BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
720                         }
721
722                         if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
723                                 if (freeibuf)
724                                         IMB_freeImBuf(freeibuf);
725                                 if (releaseibuf)
726                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
727
728                                 continue;
729                         }
730
731                         float zoomx = (x2 - x1) / ibuf->x;
732                         float zoomy = (y2 - y1) / ibuf->y;
733
734                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
735                         if (zoomx < 1.0f || zoomy < 1.0f) {
736                                 float tzoom = min_ff(zoomx, zoomy);
737                                 int mip = 0;
738
739                                 if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
740                                         IMB_remakemipmap(ibuf, 0);
741                                         ibuf->userflags &= ~IB_MIPMAP_INVALID;
742                                 }
743                                 else if (ibuf->mipmap[0] == NULL)
744                                         IMB_makemipmap(ibuf, 0);
745
746                                 while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
747                                         tzoom *= 2.0f;
748                                         zoomx *= 2.0f;
749                                         zoomy *= 2.0f;
750                                         mip++;
751                                 }
752                                 if (mip > 0)
753                                         ibuf = ibuf->mipmap[mip - 1];
754                         }
755
756                         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
757                         glDepthMask(GL_FALSE);
758
759                         glEnable(GL_BLEND);
760                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
761
762                         gpuPushProjectionMatrix();
763                         gpuPushMatrix();
764                         ED_region_pixelspace(ar);
765
766                         gpuTranslate2f(centx, centy);
767                         gpuRotate2D(RAD2DEGF(-bgpic->rotation));
768
769                         if (bgpic->flag & V3D_BGPIC_FLIP_X) {
770                                 zoomx *= -1.0f;
771                                 x1 = x2;
772                         }
773                         if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
774                                 zoomy *= -1.0f;
775                                 y1 = y2;
776                         }
777
778                         float col[4] = {1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend};
779                         IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
780                         immDrawPixelsTex(&state, x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect,
781                                          zoomx, zoomy, col);
782
783                         gpuPopProjectionMatrix();
784                         gpuPopMatrix();
785
786                         glDisable(GL_BLEND);
787
788                         glDepthMask(GL_TRUE);
789                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
790
791                         if (freeibuf)
792                                 IMB_freeImBuf(freeibuf);
793                         if (releaseibuf)
794                                 BKE_image_release_ibuf(ima, releaseibuf, lock);
795                 }
796         }
797 }
798
799 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
800                                    const bool do_foreground, const bool do_camera_frame)
801 {
802         RegionView3D *rv3d = ar->regiondata;
803
804         if ((v3d->flag & V3D_DISPBGPICS) == 0)
805                 return;
806
807         /* disabled - mango request, since footage /w only render is quite useful
808          * and this option is easy to disable all background images at once */
809 #if 0
810         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
811                 return;
812 #endif
813
814         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
815                 if (rv3d->persp == RV3D_CAMOB) {
816                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
817                 }
818         }
819         else {
820                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
821         }
822 }
823
824 /* ****************** View3d afterdraw *************** */
825
826 typedef struct View3DAfter {
827         struct View3DAfter *next, *prev;
828         struct BaseLegacy *base;
829         short dflag;
830 } View3DAfter;
831
832 /* temp storage of Objects that need to be drawn as last */
833 void ED_view3d_after_add(ListBase *lb, BaseLegacy *base, const short dflag)
834 {
835         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
836         BLI_assert((base->flag_legacy & OB_FROMDUPLI) == 0);
837         BLI_addtail(lb, v3da);
838         v3da->base = base;
839         v3da->dflag = dflag;
840 }
841
842 /* disables write in zbuffer and draws it over */
843 static void view3d_draw_transp(
844         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d)
845 {
846         View3DAfter *v3da;
847         
848         glDepthMask(GL_FALSE);
849         v3d->transp = true;
850         
851         while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
852                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
853                 MEM_freeN(v3da);
854         }
855         v3d->transp = false;
856         
857         glDepthMask(GL_TRUE);
858         
859 }
860
861 /* clears zbuffer and draws it over */
862 static void view3d_draw_xray(
863         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
864 {
865         if (*clear && v3d->zbuf) {
866                 glClear(GL_DEPTH_BUFFER_BIT);
867                 *clear = false;
868         }
869
870         v3d->xray = true;
871         View3DAfter *v3da;
872         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
873                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
874                 MEM_freeN(v3da);
875         }
876         v3d->xray = false;
877 }
878
879
880 /* clears zbuffer and draws it over */
881 static void view3d_draw_xraytransp(
882         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, const bool clear)
883 {
884         if (clear && v3d->zbuf)
885                 glClear(GL_DEPTH_BUFFER_BIT);
886
887         v3d->xray = true;
888         v3d->transp = true;
889         
890         glDepthMask(GL_FALSE);
891
892         View3DAfter *v3da;
893         while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
894                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
895                 MEM_freeN(v3da);
896         }
897
898         v3d->transp = false;
899         v3d->xray = false;
900
901         glDepthMask(GL_TRUE);
902 }
903
904 /* clears zbuffer and draws it over,
905  * note that in the select version we don't care about transparent flag as with regular drawing */
906 static void view3d_draw_xray_select(
907         const struct EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, bool *clear)
908 {
909         /* Not ideal, but we need to read from the previous depths before clearing
910          * otherwise we could have a function to load the depths after drawing.
911          *
912          * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
913          */
914         if (U.gpu_select_pick_deph) {
915                 GPU_select_load_id(-1);
916         }
917
918         View3DAfter *v3da;
919         if (*clear && v3d->zbuf) {
920                 glClear(GL_DEPTH_BUFFER_BIT);
921                 *clear = false;
922         }
923
924         v3d->xray = true;
925         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
926                 if (GPU_select_load_id(v3da->base->object->select_color)) {
927                         draw_object_select(eval_ctx, scene, sl, ar, v3d, v3da->base, v3da->dflag);
928                 }
929                 MEM_freeN(v3da);
930         }
931         v3d->xray = false;
932 }
933
934 /* *********************** */
935
936 /*
937  * In most cases call draw_dupli_objects,
938  * draw_dupli_objects_color was added because when drawing set dupli's
939  * we need to force the color
940  */
941
942 #if 0
943 int dupli_ob_sort(void *arg1, void *arg2)
944 {
945         void *p1 = ((DupliObject *)arg1)->ob;
946         void *p2 = ((DupliObject *)arg2)->ob;
947         int val = 0;
948         if (p1 < p2) val = -1;
949         else if (p1 > p2) val = 1;
950         return val;
951 }
952 #endif
953
954
955 static DupliObject *dupli_step(DupliObject *dob)
956 {
957         while (dob && dob->no_draw)
958                 dob = dob->next;
959         return dob;
960 }
961
962 static void draw_dupli_objects_color(
963         const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base,
964         const short dflag, const int color)
965 {
966         RegionView3D *rv3d = ar->regiondata;
967         ListBase *lb;
968         LodLevel *savedlod;
969         Base tbase = {NULL};
970         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
971         unsigned char color_rgb[3];
972         const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
973         short transflag;
974         char dt;
975         short dtx;
976         DupliApplyData *apply_data;
977
978         if ((base->flag & BASE_VISIBLED) == 0) return;
979         if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
980
981         if (dflag & DRAW_CONSTCOLOR) {
982                 BLI_assert(color == TH_UNDEFINED);
983         }
984         else {
985                 UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
986         }
987
988         tbase.flag_legacy = OB_FROMDUPLI | base->flag_legacy;
989         tbase.flag = base->flag;
990         lb = object_duplilist(eval_ctx, scene, base->object);
991         // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
992
993         apply_data = duplilist_apply(eval_ctx, base->object, scene, lb);
994
995         DupliObject *dob_next = NULL;
996         DupliObject *dob = dupli_step(lb->first);
997         if (dob) dob_next = dupli_step(dob->next);
998
999         for (; dob; dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1000                 bool testbb = false;
1001
1002                 tbase.object = dob->ob;
1003
1004                 /* Make sure lod is updated from dupli's position */
1005                 savedlod = dob->ob->currentlod;
1006
1007 #ifdef WITH_GAMEENGINE
1008                 if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1009                         BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
1010                 }
1011 #endif
1012
1013                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
1014                  * to allow e.g. boundbox box objects in groups for LOD */
1015                 dt = tbase.object->dt;
1016                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1017
1018                 /* inherit draw extra, but not if a boundbox under the assumption that this
1019                  * is intended to speed up drawing, and drawing extra (especially wire) can
1020                  * slow it down too much */
1021                 dtx = tbase.object->dtx;
1022                 if (tbase.object->dt != OB_BOUNDBOX)
1023                         tbase.object->dtx = base->object->dtx;
1024
1025                 /* negative scale flag has to propagate */
1026                 transflag = tbase.object->transflag;
1027
1028                 if (is_negative_m4(dob->mat))
1029                         tbase.object->transflag |= OB_NEG_SCALE;
1030                 else
1031                         tbase.object->transflag &= ~OB_NEG_SCALE;
1032                 
1033                 /* should move outside the loop but possible color is set in draw_object still */
1034                 if ((dflag & DRAW_CONSTCOLOR) == 0) {
1035                         glColor3ubv(color_rgb);
1036                 }
1037                 
1038                 if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
1039                         bb = *bb_tmp; /* must make a copy  */
1040                         testbb = true;
1041                 }
1042
1043                 if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
1044                         copy_m4_m4(dob->ob->obmat, dob->mat);
1045                         GPU_begin_dupli_object(dob);
1046                         draw_object(eval_ctx, scene, sl, ar, v3d, &tbase, dflag_dupli);
1047                         GPU_end_dupli_object();
1048                 }
1049                 
1050                 tbase.object->dt = dt;
1051                 tbase.object->dtx = dtx;
1052                 tbase.object->transflag = transflag;
1053                 tbase.object->currentlod = savedlod;
1054         }
1055
1056         if (apply_data) {
1057                 duplilist_restore(lb, apply_data);
1058                 duplilist_free_apply_data(apply_data);
1059         }
1060
1061         free_object_duplilist(lb);
1062 }
1063
1064 void draw_dupli_objects(const EvaluationContext *eval_ctx, Scene *scene, SceneLayer *sl, ARegion *ar, View3D *v3d, BaseLegacy *base)
1065 {
1066         /* define the color here so draw_dupli_objects_color can be called
1067          * from the set loop */
1068         
1069         int color = (base->flag & BASE_SELECTED) ? TH_SELECT : TH_WIRE;
1070         /* debug */
1071         if (base->object->dup_group && base->object->dup_group->id.us < 1)
1072                 color = TH_REDALERT;
1073         
1074         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, 0, color);
1075 }
1076
1077 /* XXX warning, not using gpu offscreen here */
1078 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1079 {
1080         /* clamp rect by region */
1081         rcti r = {
1082                 .xmin = 0,
1083                 .xmax = ar->winx - 1,
1084                 .ymin = 0,
1085                 .ymax = ar->winy - 1
1086         };
1087
1088         /* Constrain rect to depth bounds */
1089         BLI_rcti_isect(&r, rect, rect);
1090
1091         /* assign values to compare with the ViewDepths */
1092         int x = rect->xmin;
1093         int y = rect->ymin;
1094
1095         int w = BLI_rcti_size_x(rect);
1096         int h = BLI_rcti_size_y(rect);
1097
1098         if (w <= 0 || h <= 0) {
1099                 if (d->depths)
1100                         MEM_freeN(d->depths);
1101                 d->depths = NULL;
1102
1103                 d->damaged = false;
1104         }
1105         else if (d->w != w ||
1106                  d->h != h ||
1107                  d->x != x ||
1108                  d->y != y ||
1109                  d->depths == NULL
1110                  )
1111         {
1112                 d->x = x;
1113                 d->y = y;
1114                 d->w = w;
1115                 d->h = h;
1116
1117                 if (d->depths)
1118                         MEM_freeN(d->depths);
1119
1120                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
1121                 
1122                 d->damaged = true;
1123         }
1124
1125         if (d->damaged) {
1126                 /* XXX using special function here, it doesn't use the gpu offscreen system */
1127                 view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1128                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1129                 d->damaged = false;
1130         }
1131 }
1132
1133 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1134 void ED_view3d_depth_update(ARegion *ar)
1135 {
1136         RegionView3D *rv3d = ar->regiondata;
1137         
1138         /* Create storage for, and, if necessary, copy depth buffer */
1139         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
1140         if (rv3d->depths) {
1141                 ViewDepths *d = rv3d->depths;
1142                 if (d->w != ar->winx ||
1143                     d->h != ar->winy ||
1144                     !d->depths)
1145                 {
1146                         d->w = ar->winx;
1147                         d->h = ar->winy;
1148                         if (d->depths)
1149                                 MEM_freeN(d->depths);
1150                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
1151                         d->damaged = true;
1152                 }
1153                 
1154                 if (d->damaged) {
1155                         view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
1156                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
1157                         
1158                         d->damaged = false;
1159                 }
1160         }
1161 }
1162
1163 /* utility function to find the closest Z value, use for autodepth */
1164 float view3d_depth_near(ViewDepths *d)
1165 {
1166         /* convert to float for comparisons */
1167         const float near = (float)d->depth_range[0];
1168         const float far_real = (float)d->depth_range[1];
1169         float far = far_real;
1170
1171         const float *depths = d->depths;
1172         float depth = FLT_MAX;
1173         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
1174
1175         /* far is both the starting 'far' value
1176          * and the closest value found. */
1177         while (i--) {
1178                 depth = *depths++;
1179                 if ((depth < far) && (depth > near)) {
1180                         far = depth;
1181                 }
1182         }
1183
1184         return far == far_real ? FLT_MAX : far;
1185 }
1186
1187 void ED_view3d_draw_depth_gpencil(
1188         const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d)
1189 {
1190         bool zbuf = v3d->zbuf;
1191
1192         /* Setup view matrix. */
1193         ED_view3d_draw_setup_view(NULL, eval_ctx, scene, ar, v3d, NULL, NULL, NULL);
1194
1195         glClear(GL_DEPTH_BUFFER_BIT);
1196
1197         v3d->zbuf = true;
1198         glEnable(GL_DEPTH_TEST);
1199
1200         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1201                 ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
1202         }
1203
1204         v3d->zbuf = zbuf;
1205         if (!zbuf) glDisable(GL_DEPTH_TEST);
1206 }
1207
1208 void ED_view3d_draw_depth_loop(const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d)
1209 {
1210         Base *base;
1211         SceneLayer *sl = eval_ctx->scene_layer;
1212         /* no need for color when drawing depth buffer */
1213         const short dflag_depth = DRAW_CONSTCOLOR;
1214
1215         /* draw set first */
1216         if (scene->set) {
1217                 Scene *sce_iter;
1218                 for (SETLOOPER(scene->set, sce_iter, base)) {
1219                         if ((base->flag & BASE_VISIBLED) != 0) {
1220                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1221                                 if (base->object->transflag & OB_DUPLI) {
1222                                         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1223                                 }
1224                         }
1225                 }
1226         }
1227         
1228         for (base = sl->object_bases.first; base; base = base->next) {
1229                 if ((base->flag & BASE_VISIBLED) != 0) {
1230                         /* dupli drawing */
1231                         if (base->object->transflag & OB_DUPLI) {
1232                                 draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag_depth, TH_UNDEFINED);
1233                         }
1234                         draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag_depth);
1235                 }
1236         }
1237         
1238         /* this isn't that nice, draw xray objects as if they are normal */
1239         if (v3d->afterdraw_transp.first ||
1240             v3d->afterdraw_xray.first ||
1241             v3d->afterdraw_xraytransp.first)
1242         {
1243                 View3DAfter *v3da;
1244                 int mask_orig;
1245
1246                 v3d->xray = true;
1247                 
1248                 /* transp materials can change the depth mask, see #21388 */
1249                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
1250
1251
1252                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
1253                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1254                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
1255                                 draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1256                         }
1257                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1258                 }
1259
1260                 /* draw 3 passes, transp/xray/xraytransp */
1261                 v3d->xray = false;
1262                 v3d->transp = true;
1263                 while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
1264                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1265                         MEM_freeN(v3da);
1266                 }
1267
1268                 v3d->xray = true;
1269                 v3d->transp = false;
1270                 while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
1271                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1272                         MEM_freeN(v3da);
1273                 }
1274
1275                 v3d->xray = true;
1276                 v3d->transp = true;
1277                 while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
1278                         draw_object(eval_ctx, scene, sl, ar, v3d, v3da->base, dflag_depth);
1279                         MEM_freeN(v3da);
1280                 }
1281
1282                 
1283                 v3d->xray = false;
1284                 v3d->transp = false;
1285
1286                 glDepthMask(mask_orig);
1287         }
1288 }
1289
1290 void ED_view3d_draw_select_loop(
1291         const struct EvaluationContext *eval_ctx, ViewContext *vc, Scene *scene, SceneLayer *sl,
1292         View3D *v3d, ARegion *ar, bool use_obedit_skip, bool use_nearest)
1293 {
1294         struct bThemeState theme_state;
1295
1296         short code = 1;
1297         const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
1298
1299         /* Tools may request depth outside of regular drawing code. */
1300         UI_Theme_Store(&theme_state);
1301         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
1302
1303         if (vc->obedit && vc->obedit->type == OB_MBALL) {
1304                 draw_object(eval_ctx, scene, sl, ar, v3d, BASACT_NEW(sl), dflag);
1305         }
1306         else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
1307                 /* if not drawing sketch, draw bones */
1308                 if (!BDR_drawSketchNames(vc)) {
1309                         draw_object(eval_ctx, scene, sl, ar, v3d, BASACT_NEW(sl), dflag);
1310                 }
1311         }
1312         else {
1313                 Base *base;
1314
1315                 for (base = sl->object_bases.first; base; base = base->next) {
1316                         if ((base->flag & BASE_VISIBLED) != 0) {
1317                                 if (((base->flag & BASE_SELECTABLED) == 0) ||
1318                                     (use_obedit_skip && (scene->obedit->data == base->object->data)))
1319                                 {
1320                                         base->object->select_color = 0;
1321                                 }
1322                                 else {
1323                                         base->object->select_color = code;
1324
1325                                         if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
1326                                                 ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
1327                                         }
1328                                         else {
1329                                                 if (GPU_select_load_id(code)) {
1330                                                         draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag);
1331                                                 }
1332                                         }
1333                                         code++;
1334                                 }
1335                         }
1336                 }
1337
1338                 if (use_nearest) {
1339                         bool xrayclear = true;
1340                         if (v3d->afterdraw_xray.first) {
1341                                 view3d_draw_xray_select(eval_ctx, scene, sl, ar, v3d, &xrayclear);
1342                         }
1343                 }
1344         }
1345
1346         UI_Theme_Restore(&theme_state);
1347 }
1348
1349 typedef struct View3DShadow {
1350         struct View3DShadow *next, *prev;
1351         GPULamp *lamp;
1352 } View3DShadow;
1353
1354 static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
1355                                    Object *ob, Object *par,
1356                                    float obmat[4][4], unsigned int lay,
1357                                    ListBase *shadows, SceneRenderLayer *srl)
1358 {
1359         GPULamp *lamp = GPU_lamp_from_blender(scene, ob, par);
1360         
1361         if (lamp) {
1362                 Lamp *la = (Lamp *)ob->data;
1363
1364                 GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
1365                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1366                 
1367                 unsigned int layers = lay & v3d->lay;
1368                 if (srl)
1369                         layers &= srl->lay;
1370
1371                 if (layers &&
1372                     GPU_lamp_has_shadow_buffer(lamp) &&
1373                     /* keep last, may do string lookup */
1374                     GPU_lamp_visible(lamp, srl, NULL))
1375                 {
1376                         View3DShadow *shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1377                         shadow->lamp = lamp;
1378                         BLI_addtail(shadows, shadow);
1379                 }
1380         }
1381 }
1382
1383 static void gpu_update_lamps_shadows_world(const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d)
1384 {
1385         ListBase shadows;
1386         Scene *sce_iter;
1387         Base *base;
1388         World *world = scene->world;
1389         SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
1390         
1391         BLI_listbase_clear(&shadows);
1392         
1393         /* update lamp transform and gather shadow lamps */
1394         for (SETLOOPER(scene, sce_iter, base)) {
1395                 Object *ob = base->object;
1396                 
1397                 if (ob->type == OB_LAMP)
1398                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
1399                 
1400                 if (ob->transflag & OB_DUPLI) {
1401                         DupliObject *dob;
1402                         ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
1403                         
1404                         for (dob = lb->first; dob; dob = dob->next)
1405                                 if (dob->ob->type == OB_LAMP)
1406                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
1407                         
1408                         free_object_duplilist(lb);
1409                 }
1410         }
1411         
1412         /* render shadows after updating all lamps, nested object_duplilist
1413          * don't work correct since it's replacing object matrices */
1414         for (View3DShadow *shadow = shadows.first; shadow; shadow = shadow->next) {
1415                 /* this needs to be done better .. */
1416                 float viewmat[4][4], winmat[4][4];
1417                 ARegion ar = {NULL};
1418                 RegionView3D rv3d = {{{0}}};
1419
1420                 int drawtype = v3d->drawtype;
1421                 int lay = v3d->lay;
1422                 int flag2 = v3d->flag2;
1423
1424                 v3d->drawtype = OB_SOLID;
1425                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1426                 v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
1427                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
1428                 
1429                 int winsize;
1430                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1431
1432                 ar.regiondata = &rv3d;
1433                 ar.regiontype = RGN_TYPE_WINDOW;
1434                 rv3d.persp = RV3D_CAMOB;
1435                 copy_m4_m4(rv3d.winmat, winmat);
1436                 copy_m4_m4(rv3d.viewmat, viewmat);
1437                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
1438                 mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
1439                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
1440
1441                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
1442                 ED_view3d_draw_offscreen(
1443                             eval_ctx, scene, eval_ctx->scene_layer, v3d, &ar, winsize, winsize, viewmat, winmat,
1444                             false, false, true,
1445                             NULL, NULL, NULL, NULL);
1446                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1447                 
1448                 v3d->drawtype = drawtype;
1449                 v3d->lay = lay;
1450                 v3d->flag2 = flag2;
1451         }
1452
1453         BLI_freelistN(&shadows);
1454
1455         /* update world values */
1456         if (world) {
1457                 GPU_mist_update_enable(world->mode & WO_MIST);
1458                 GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
1459                 GPU_horizon_update_color(&world->horr);
1460                 GPU_ambient_update_color(&world->ambr);
1461                 GPU_zenith_update_color(&world->zenr);
1462         }
1463 }
1464
1465 /* *********************** customdata **************** */
1466
1467 CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
1468 {
1469         CustomDataMask mask = 0;
1470         const int drawtype = view3d_effective_drawtype(v3d);
1471
1472         if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
1473             ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
1474         {
1475                 mask |= CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
1476
1477                 if (BKE_scene_use_new_shading_nodes(scene)) {
1478                         if (drawtype == OB_MATERIAL)
1479                                 mask |= CD_MASK_ORCO;
1480                 }
1481                 else {
1482                         if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || 
1483                             (drawtype == OB_MATERIAL))
1484                         {
1485                                 mask |= CD_MASK_ORCO;
1486                         }
1487                 }
1488         }
1489
1490         return mask;
1491 }
1492
1493 /* goes over all modes and view3d settings */
1494 CustomDataMask ED_view3d_screen_datamask(const Scene *scene, const bScreen *screen)
1495 {
1496         CustomDataMask mask = CD_MASK_BAREMESH;
1497         
1498         /* check if we need tfaces & mcols due to view mode */
1499         for (const ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
1500                 if (sa->spacetype == SPACE_VIEW3D) {
1501                         mask |= ED_view3d_datamask(scene, sa->spacedata.first);
1502                 }
1503         }
1504
1505         return mask;
1506 }
1507
1508 /**
1509  * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
1510  *
1511  * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
1512  * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
1513  */
1514 static void view3d_draw_objects(
1515         const bContext *C,
1516         const EvaluationContext *eval_ctx,
1517         Scene *scene, View3D *v3d, ARegion *ar,
1518         const char **grid_unit,
1519         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
1520 {
1521         SceneLayer *sl = C ? CTX_data_scene_layer(C) : BKE_scene_layer_from_scene_get(scene);
1522         RegionView3D *rv3d = ar->regiondata;
1523         Base *base;
1524         const bool do_camera_frame = !draw_offscreen;
1525         const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
1526         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
1527         /* only draw grids after in solid modes, else it hovers over mesh wires */
1528         const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
1529         bool do_composite_xray = false;
1530         bool xrayclear = true;
1531
1532         if (!draw_offscreen) {
1533                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
1534         }
1535
1536         if (rv3d->rflag & RV3D_CLIPPING)
1537                 view3d_draw_clipping(rv3d);
1538
1539         /* set zbuffer after we draw clipping region */
1540         v3d->zbuf = VP_legacy_use_depth(scene, v3d);
1541
1542         if (v3d->zbuf) {
1543                 glEnable(GL_DEPTH_TEST);
1544         }
1545
1546         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
1547          * objects if done last */
1548         if (draw_grids) {
1549                 /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
1550                 rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
1551
1552                 if (!draw_floor) {
1553                         ED_region_pixelspace(ar);
1554                         *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
1555                         VP_legacy_drawgrid(&scene->unit, ar, v3d, grid_unit);
1556                         gpuLoadProjectionMatrix(rv3d->winmat);
1557                         gpuLoadMatrix(rv3d->viewmat);
1558                 }
1559                 else if (!draw_grids_after) {
1560                         VP_legacy_drawfloor(scene, v3d, grid_unit, true);
1561                 }
1562         }
1563
1564         /* important to do before clipping */
1565         if (do_bgpic) {
1566                 view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
1567         }
1568
1569         if (rv3d->rflag & RV3D_CLIPPING) {
1570                 ED_view3d_clipping_set(rv3d);
1571         }
1572
1573         /* draw set first */
1574         if (scene->set) {
1575                 const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
1576                 Scene *sce_iter;
1577                 for (SETLOOPER(scene->set, sce_iter, base)) {
1578                         if ((base->flag & BASE_VISIBLED) != 0) {
1579                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1580                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, dflag);
1581
1582                                 if (base->object->transflag & OB_DUPLI) {
1583                                         draw_dupli_objects_color(eval_ctx, scene, sl, ar, v3d, base, dflag, TH_UNDEFINED);
1584                                 }
1585                         }
1586                 }
1587
1588                 /* Transp and X-ray afterdraw stuff for sets is done later */
1589         }
1590
1591         if (draw_offscreen) {
1592                 for (base = sl->object_bases.first; base; base = base->next) {
1593                         if ((base->flag & BASE_VISIBLED) != 0) {
1594                                 /* dupli drawing */
1595                                 if (base->object->transflag & OB_DUPLI) {
1596                                         draw_dupli_objects(eval_ctx, scene, sl, ar, v3d, base);
1597                                 }
1598
1599                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1600                         }
1601                 }
1602         }
1603         else {
1604                 unsigned int lay_used = 0;
1605
1606                 /* then draw not selected and the duplis, but skip editmode object */
1607                 for (base = sl->object_bases.first; base; base = base->next) {
1608                         lay_used |= base->lay;
1609
1610                         if ((base->flag & BASE_VISIBLED) != 0) {
1611
1612                                 /* dupli drawing */
1613                                 if (base->object->transflag & OB_DUPLI) {
1614                                         draw_dupli_objects(eval_ctx, scene, sl, ar, v3d, base);
1615                                 }
1616                                 if ((base->flag & BASE_SELECTED) == 0) {
1617                                         if (base->object != scene->obedit)
1618                                                 draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1619                                 }
1620                         }
1621                 }
1622
1623                 /* mask out localview */
1624                 v3d->lay_used = lay_used & ((1 << 20) - 1);
1625
1626                 /* draw selected and editmode */
1627                 for (base = sl->object_bases.first; base; base = base->next) {
1628                         if ((base->flag & BASE_VISIBLED) != 0) {
1629                                 if (base->object == scene->obedit || (base->flag & BASE_SELECTED)) {
1630                                         draw_object(eval_ctx, scene, sl, ar, v3d, base, 0);
1631                                 }
1632                         }
1633                 }
1634         }
1635
1636         /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
1637         if (draw_grids_after) {
1638                 VP_legacy_drawfloor(scene, v3d, grid_unit, false);
1639         }
1640
1641         /* must be before xray draw which clears the depth buffer */
1642         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
1643                 wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
1644                 
1645                 /* must be before xray draw which clears the depth buffer */
1646                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1647                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
1648                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1649         }
1650
1651         /* transp and X-ray afterdraw stuff */
1652         if (v3d->afterdraw_transp.first)     view3d_draw_transp(eval_ctx, scene, sl, ar, v3d);
1653
1654         /* always do that here to cleanup depth buffers if none needed */
1655         if (fx) {
1656                 do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
1657                 GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
1658         }
1659
1660         if (v3d->afterdraw_xray.first)       view3d_draw_xray(eval_ctx, scene, sl, ar, v3d, &xrayclear);
1661         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(eval_ctx, scene, sl, ar, v3d, xrayclear);
1662
1663         if (fx && do_composite_xray) {
1664                 GPU_fx_compositor_XRay_resolve(fx);
1665         }
1666
1667         if (!draw_offscreen) {
1668                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
1669         }
1670
1671         if (rv3d->rflag & RV3D_CLIPPING)
1672                 ED_view3d_clipping_disable();
1673
1674         /* important to do after clipping */
1675         if (do_bgpic) {
1676                 view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
1677         }
1678
1679         /* cleanup */
1680         if (v3d->zbuf) {
1681                 v3d->zbuf = false;
1682                 glDisable(GL_DEPTH_TEST);
1683         }
1684
1685         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
1686                 GPU_free_images_old();
1687         }
1688 }
1689
1690 /**
1691  * Store values from #RegionView3D, set when drawing.
1692  * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
1693  *
1694  * Values set by #ED_view3d_update_viewmat should be handled here.
1695  */
1696 struct RV3DMatrixStore {
1697         float winmat[4][4];
1698         float viewmat[4][4];
1699         float viewinv[4][4];
1700         float persmat[4][4];
1701         float persinv[4][4];
1702         float viewcamtexcofac[4];
1703         float pixsize;
1704 };
1705
1706 struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
1707 {
1708         struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
1709         copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
1710         copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
1711         copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
1712         copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
1713         copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
1714         copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
1715         rv3dmat->pixsize = rv3d->pixsize;
1716         return (void *)rv3dmat;
1717 }
1718
1719 void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat_pt)
1720 {
1721         struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
1722         copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
1723         copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
1724         copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
1725         copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
1726         copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
1727         copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
1728         rv3d->pixsize = rv3dmat->pixsize;
1729 }
1730
1731 /**
1732  * \note The info that this uses is updated in #ED_refresh_viewport_fps,
1733  * which currently gets called during #SCREEN_OT_animation_step.
1734  */
1735 void ED_scene_draw_fps(Scene *scene, const rcti *rect)
1736 {
1737         ScreenFrameRateInfo *fpsi = scene->fps_info;
1738         char printable[16];
1739         
1740         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
1741                 return;
1742         
1743         printable[0] = '\0';
1744         
1745 #if 0
1746         /* this is too simple, better do an average */
1747         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
1748 #else
1749         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
1750         
1751         float fps = 0.0f;
1752         int tot = 0;
1753         for (int i = 0; i < REDRAW_FRAME_AVERAGE; i++) {
1754                 if (fpsi->redrawtimes_fps[i]) {
1755                         fps += fpsi->redrawtimes_fps[i];
1756                         tot++;
1757                 }
1758         }
1759         if (tot) {
1760                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
1761                 
1762                 //fpsi->redrawtime_index++;
1763                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
1764                 //      fpsi->redrawtime = 0;
1765                 
1766                 fps = fps / tot;
1767         }
1768 #endif
1769
1770         const int font_id = BLF_default();
1771
1772         /* is this more than half a frame behind? */
1773         if (fps + 0.5f < (float)(FPS)) {
1774                 UI_FontThemeColor(font_id, TH_REDALERT);
1775                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
1776         }
1777         else {
1778                 UI_FontThemeColor(font_id, TH_TEXT_HI);
1779                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
1780         }
1781
1782 #ifdef WITH_INTERNATIONAL
1783         BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1784 #else
1785         BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
1786 #endif
1787 }
1788
1789 static bool view3d_main_region_do_render_draw(const Scene *scene)
1790 {
1791         RenderEngineType *type = RE_engines_find(scene->r.engine);
1792
1793         return (type && type->view_update && type->render_to_view);
1794 }
1795
1796 bool ED_view3d_calc_render_border(const Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
1797 {
1798         RegionView3D *rv3d = ar->regiondata;
1799         bool use_border;
1800
1801         /* test if there is a 3d view rendering */
1802         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene))
1803                 return false;
1804
1805         /* test if there is a border render */
1806         if (rv3d->persp == RV3D_CAMOB)
1807                 use_border = (scene->r.mode & R_BORDER) != 0;
1808         else
1809                 use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
1810         
1811         if (!use_border)
1812                 return false;
1813
1814         /* compute border */
1815         if (rv3d->persp == RV3D_CAMOB) {
1816                 rctf viewborder;
1817                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1818
1819                 rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
1820                 rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
1821                 rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
1822                 rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
1823         }
1824         else {
1825                 rect->xmin = v3d->render_border.xmin * ar->winx;
1826                 rect->xmax = v3d->render_border.xmax * ar->winx;
1827                 rect->ymin = v3d->render_border.ymin * ar->winy;
1828                 rect->ymax = v3d->render_border.ymax * ar->winy;
1829         }
1830
1831         BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
1832         BLI_rcti_isect(&ar->winrct, rect, rect);
1833
1834         return true;
1835 }
1836
1837 /**
1838   * IMPORTANT: this is deprecated, any changes made in this function should
1839   * be mirrored in view3d_draw_render_draw() in view3d_draw.c
1840   */
1841 static bool view3d_main_region_draw_engine(
1842         const bContext *C, const EvaluationContext *eval_ctx, Scene *scene,
1843         ARegion *ar, View3D *v3d,
1844         bool clip_border, const rcti *border_rect)
1845 {
1846         RegionView3D *rv3d = ar->regiondata;
1847         RenderEngineType *type;
1848         GLint scissor[4];
1849
1850
1851         /* create render engine */
1852         if (!rv3d->render_engine) {
1853                 RenderEngine *engine;
1854
1855                 type = RE_engines_find(scene->r.engine);
1856
1857                 if (!(type->view_update && type->render_to_view))
1858                         return false;
1859
1860                 engine = RE_engine_create_ex(type, true);
1861
1862                 engine->tile_x = scene->r.tilex;
1863                 engine->tile_y = scene->r.tiley;
1864
1865                 type->view_update(engine, C);
1866
1867                 rv3d->render_engine = engine;
1868         }
1869
1870         /* setup view matrices */
1871         VP_legacy_view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, NULL, NULL);
1872
1873         /* background draw */
1874         ED_region_pixelspace(ar);
1875
1876         if (clip_border) {
1877                 /* for border draw, we only need to clear a subset of the 3d view */
1878                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
1879                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
1880                         glScissor(border_rect->xmin, border_rect->ymin,
1881                                   BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
1882                 }
1883                 else {
1884                         return false;
1885                 }
1886         }
1887
1888         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
1889         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1890
1891         if (v3d->flag & V3D_DISPBGPICS)
1892                 view3d_draw_bgpic_test(scene, ar, v3d, false, true);
1893         else
1894                 imm_draw_checker_box(0, 0, ar->winx, ar->winy);
1895
1896         /* render result draw */
1897         type = rv3d->render_engine->type;
1898         type->render_to_view(rv3d->render_engine, C);
1899
1900         if (v3d->flag & V3D_DISPBGPICS)
1901                 view3d_draw_bgpic_test(scene, ar, v3d, true, true);
1902
1903         if (clip_border) {
1904                 /* restore scissor as it was before */
1905                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
1906         }
1907
1908         return true;
1909 }
1910
1911 static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
1912 {
1913         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
1914
1915         if (!rv3d->render_engine || !rv3d->render_engine->text[0])
1916                 return;
1917         
1918         if (render_border) {
1919                 /* draw darkened background color. no alpha because border render does
1920                  * partial redraw and will not redraw the region behind this info bar */
1921                 float alpha = 1.0f - fill_color[3];
1922                 Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
1923
1924                 if (camera) {
1925                         if (camera->flag & CAM_SHOWPASSEPARTOUT) {
1926                                 alpha *= (1.0f - camera->passepartalpha);
1927                         }
1928                 }
1929
1930                 UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
1931                 mul_v3_fl(fill_color, alpha);
1932                 fill_color[3] = 1.0f;
1933         }
1934
1935         ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
1936 }
1937
1938 #ifdef WITH_GAMEENGINE
1939 static void update_lods(Scene *scene, float camera_pos[3])
1940 {
1941         Scene *sce_iter;
1942         Base *base;
1943
1944         for (SETLOOPER(scene, sce_iter, base)) {
1945                 Object *ob = base->object;
1946                 BKE_object_lod_update(ob, camera_pos);
1947         }
1948 }
1949 #endif
1950
1951 static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, SceneLayer *sl, View3D *v3d,
1952                                           ARegion *ar, const char **grid_unit)
1953 {
1954         wmWindow *win = CTX_wm_window(C);
1955         EvaluationContext eval_ctx;
1956         RegionView3D *rv3d = ar->regiondata;
1957         unsigned int lay_used = v3d->lay_used;
1958         
1959         CTX_data_eval_ctx(C, &eval_ctx);
1960
1961         /* post processing */
1962         bool do_compositing = false;
1963         
1964         /* shadow buffers, before we setup matrices */
1965         if (draw_glsl_material(scene, sl, NULL, v3d, v3d->drawtype))
1966                 gpu_update_lamps_shadows_world(&eval_ctx, scene, v3d);
1967
1968         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
1969         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
1970                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
1971                 GPU_default_lights();
1972         }
1973
1974         /* setup the view matrix */
1975         if (VP_legacy_view3d_stereo3d_active(win, scene, v3d, rv3d)) {
1976                 VP_legacy_view3d_stereo3d_setup(&eval_ctx, scene, v3d, ar);
1977         }
1978         else {
1979                 VP_legacy_view3d_main_region_setup_view(&eval_ctx, scene, v3d, ar, NULL, NULL);
1980         }
1981
1982         rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
1983 #ifdef WITH_GAMEENGINE
1984         if (STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME)) {
1985                 rv3d->rflag |= RV3D_IS_GAME_ENGINE;
1986
1987                 /* Make sure LoDs are up to date */
1988                 update_lods(scene, rv3d->viewinv[3]);
1989         }
1990 #endif
1991
1992         /* framebuffer fx needed, we need to draw offscreen first */
1993         if (v3d->fx_settings.fx_flag && v3d->drawtype >= OB_SOLID) {
1994                 BKE_screen_gpu_fx_validate(&v3d->fx_settings);
1995                 GPUFXSettings fx_settings = v3d->fx_settings;
1996                 if (!rv3d->compositor)
1997                         rv3d->compositor = GPU_fx_compositor_create();
1998                 
1999                 if (rv3d->persp == RV3D_CAMOB && v3d->camera)
2000                         BKE_camera_to_gpu_dof(v3d->camera, &fx_settings);
2001                 else {
2002                         fx_settings.dof = NULL;
2003                 }
2004
2005                 do_compositing = GPU_fx_compositor_initialize_passes(rv3d->compositor, &ar->winrct, &ar->drawrct, &fx_settings);
2006         }
2007         
2008         /* enables anti-aliasing for 3D view drawing */
2009         if (win->multisamples != USER_MULTISAMPLE_NONE) {
2010                 glEnable(GL_MULTISAMPLE);
2011         }
2012
2013         /* main drawing call */
2014         view3d_draw_objects(C, &eval_ctx, scene, v3d, ar, grid_unit, true, false, do_compositing ? rv3d->compositor : NULL);
2015
2016         /* draw depth culled manipulators - manipulators need to be updated *after* view matrix was set up */
2017         /* TODO depth culling manipulators is not yet supported, just drawing _3D here, should
2018          * later become _IN_SCENE (and draw _3D separate) */
2019         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_3D);
2020
2021         /* post process */
2022         if (do_compositing) {
2023                 GPU_fx_do_composite_pass(rv3d->compositor, rv3d->winmat, rv3d->is_persp, scene, NULL);
2024         }
2025
2026         /* Disable back anti-aliasing */
2027         if (win->multisamples != USER_MULTISAMPLE_NONE) {
2028                 glDisable(GL_MULTISAMPLE);
2029         }
2030
2031         if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2032                 /* find header and force tag redraw */
2033                 ScrArea *sa = CTX_wm_area(C);
2034                 ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
2035                 ED_region_tag_redraw(ar_header); /* can be NULL */
2036         }
2037
2038         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2039                 BDR_drawSketch(C);
2040         }
2041 }
2042
2043 static void view3d_main_region_draw_info(const bContext *C, Scene *scene,
2044                                        ARegion *ar, View3D *v3d,
2045                                        const char *grid_unit, bool render_border)
2046 {
2047         SceneLayer *sl = CTX_data_scene_layer(C);
2048         wmWindowManager *wm = CTX_wm_manager(C);
2049         RegionView3D *rv3d = ar->regiondata;
2050         rcti rect;
2051         
2052         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2053         ED_region_visible_rect(ar, &rect);
2054
2055         if (rv3d->persp == RV3D_CAMOB) {
2056                 VP_drawviewborder(scene, ar, v3d);
2057         }
2058         else if (v3d->flag2 & V3D_RENDER_BORDER) {
2059                 VP_drawrenderborder(ar, v3d);
2060         }
2061
2062         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2063                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2064                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, false);
2065         }
2066
2067         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2068                 VP_legacy_drawcursor(scene, sl, ar, v3d); /* 3D cursor */
2069
2070                 if (U.uiflag & USER_SHOW_ROTVIEWICON)
2071                         VP_legacy_draw_view_axis(rv3d, &rect);
2072                 else
2073                         draw_view_icon(rv3d, &rect);
2074
2075                 if (U.uiflag & USER_DRAWVIEWINFO) {
2076                         Object *ob = OBACT_NEW(sl);
2077                         VP_legacy_draw_selected_name(scene, ob, &rect);
2078                 }
2079         }
2080
2081         if (rv3d->render_engine) {
2082                 view3d_main_region_draw_engine_info(v3d, rv3d, ar, render_border);
2083                 return;
2084         }
2085
2086         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2087                 if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
2088                         ED_scene_draw_fps(scene, &rect);
2089                 }
2090                 else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
2091                         VP_legacy_draw_viewport_name(ar, v3d, &rect);
2092                 }
2093
2094                 if (grid_unit) { /* draw below the viewport name */
2095                         char numstr[32] = "";
2096
2097                         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2098                         if (v3d->grid != 1.0f) {
2099                                 BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
2100                         }
2101
2102                         BLF_draw_default_ascii(rect.xmin + U.widget_unit,
2103                                                rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
2104                                                numstr[0] ? numstr : grid_unit, sizeof(numstr));
2105                 }
2106         }
2107 }
2108
2109 void view3d_main_region_draw_legacy(const bContext *C, ARegion *ar)
2110 {
2111         EvaluationContext eval_ctx;
2112         Scene *scene = CTX_data_scene(C);
2113         SceneLayer *sl = CTX_data_scene_layer(C);
2114         View3D *v3d = CTX_wm_view3d(C);
2115         const char *grid_unit = NULL;
2116         rcti border_rect;
2117
2118         /* if we only redraw render border area, skip opengl draw and also
2119          * don't do scissor because it's already set */
2120         bool render_border = ED_view3d_calc_render_border(scene, v3d, ar, &border_rect);
2121         bool clip_border = (render_border && !BLI_rcti_compare(&ar->drawrct, &border_rect));
2122
2123         gpuPushProjectionMatrix();
2124         gpuLoadIdentityProjectionMatrix();
2125         gpuPushMatrix();
2126         gpuLoadIdentity();
2127
2128         CTX_data_eval_ctx(C, &eval_ctx);
2129
2130         /* draw viewport using opengl */
2131         if (v3d->drawtype != OB_RENDER || !view3d_main_region_do_render_draw(scene) || clip_border) {
2132                 VP_view3d_main_region_clear(scene, v3d, ar); /* background */
2133                 view3d_main_region_draw_objects(C, scene, sl, v3d, ar, &grid_unit);
2134
2135                 if (G.debug & G_DEBUG_SIMDATA)
2136                         draw_sim_debug_data(scene, v3d, ar);
2137
2138                 glDisable(GL_DEPTH_TEST);
2139                 ED_region_pixelspace(ar);
2140         }
2141
2142         /* draw viewport using external renderer */
2143         if (v3d->drawtype == OB_RENDER) {
2144                 view3d_main_region_draw_engine(C, &eval_ctx, scene, ar, v3d, clip_border, &border_rect);
2145         }
2146
2147         VP_legacy_view3d_main_region_setup_view(&eval_ctx, scene, v3d, ar, NULL, NULL);
2148         glClear(GL_DEPTH_BUFFER_BIT);
2149
2150         ED_region_pixelspace(ar);
2151
2152         WM_manipulatormap_draw(ar->manipulator_map, C, WM_MANIPULATORMAP_DRAWSTEP_2D);
2153
2154         view3d_main_region_draw_info(C, scene, ar, v3d, grid_unit, render_border);
2155
2156         gpuPopProjectionMatrix();
2157         gpuPopMatrix();
2158
2159         v3d->flag |= V3D_INVALID_BACKBUF;
2160
2161         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_transp));
2162         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xray));
2163         BLI_assert(BLI_listbase_is_empty(&v3d->afterdraw_xraytransp));
2164 }
2165
2166
2167 /* -------------------------------------------------------------------- */
2168
2169 /** \name Deprecated Interface
2170  *
2171  * New viewport sometimes has a check for new/old viewport code.
2172  * Use these functions so new viewport can *optionally* call.
2173  *
2174  * \{ */
2175
2176
2177 void VP_deprecated_view3d_draw_objects(
2178         const bContext *C,
2179         const EvaluationContext *eval_ctx,
2180         Scene *scene, View3D *v3d, ARegion *ar,
2181         const char **grid_unit,
2182         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
2183 {
2184         view3d_draw_objects(C, eval_ctx, scene, v3d, ar, grid_unit, do_bgpic, draw_offscreen, fx);
2185 }
2186
2187 void VP_deprecated_gpu_update_lamps_shadows_world(const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d)
2188 {
2189         gpu_update_lamps_shadows_world(eval_ctx, scene, v3d);
2190 }
2191
2192 /** \} */