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