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