Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 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.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_main.h"
64 #include "BKE_object.h"
65 #include "BKE_global.h"
66 #include "BKE_paint.h"
67 #include "BKE_scene.h"
68 #include "BKE_screen.h"
69 #include "BKE_unit.h"
70 #include "BKE_movieclip.h"
71
72 #include "RE_engine.h"
73
74 #include "IMB_imbuf_types.h"
75 #include "IMB_imbuf.h"
76 #include "IMB_colormanagement.h"
77
78 #include "BIF_gl.h"
79 #include "BIF_glutil.h"
80
81 #include "WM_api.h"
82
83 #include "BLF_api.h"
84 #include "BLT_translation.h"
85
86 #include "ED_armature.h"
87 #include "ED_keyframing.h"
88 #include "ED_gpencil.h"
89 #include "ED_screen.h"
90 #include "ED_space_api.h"
91 #include "ED_screen_types.h"
92 #include "ED_transform.h"
93
94 #include "UI_interface.h"
95 #include "UI_interface_icons.h"
96 #include "UI_resources.h"
97
98 #include "GPU_draw.h"
99 #include "GPU_framebuffer.h"
100 #include "GPU_material.h"
101 #include "GPU_compositing.h"
102 #include "GPU_extensions.h"
103
104 #include "view3d_intern.h"  /* own include */
105
106 /* prototypes */
107 static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar);
108 static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
109                                             float winmat[4][4], const char *viewname);
110
111 /* handy utility for drawing shapes in the viewport for arbitrary code.
112  * could add lines and points too */
113 // #define DEBUG_DRAW
114 #ifdef DEBUG_DRAW
115 static void bl_debug_draw(void);
116 /* add these locally when using these functions for testing */
117 extern void bl_debug_draw_quad_clear(void);
118 extern void bl_debug_draw_quad_add(const float v0[3], const float v1[3], const float v2[3], const float v3[3]);
119 extern void bl_debug_draw_edge_add(const float v0[3], const float v1[3]);
120 extern void bl_debug_color_set(const unsigned int col);
121 #endif
122
123 void circf(float x, float y, float rad)
124 {
125         GLUquadricObj *qobj = gluNewQuadric(); 
126         
127         gluQuadricDrawStyle(qobj, GLU_FILL); 
128         
129         glPushMatrix(); 
130         
131         glTranslatef(x, y, 0.0);
132         
133         gluDisk(qobj, 0.0,  rad, 32, 1);
134         
135         glPopMatrix(); 
136         
137         gluDeleteQuadric(qobj);
138 }
139
140 void circ(float x, float y, float rad)
141 {
142         GLUquadricObj *qobj = gluNewQuadric(); 
143         
144         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
145         
146         glPushMatrix(); 
147         
148         glTranslatef(x, y, 0.0);
149         
150         gluDisk(qobj, 0.0,  rad, 32, 1);
151         
152         glPopMatrix(); 
153         
154         gluDeleteQuadric(qobj);
155 }
156
157
158 /* ********* custom clipping *********** */
159
160 static void view3d_draw_clipping(RegionView3D *rv3d)
161 {
162         BoundBox *bb = rv3d->clipbb;
163
164         if (bb) {
165                 const unsigned int clipping_index[6][4] = {
166                         {0, 1, 2, 3},
167                         {0, 4, 5, 1},
168                         {4, 7, 6, 5},
169                         {7, 3, 2, 6},
170                         {1, 5, 6, 2},
171                         {7, 4, 0, 3}
172                 };
173
174                 /* fill in zero alpha for rendering & re-projection [#31530] */
175                 unsigned char col[4];
176                 UI_GetThemeColor4ubv(TH_V3D_CLIPPING_BORDER, col);
177                 glColor4ubv(col);
178
179                 glEnable(GL_BLEND);
180                 glEnableClientState(GL_VERTEX_ARRAY);
181                 glVertexPointer(3, GL_FLOAT, 0, bb->vec);
182                 glDrawElements(GL_QUADS, sizeof(clipping_index) / sizeof(unsigned int), GL_UNSIGNED_INT, clipping_index);
183                 glDisableClientState(GL_VERTEX_ARRAY);
184                 glDisable(GL_BLEND);
185         }
186 }
187
188 void ED_view3d_clipping_set(RegionView3D *rv3d)
189 {
190         double plane[4];
191         const unsigned int tot = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : 6;
192         unsigned int a;
193
194         for (a = 0; a < tot; a++) {
195                 copy_v4db_v4fl(plane, rv3d->clip[a]);
196                 glClipPlane(GL_CLIP_PLANE0 + a, plane);
197                 glEnable(GL_CLIP_PLANE0 + a);
198         }
199 }
200
201 /* use these to temp disable/enable clipping when 'rv3d->rflag & RV3D_CLIPPING' is set */
202 void ED_view3d_clipping_disable(void)
203 {
204         unsigned int a;
205
206         for (a = 0; a < 6; a++) {
207                 glDisable(GL_CLIP_PLANE0 + a);
208         }
209 }
210 void ED_view3d_clipping_enable(void)
211 {
212         unsigned int a;
213
214         for (a = 0; a < 6; a++) {
215                 glEnable(GL_CLIP_PLANE0 + a);
216         }
217 }
218
219 static bool view3d_clipping_test(const float co[3], const float clip[6][4])
220 {
221         if (plane_point_side_v3(clip[0], co) > 0.0f)
222                 if (plane_point_side_v3(clip[1], co) > 0.0f)
223                         if (plane_point_side_v3(clip[2], co) > 0.0f)
224                                 if (plane_point_side_v3(clip[3], co) > 0.0f)
225                                         return false;
226
227         return true;
228 }
229
230 /* for 'local' ED_view3d_clipping_local must run first
231  * then all comparisons can be done in localspace */
232 bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], const bool is_local)
233 {
234         return view3d_clipping_test(co, is_local ? rv3d->clip_local : rv3d->clip);
235 }
236
237 /* ********* end custom clipping *********** */
238
239
240 static void drawgrid_draw(ARegion *ar, double wx, double wy, double x, double y, double dx)
241 {       
242         double verts[2][2];
243
244         x += (wx);
245         y += (wy);
246
247         /* set fixed 'Y' */
248         verts[0][1] = 0.0f;
249         verts[1][1] = (double)ar->winy;
250
251         /* iter over 'X' */
252         verts[0][0] = verts[1][0] = x - dx * floor(x / dx);
253         glEnableClientState(GL_VERTEX_ARRAY);
254         glVertexPointer(2, GL_DOUBLE, 0, verts);
255
256         while (verts[0][0] < ar->winx) {
257                 glDrawArrays(GL_LINES, 0, 2);
258                 verts[0][0] = verts[1][0] = verts[0][0] + dx;
259         }
260
261         /* set fixed 'X' */
262         verts[0][0] = 0.0f;
263         verts[1][0] = (double)ar->winx;
264
265         /* iter over 'Y' */
266         verts[0][1] = verts[1][1] = y - dx * floor(y / dx);
267         while (verts[0][1] < ar->winy) {
268                 glDrawArrays(GL_LINES, 0, 2);
269                 verts[0][1] = verts[1][1] = verts[0][1] + dx;
270         }
271
272         glDisableClientState(GL_VERTEX_ARRAY);
273 }
274
275 #define GRID_MIN_PX_D   6.0
276 #define GRID_MIN_PX_F 6.0f
277
278 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
279 {
280         /* extern short bgpicmode; */
281         RegionView3D *rv3d = ar->regiondata;
282         double wx, wy, x, y, fw, fx, fy, dx;
283         double vec4[4];
284         unsigned char col[3], col2[3];
285
286         fx = rv3d->persmat[3][0];
287         fy = rv3d->persmat[3][1];
288         fw = rv3d->persmat[3][3];
289
290         wx = (ar->winx / 2.0); /* because of rounding errors, grid at wrong location */
291         wy = (ar->winy / 2.0);
292
293         x = (wx) * fx / fw;
294         y = (wy) * fy / fw;
295
296         vec4[0] = vec4[1] = v3d->grid;
297
298         vec4[2] = 0.0;
299         vec4[3] = 1.0;
300         mul_m4_v4d(rv3d->persmat, vec4);
301         fx = vec4[0];
302         fy = vec4[1];
303         fw = vec4[3];
304
305         dx = fabs(x - (wx) * fx / fw);
306         if (dx == 0) dx = fabs(y - (wy) * fy / fw);
307         
308         glLineWidth(1.0f);
309
310         glDepthMask(GL_FALSE);     /* disable write in zbuffer */
311
312         /* check zoom out */
313         UI_ThemeColor(TH_GRID);
314         
315         if (unit->system) {
316                 /* Use GRID_MIN_PX * 2 for units because very very small grid
317                  * items are less useful when dealing with units */
318                 const void *usys;
319                 int len, i;
320                 double dx_scalar;
321                 float blend_fac;
322
323                 bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
324
325                 if (usys) {
326                         i = len;
327                         while (i--) {
328                                 double scalar = bUnit_GetScaler(usys, i);
329
330                                 dx_scalar = dx * scalar / (double)unit->scale_length;
331                                 if (dx_scalar < (GRID_MIN_PX_D * 2.0))
332                                         continue;
333
334                                 /* Store the smallest drawn grid size units name so users know how big each grid cell is */
335                                 if (*grid_unit == NULL) {
336                                         *grid_unit = bUnit_GetNameDisplay(usys, i);
337                                         rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
338                                 }
339                                 blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
340
341                                 /* tweak to have the fade a bit nicer */
342                                 blend_fac = (blend_fac * blend_fac) * 2.0f;
343                                 CLAMP(blend_fac, 0.3f, 1.0f);
344
345
346                                 UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, blend_fac);
347
348                                 drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
349                         }
350                 }
351         }
352         else {
353                 const double sublines    = v3d->gridsubdiv;
354                 const float  sublines_fl = v3d->gridsubdiv;
355
356                 if (dx < GRID_MIN_PX_D) {
357                         rv3d->gridview *= sublines_fl;
358                         dx *= sublines;
359
360                         if (dx < GRID_MIN_PX_D) {
361                                 rv3d->gridview *= sublines_fl;
362                                 dx *= sublines;
363
364                                 if (dx < GRID_MIN_PX_D) {
365                                         rv3d->gridview *= sublines_fl;
366                                         dx *= sublines;
367                                         if (dx < GRID_MIN_PX_D) {
368                                                 /* pass */
369                                         }
370                                         else {
371                                                 UI_ThemeColor(TH_GRID);
372                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
373                                         }
374                                 }
375                                 else {  /* start blending out */
376                                         UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
377                                         drawgrid_draw(ar, wx, wy, x, y, dx);
378
379                                         UI_ThemeColor(TH_GRID);
380                                         drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
381                                 }
382                         }
383                         else {  /* start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX * 10)) */
384                                 UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
385                                 drawgrid_draw(ar, wx, wy, x, y, dx);
386
387                                 UI_ThemeColor(TH_GRID);
388                                 drawgrid_draw(ar, wx, wy, x, y, sublines * dx);
389                         }
390                 }
391                 else {
392                         if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
393                                 rv3d->gridview /= sublines_fl;
394                                 dx /= sublines;
395                                 if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
396                                         rv3d->gridview /= sublines_fl;
397                                         dx /= sublines;
398                                         if (dx > (GRID_MIN_PX_D * 10.0)) {
399                                                 UI_ThemeColor(TH_GRID);
400                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
401                                         }
402                                         else {
403                                                 UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
404                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
405                                                 UI_ThemeColor(TH_GRID);
406                                                 drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
407                                         }
408                                 }
409                                 else {
410                                         UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
411                                         drawgrid_draw(ar, wx, wy, x, y, dx);
412                                         UI_ThemeColor(TH_GRID);
413                                         drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
414                                 }
415                         }
416                         else {
417                                 UI_ThemeColorBlend(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0));
418                                 drawgrid_draw(ar, wx, wy, x, y, dx);
419                                 UI_ThemeColor(TH_GRID);
420                                 drawgrid_draw(ar, wx, wy, x, y, dx * sublines);
421                         }
422                 }
423         }
424
425
426         x += (wx);
427         y += (wy);
428         UI_GetThemeColor3ubv(TH_GRID, col);
429
430         setlinestyle(0);
431         
432         /* center cross */
433         /* horizontal line */
434         if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
435                 UI_make_axis_color(col, col2, 'Y');
436         else UI_make_axis_color(col, col2, 'X');
437         glColor3ubv(col2);
438         
439         fdrawline(0.0,  y,  (float)ar->winx,  y); 
440         
441         /* vertical line */
442         if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
443                 UI_make_axis_color(col, col2, 'Y');
444         else UI_make_axis_color(col, col2, 'Z');
445         glColor3ubv(col2);
446
447         fdrawline(x, 0.0, x, (float)ar->winy); 
448
449         glDepthMask(GL_TRUE);  /* enable write in zbuffer */
450 }
451 #undef GRID_MIN_PX
452
453 /** could move this elsewhere, but tied into #ED_view3d_grid_scale */
454 float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
455 {
456         /* apply units */
457         if (scene->unit.system) {
458                 const void *usys;
459                 int len;
460
461                 bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
462
463                 if (usys) {
464                         int i = bUnit_GetBaseUnit(usys);
465                         if (grid_unit)
466                                 *grid_unit = bUnit_GetNameDisplay(usys, i);
467                         return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
468                 }
469         }
470
471         return 1.0f;
472 }
473
474 float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
475 {
476         return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
477 }
478
479 static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
480 {
481         float grid, grid_scale;
482         unsigned char col_grid[3];
483         const int gridlines = v3d->gridlines / 2;
484
485         if (v3d->gridlines < 3) return;
486         
487         /* use 'grid_scale' instead of 'v3d->grid' from now on */
488         grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
489         grid = gridlines * grid_scale;
490
491         if (!write_depth)
492                 glDepthMask(GL_FALSE);
493
494         UI_GetThemeColor3ubv(TH_GRID, col_grid);
495
496         glLineWidth(1);
497
498         /* draw the Y axis and/or grid lines */
499         if (v3d->gridflag & V3D_SHOW_FLOOR) {
500                 const int sublines = v3d->gridsubdiv;
501                 float vert[4][3] = {{0.0f}};
502                 unsigned char col_bg[3];
503                 unsigned char col_grid_emphasise[3], col_grid_light[3];
504                 int a;
505                 int prev_emphasise = -1;
506
507                 UI_GetThemeColor3ubv(TH_BACK, col_bg);
508
509                 /* emphasise division lines lighter instead of darker, if background is darker than grid */
510                 UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
511                 UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
512                                         (((col_grid[0] + col_grid[1] + col_grid[2]) + 30) >
513                                          (col_bg[0] + col_bg[1] + col_bg[2])) ? 20 : -10);
514
515                 /* set fixed axis */
516                 vert[0][0] = vert[2][1] = grid;
517                 vert[1][0] = vert[3][1] = -grid;
518
519                 glEnableClientState(GL_VERTEX_ARRAY);
520                 glVertexPointer(3, GL_FLOAT, 0, vert);
521
522                 for (a = -gridlines; a <= gridlines; a++) {
523                         const float line = a * grid_scale;
524                         const int is_emphasise = (a % sublines) == 0;
525
526                         if (is_emphasise != prev_emphasise) {
527                                 glColor3ubv(is_emphasise ? col_grid_emphasise : col_grid_light);
528                                 prev_emphasise = is_emphasise;
529                         }
530
531                         /* set variable axis */
532                         vert[0][1] = vert[1][1] = vert[2][0] = vert[3][0] = line;
533
534                         glDrawArrays(GL_LINES, 0, 4);
535                 }
536
537                 glDisableClientState(GL_VERTEX_ARRAY);
538         }
539         
540         /* draw the Z axis line */
541         /* check for the 'show Z axis' preference */
542         if (v3d->gridflag & (V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
543                 glBegin(GL_LINES);
544                 int axis;
545                 for (axis = 0; axis < 3; axis++) {
546                         if (v3d->gridflag & (V3D_SHOW_X << axis)) {
547                                 float vert[3];
548                                 unsigned char tcol[3];
549
550                                 UI_make_axis_color(col_grid, tcol, 'X' + axis);
551                                 glColor3ubv(tcol);
552
553                                 zero_v3(vert);
554                                 vert[axis] = grid;
555                                 glVertex3fv(vert);
556                                 vert[axis] = -grid;
557                                 glVertex3fv(vert);
558                         }
559                 }
560                 glEnd();
561         }
562         
563         glDepthMask(GL_TRUE);
564 }
565
566
567 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
568 {
569         int co[2];
570
571         /* we don't want the clipping for cursor */
572         if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
573                 const float f5 = 0.25f * U.widget_unit;
574                 const float f10 = 0.5f * U.widget_unit;
575                 const float f20 = U.widget_unit;
576                 
577                 glLineWidth(1);
578                 setlinestyle(0); 
579                 cpack(0xFF);
580                 circ((float)co[0], (float)co[1], f10);
581                 setlinestyle(4);
582                 cpack(0xFFFFFF);
583                 circ((float)co[0], (float)co[1], f10);
584                 setlinestyle(0);
585
586                 UI_ThemeColor(TH_VIEW_OVERLAY);
587                 sdrawline(co[0] - f20, co[1], co[0] - f5, co[1]);
588                 sdrawline(co[0] + f5, co[1], co[0] + f20, co[1]);
589                 sdrawline(co[0], co[1] - f20, co[0], co[1] - f5);
590                 sdrawline(co[0], co[1] + f5, co[0], co[1] + f20);
591         }
592 }
593
594 /* Draw a live substitute of the view icon, which is always shown
595  * colors copied from transform_manipulator.c, we should keep these matching. */
596 static void draw_view_axis(RegionView3D *rv3d, rcti *rect)
597 {
598         const float k = U.rvisize * U.pixelsize;   /* axis size */
599         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
600         float startx = k + 1.0f; /* axis center in screen coordinates, x=y */
601         float starty = k + 1.0f;
602         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
603         int bright = - 20 * (10 - U.rvibright); /* axis alpha offset (rvibright has range 0-10) */
604         float vec[3];
605         float dx, dy;
606
607         int axis_order[3] = {0, 1, 2};
608         int axis_i;
609
610         startx += rect->xmin;
611         starty += rect->ymin;
612
613         axis_sort_v3(rv3d->viewinv[2], axis_order);
614
615         /* thickness of lines is proportional to k */
616         glLineWidth(2);
617
618         glEnable(GL_BLEND);
619         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
620
621         for (axis_i = 0; axis_i < 3; axis_i++) {
622                 int i = axis_order[axis_i];
623                 const char axis_text[2] = {'x' + i, '\0'};
624
625                 zero_v3(vec);
626                 vec[i] = 1.0f;
627                 mul_qt_v3(rv3d->viewquat, vec);
628                 dx = vec[0] * k;
629                 dy = vec[1] * k;
630
631                 UI_ThemeColorShadeAlpha(TH_AXIS_X + i, 0, bright);
632                 glBegin(GL_LINES);
633                 glVertex2f(startx, starty + ydisp);
634                 glVertex2f(startx + dx, starty + dy + ydisp);
635                 glEnd();
636
637                 if (fabsf(dx) > toll || fabsf(dy) > toll) {
638                         BLF_draw_default_ascii(startx + dx + 2, starty + dy + ydisp + 2, 0.0f, axis_text, 1);
639
640                         /* BLF_draw_default disables blending */
641                         glEnable(GL_BLEND);
642                 }
643         }
644
645         glDisable(GL_BLEND);
646 }
647
648 /* draw center and axis of rotation for ongoing 3D mouse navigation */
649 static void draw_rotation_guide(RegionView3D *rv3d)
650 {
651         float o[3];    /* center of rotation */
652         float end[3];  /* endpoints for drawing */
653
654         float color[4] = {0.0f, 0.4235f, 1.0f, 1.0f};  /* bright blue so it matches device LEDs */
655
656         negate_v3_v3(o, rv3d->ofs);
657
658         glEnable(GL_BLEND);
659         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
660         glPointSize(5);
661         glEnable(GL_POINT_SMOOTH);
662         glDepthMask(0);  /* don't overwrite zbuf */
663
664         if (rv3d->rot_angle != 0.0f) {
665                 /* -- draw rotation axis -- */
666                 float scaled_axis[3];
667                 const float scale = rv3d->dist;
668                 mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
669
670
671                 glBegin(GL_LINE_STRIP);
672                 color[3] = 0.0f;  /* more transparent toward the ends */
673                 glColor4fv(color);
674                 add_v3_v3v3(end, o, scaled_axis);
675                 glVertex3fv(end);
676
677 #if 0
678                 color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
679                 /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
680 #endif
681
682                 color[3] = 0.5f;  /* more opaque toward the center */
683                 glColor4fv(color);
684                 glVertex3fv(o);
685
686                 color[3] = 0.0f;
687                 glColor4fv(color);
688                 sub_v3_v3v3(end, o, scaled_axis);
689                 glVertex3fv(end);
690                 glEnd();
691                 
692                 /* -- draw ring around rotation center -- */
693                 {
694 #define     ROT_AXIS_DETAIL 13
695
696                         const float s = 0.05f * scale;
697                         const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
698                         float angle;
699                         int i;
700
701                         float q[4];  /* rotate ring so it's perpendicular to axis */
702                         const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
703                         if (!upright) {
704                                 const float up[3] = {0.0f, 0.0f, 1.0f};
705                                 float vis_angle, vis_axis[3];
706
707                                 cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
708                                 vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
709                                 axis_angle_to_quat(q, vis_axis, vis_angle);
710                         }
711
712                         color[3] = 0.25f;  /* somewhat faint */
713                         glColor4fv(color);
714                         glBegin(GL_LINE_LOOP);
715                         for (i = 0, angle = 0.0f; i < ROT_AXIS_DETAIL; ++i, angle += step) {
716                                 float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
717
718                                 if (!upright) {
719                                         mul_qt_v3(q, p);
720                                 }
721
722                                 add_v3_v3(p, o);
723                                 glVertex3fv(p);
724                         }
725                         glEnd();
726
727 #undef      ROT_AXIS_DETAIL
728                 }
729
730                 color[3] = 1.0f;  /* solid dot */
731         }
732         else
733                 color[3] = 0.5f;  /* see-through dot */
734
735         /* -- draw rotation center -- */
736         glColor4fv(color);
737         glBegin(GL_POINTS);
738         glVertex3fv(o);
739         glEnd();
740
741 #if 0
742         /* find screen coordinates for rotation center, then draw pretty icon */
743         mul_m4_v3(rv3d->persinv, rot_center);
744         UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
745         /* ^^ just playing around, does not work */
746 #endif
747
748         glDisable(GL_BLEND);
749         glDisable(GL_POINT_SMOOTH);
750         glDepthMask(1);
751 }
752
753 static void draw_view_icon(RegionView3D *rv3d, rcti *rect)
754 {
755         BIFIconID icon;
756         
757         if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM))
758                 icon = ICON_AXIS_TOP;
759         else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK))
760                 icon = ICON_AXIS_FRONT;
761         else if (ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT))
762                 icon = ICON_AXIS_SIDE;
763         else return;
764         
765         glEnable(GL_BLEND);
766         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
767         
768         UI_icon_draw(5.0 + rect->xmin, 5.0 + rect->ymin, icon);
769         
770         glDisable(GL_BLEND);
771 }
772
773 static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
774 {
775         const char *name = NULL;
776         
777         switch (rv3d->view) {
778                 case RV3D_VIEW_FRONT:
779                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Front Ortho");
780                         else name = IFACE_("Front Persp");
781                         break;
782                 case RV3D_VIEW_BACK:
783                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Back Ortho");
784                         else name = IFACE_("Back Persp");
785                         break;
786                 case RV3D_VIEW_TOP:
787                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Top Ortho");
788                         else name = IFACE_("Top Persp");
789                         break;
790                 case RV3D_VIEW_BOTTOM:
791                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Bottom Ortho");
792                         else name = IFACE_("Bottom Persp");
793                         break;
794                 case RV3D_VIEW_RIGHT:
795                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Right Ortho");
796                         else name = IFACE_("Right Persp");
797                         break;
798                 case RV3D_VIEW_LEFT:
799                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Left Ortho");
800                         else name = IFACE_("Left Persp");
801                         break;
802                         
803                 default:
804                         if (rv3d->persp == RV3D_CAMOB) {
805                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
806                                         Camera *cam;
807                                         cam = v3d->camera->data;
808                                         if (cam->type == CAM_PERSP) {
809                                                 name = IFACE_("Camera Persp");
810                                         }
811                                         else if (cam->type == CAM_ORTHO) {
812                                                 name = IFACE_("Camera Ortho");
813                                         }
814                                         else {
815                                                 BLI_assert(cam->type == CAM_PANO);
816                                                 name = IFACE_("Camera Pano");
817                                         }
818                                 }
819                                 else {
820                                         name = IFACE_("Object as Camera");
821                                 }
822                         }
823                         else {
824                                 name = (rv3d->persp == RV3D_ORTHO) ? IFACE_("User Ortho") : IFACE_("User Persp");
825                         }
826                         break;
827         }
828         
829         return name;
830 }
831
832 static void draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
833 {
834         RegionView3D *rv3d = ar->regiondata;
835         const char *name = view3d_get_name(v3d, rv3d);
836         /* increase size for unicode languages (Chinese in utf-8...) */
837 #ifdef WITH_INTERNATIONAL
838         char tmpstr[96];
839 #else
840         char tmpstr[32];
841 #endif
842
843         if (v3d->localvd) {
844                 BLI_snprintf(tmpstr, sizeof(tmpstr), IFACE_("%s (Local)"), name);
845                 name = tmpstr;
846         }
847
848         UI_ThemeColor(TH_TEXT_HI);
849 #ifdef WITH_INTERNATIONAL
850         BLF_draw_default(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
851 #else
852         BLF_draw_default_ascii(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
853 #endif
854 }
855
856 /* draw info beside axes in bottom left-corner: 
857  * framenum, object name, bone name (if available), marker name (if available)
858  */
859
860 static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
861 {
862         const int cfra = CFRA;
863         const char *msg_pin = " (Pinned)";
864         const char *msg_sep = " : ";
865
866         char info[300];
867         const char *markern;
868         char *s = info;
869         short offset = 1.5f * UI_UNIT_X + rect->xmin;
870
871         s += sprintf(s, "(%d)", cfra);
872
873         /* 
874          * info can contain:
875          * - a frame (7 + 2)
876          * - 3 object names (MAX_NAME)
877          * - 2 BREAD_CRUMB_SEPARATORs (6)
878          * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
879          * - a marker name (MAX_NAME + 3)
880          */
881
882         /* get name of marker on current frame (if available) */
883         markern = BKE_scene_find_marker_name(scene, cfra);
884         
885         /* check if there is an object */
886         if (ob) {
887                 *s++ = ' ';
888                 s += BLI_strcpy_rlen(s, ob->id.name + 2);
889
890                 /* name(s) to display depends on type of object */
891                 if (ob->type == OB_ARMATURE) {
892                         bArmature *arm = ob->data;
893                         
894                         /* show name of active bone too (if possible) */
895                         if (arm->edbo) {
896                                 if (arm->act_edbone) {
897                                         s += BLI_strcpy_rlen(s, msg_sep);
898                                         s += BLI_strcpy_rlen(s, arm->act_edbone->name);
899                                 }
900                         }
901                         else if (ob->mode & OB_MODE_POSE) {
902                                 if (arm->act_bone) {
903
904                                         if (arm->act_bone->layer & arm->layer) {
905                                                 s += BLI_strcpy_rlen(s, msg_sep);
906                                                 s += BLI_strcpy_rlen(s, arm->act_bone->name);
907                                         }
908                                 }
909                         }
910                 }
911                 else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
912                         Key *key = NULL;
913                         KeyBlock *kb = NULL;
914
915                         /* try to display active bone and active shapekey too (if they exist) */
916
917                         if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
918                                 Object *armobj = BKE_object_pose_armature_get(ob);
919                                 if (armobj  && armobj->mode & OB_MODE_POSE) {
920                                         bArmature *arm = armobj->data;
921                                         if (arm->act_bone) {
922                                                 if (arm->act_bone->layer & arm->layer) {
923                                                         s += BLI_strcpy_rlen(s, msg_sep);
924                                                         s += BLI_strcpy_rlen(s, arm->act_bone->name);
925                                                 }
926                                         }
927                                 }
928                         }
929
930                         key = BKE_key_from_object(ob);
931                         if (key) {
932                                 kb = BLI_findlink(&key->block, ob->shapenr - 1);
933                                 if (kb) {
934                                         s += BLI_strcpy_rlen(s, msg_sep);
935                                         s += BLI_strcpy_rlen(s, kb->name);
936                                         if (ob->shapeflag & OB_SHAPE_LOCK) {
937                                                 s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
938                                         }
939                                 }
940                         }
941                 }
942                 
943                 /* color depends on whether there is a keyframe */
944                 if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
945                         UI_ThemeColor(TH_TIME_KEYFRAME);
946                 else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
947                         UI_ThemeColor(TH_TIME_GP_KEYFRAME);
948                 else
949                         UI_ThemeColor(TH_TEXT_HI);
950         }
951         else {
952                 /* no object */         
953                 /* color is always white */
954                 UI_ThemeColor(TH_TEXT_HI);
955         }
956
957         if (markern) {
958                 s += sprintf(s, " <%s>", markern);
959         }
960         
961         if (U.uiflag & USER_SHOW_ROTVIEWICON)
962                 offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
963
964         BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
965 }
966
967 static void view3d_camera_border(
968         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
969         rctf *r_viewborder, const bool no_shift, const bool no_zoom)
970 {
971         CameraParams params;
972         rctf rect_view, rect_camera;
973
974         /* get viewport viewplane */
975         BKE_camera_params_init(&params);
976         BKE_camera_params_from_view3d(&params, v3d, rv3d);
977         if (no_zoom)
978                 params.zoom = 1.0f;
979         BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
980         rect_view = params.viewplane;
981
982         /* get camera viewplane */
983         BKE_camera_params_init(&params);
984         /* fallback for non camera objects */
985         params.clipsta = v3d->near;
986         params.clipend = v3d->far;
987         BKE_camera_params_from_object(&params, v3d->camera);
988         if (no_shift) {
989                 params.shiftx = 0.0f;
990                 params.shifty = 0.0f;
991         }
992         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
993         rect_camera = params.viewplane;
994
995         /* get camera border within viewport */
996         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
997         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
998         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
999         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
1000 }
1001
1002 void ED_view3d_calc_camera_border_size(
1003         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
1004         float r_size[2])
1005 {
1006         rctf viewborder;
1007
1008         view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
1009         r_size[0] = BLI_rctf_size_x(&viewborder);
1010         r_size[1] = BLI_rctf_size_y(&viewborder);
1011 }
1012
1013 void ED_view3d_calc_camera_border(
1014         const Scene *scene, const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
1015         rctf *r_viewborder, const bool no_shift)
1016 {
1017         view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
1018 }
1019
1020 static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac)
1021 {
1022         float x3, y3, x4, y4;
1023
1024         x3 = x1 + fac * (x2 - x1);
1025         y3 = y1 + fac * (y2 - y1);
1026         x4 = x1 + (1.0f - fac) * (x2 - x1);
1027         y4 = y1 + (1.0f - fac) * (y2 - y1);
1028
1029         glBegin(GL_LINES);
1030         glVertex2f(x1, y3);
1031         glVertex2f(x2, y3);
1032
1033         glVertex2f(x1, y4);
1034         glVertex2f(x2, y4);
1035
1036         glVertex2f(x3, y1);
1037         glVertex2f(x3, y2);
1038
1039         glVertex2f(x4, y1);
1040         glVertex2f(x4, y2);
1041         glEnd();
1042 }
1043
1044 /* harmonious triangle */
1045 static void drawviewborder_triangle(float x1, float x2, float y1, float y2, const char golden, const char dir)
1046 {
1047         float ofs;
1048         float w = x2 - x1;
1049         float h = y2 - y1;
1050
1051         glBegin(GL_LINES);
1052         if (w > h) {
1053                 if (golden) {
1054                         ofs = w * (1.0f - (1.0f / 1.61803399f));
1055                 }
1056                 else {
1057                         ofs = h * (h / w);
1058                 }
1059                 if (dir == 'B') SWAP(float, y1, y2);
1060
1061                 glVertex2f(x1, y1);
1062                 glVertex2f(x2, y2);
1063
1064                 glVertex2f(x2, y1);
1065                 glVertex2f(x1 + (w - ofs), y2);
1066
1067                 glVertex2f(x1, y2);
1068                 glVertex2f(x1 + ofs, y1);
1069         }
1070         else {
1071                 if (golden) {
1072                         ofs = h * (1.0f - (1.0f / 1.61803399f));
1073                 }
1074                 else {
1075                         ofs = w * (w / h);
1076                 }
1077                 if (dir == 'B') SWAP(float, x1, x2);
1078
1079                 glVertex2f(x1, y1);
1080                 glVertex2f(x2, y2);
1081
1082                 glVertex2f(x2, y1);
1083                 glVertex2f(x1, y1 + ofs);
1084
1085                 glVertex2f(x1, y2);
1086                 glVertex2f(x2, y1 + (h - ofs));
1087         }
1088         glEnd();
1089 }
1090
1091 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
1092 {
1093         float x1, x2, y1, y2;
1094         float x1i, x2i, y1i, y2i;
1095
1096         rctf viewborder;
1097         Camera *ca = NULL;
1098         RegionView3D *rv3d = ar->regiondata;
1099
1100         if (v3d->camera == NULL)
1101                 return;
1102         if (v3d->camera->type == OB_CAMERA)
1103                 ca = v3d->camera->data;
1104         
1105         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1106         /* the offsets */
1107         x1 = viewborder.xmin;
1108         y1 = viewborder.ymin;
1109         x2 = viewborder.xmax;
1110         y2 = viewborder.ymax;
1111         
1112         glLineWidth(1.0f);
1113
1114         /* apply offsets so the real 3D camera shows through */
1115
1116         /* note: quite un-scientific but without this bit extra
1117          * 0.0001 on the lower left the 2D border sometimes
1118          * obscures the 3D camera border */
1119         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
1120          * but keep it here in case we need to remove the workaround */
1121         x1i = (int)(x1 - 1.0001f);
1122         y1i = (int)(y1 - 1.0001f);
1123         x2i = (int)(x2 + (1.0f - 0.0001f));
1124         y2i = (int)(y2 + (1.0f - 0.0001f));
1125         
1126         /* passepartout, specified in camera edit buttons */
1127         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
1128                 const float winx = (ar->winx + 1);
1129                 const float winy = (ar->winy + 1);
1130
1131                 if (ca->passepartalpha == 1.0f) {
1132                         glColor3f(0, 0, 0);
1133                 }
1134                 else {
1135                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1136                         glEnable(GL_BLEND);
1137                         glColor4f(0, 0, 0, ca->passepartalpha);
1138                 }
1139
1140                 if (x1i > 0.0f)
1141                         glRectf(0.0, winy, x1i, 0.0);
1142                 if (x2i < winx)
1143                         glRectf(x2i, winy, winx, 0.0);
1144                 if (y2i < winy)
1145                         glRectf(x1i, winy, x2i, y2i);
1146                 if (y2i > 0.0f)
1147                         glRectf(x1i, y1i, x2i, 0.0);
1148                 
1149                 glDisable(GL_BLEND);
1150         }
1151
1152         setlinestyle(0);
1153
1154         UI_ThemeColor(TH_BACK);
1155                 
1156         fdrawbox(x1i, y1i, x2i, y2i);
1157
1158 #ifdef VIEW3D_CAMERA_BORDER_HACK
1159         if (view3d_camera_border_hack_test == true) {
1160                 glColor3ubv(view3d_camera_border_hack_col);
1161                 fdrawbox(x1i + 1, y1i + 1, x2i - 1, y2i - 1);
1162                 view3d_camera_border_hack_test = false;
1163         }
1164 #endif
1165
1166         setlinestyle(3);
1167
1168         /* outer line not to confuse with object selecton */
1169         if (v3d->flag2 & V3D_LOCK_CAMERA) {
1170                 UI_ThemeColor(TH_REDALERT);
1171                 fdrawbox(x1i - 1, y1i - 1, x2i + 1, y2i + 1);
1172         }
1173
1174         UI_ThemeColor(TH_VIEW_OVERLAY);
1175         fdrawbox(x1i, y1i, x2i, y2i);
1176
1177         /* border */
1178         if (scene->r.mode & R_BORDER) {
1179                 float x3, y3, x4, y4;
1180
1181                 x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
1182                 y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
1183                 x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
1184                 y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
1185
1186                 cpack(0x4040FF);
1187                 sdrawbox(x3,  y3,  x4,  y4);
1188         }
1189
1190         /* safety border */
1191         if (ca) {
1192                 if (ca->dtx & CAM_DTX_CENTER) {
1193                         float x3, y3;
1194
1195                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1196
1197                         x3 = x1 + 0.5f * (x2 - x1);
1198                         y3 = y1 + 0.5f * (y2 - y1);
1199
1200                         glBegin(GL_LINES);
1201                         glVertex2f(x1, y3);
1202                         glVertex2f(x2, y3);
1203
1204                         glVertex2f(x3, y1);
1205                         glVertex2f(x3, y2);
1206                         glEnd();
1207                 }
1208
1209                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
1210                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1211
1212                         glBegin(GL_LINES);
1213                         glVertex2f(x1, y1);
1214                         glVertex2f(x2, y2);
1215
1216                         glVertex2f(x1, y2);
1217                         glVertex2f(x2, y1);
1218                         glEnd();
1219                 }
1220
1221                 if (ca->dtx & CAM_DTX_THIRDS) {
1222                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1223                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f / 3.0f);
1224                 }
1225
1226                 if (ca->dtx & CAM_DTX_GOLDEN) {
1227                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1228                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
1229                 }
1230
1231                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
1232                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1233                         drawviewborder_triangle(x1, x2, y1, y2, 0, 'A');
1234                 }
1235
1236                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
1237                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1238                         drawviewborder_triangle(x1, x2, y1, y2, 0, 'B');
1239                 }
1240
1241                 if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
1242                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1243                         drawviewborder_triangle(x1, x2, y1, y2, 1, 'A');
1244                 }
1245
1246                 if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
1247                         UI_ThemeColorBlendShade(TH_VIEW_OVERLAY, TH_BACK, 0.25, 0);
1248                         drawviewborder_triangle(x1, x2, y1, y2, 1, 'B');
1249                 }
1250
1251                 if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
1252                         UI_draw_safe_areas(
1253                                 x1, x2, y1, y2,
1254                                 scene->safe_areas.title,
1255                                 scene->safe_areas.action);
1256
1257                         if (ca->flag & CAM_SHOW_SAFE_CENTER) {
1258                                 UI_draw_safe_areas(
1259                                         x1, x2, y1, y2,
1260                                         scene->safe_areas.title_center,
1261                                         scene->safe_areas.action_center);
1262                         }
1263                 }
1264
1265                 if (ca->flag & CAM_SHOWSENSOR) {
1266                         /* determine sensor fit, and get sensor x/y, for auto fit we
1267                          * assume and square sensor and only use sensor_x */
1268                         float sizex = scene->r.xsch * scene->r.xasp;
1269                         float sizey = scene->r.ysch * scene->r.yasp;
1270                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
1271                         float sensor_x = ca->sensor_x;
1272                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
1273
1274                         /* determine sensor plane */
1275                         rctf rect;
1276
1277                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
1278                                 float sensor_scale = (x2i - x1i) / sensor_x;
1279                                 float sensor_height = sensor_scale * sensor_y;
1280
1281                                 rect.xmin = x1i;
1282                                 rect.xmax = x2i;
1283                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
1284                                 rect.ymax = rect.ymin + sensor_height;
1285                         }
1286                         else {
1287                                 float sensor_scale = (y2i - y1i) / sensor_y;
1288                                 float sensor_width = sensor_scale * sensor_x;
1289
1290                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
1291                                 rect.xmax = rect.xmin + sensor_width;
1292                                 rect.ymin = y1i;
1293                                 rect.ymax = y2i;
1294                         }
1295
1296                         /* draw */
1297                         UI_ThemeColorShade(TH_VIEW_OVERLAY, 100);
1298                         UI_draw_roundbox_gl_mode(GL_LINE_LOOP, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f);
1299                 }
1300         }
1301
1302         setlinestyle(0);
1303
1304         /* camera name - draw in highlighted text color */
1305         if (ca && (ca->flag & CAM_SHOWNAME)) {
1306                 UI_ThemeColor(TH_TEXT_HI);
1307                 BLF_draw_default(
1308                         x1i, y1i - (0.7f * U.widget_unit), 0.0f,
1309                         v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
1310         }
1311 }
1312
1313 /* *********************** backdraw for selection *************** */
1314
1315 static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d)
1316 {
1317         RegionView3D *rv3d = ar->regiondata;
1318         struct Base *base = scene->basact;
1319         int multisample_enabled;
1320
1321         BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
1322
1323         if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
1324                      BKE_paint_select_face_test(base->object)))
1325         {
1326                 /* do nothing */
1327         }
1328         /* texture paint mode sampling */
1329         else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
1330                  (v3d->drawtype > OB_WIRE))
1331         {
1332                 /* do nothing */
1333         }
1334         else if (scene->obedit &&
1335                  V3D_IS_ZBUF(v3d))
1336         {
1337                 /* do nothing */
1338         }
1339         else {
1340                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1341                 return;
1342         }
1343
1344         if (!(v3d->flag & V3D_INVALID_BACKBUF))
1345                 return;
1346
1347 #if 0
1348         if (test) {
1349                 if (qtest()) {
1350                         addafterqueue(ar->win, BACKBUFDRAW, 1);
1351                         return;
1352                 }
1353         }
1354 #endif
1355
1356         if (v3d->drawtype > OB_WIRE) v3d->zbuf = true;
1357         
1358         /* dithering and AA break color coding, so disable */
1359         glDisable(GL_DITHER);
1360
1361         multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
1362         if (multisample_enabled)
1363                 glDisable(GL_MULTISAMPLE);
1364
1365         if (win->multisamples != USER_MULTISAMPLE_NONE) {
1366                 /* for multisample we use an offscreen FBO. multisample drawing can fail
1367                  * with color coded selection drawing, and reading back depths from such
1368                  * a buffer can also cause a few seconds freeze on OS X / NVidia. */
1369                 int w = BLI_rcti_size_x(&ar->winrct);
1370                 int h = BLI_rcti_size_y(&ar->winrct);
1371                 char error[256];
1372
1373                 if (rv3d->gpuoffscreen) {
1374                         if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
1375                             GPU_offscreen_height(rv3d->gpuoffscreen) != h)
1376                         {
1377                                 GPU_offscreen_free(rv3d->gpuoffscreen);
1378                                 rv3d->gpuoffscreen = NULL;
1379                         }
1380                 }
1381
1382                 if (!rv3d->gpuoffscreen) {
1383                         rv3d->gpuoffscreen = GPU_offscreen_create(w, h, 0, error);
1384
1385                         if (!rv3d->gpuoffscreen)
1386                                 fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
1387                 }
1388         }
1389
1390         if (rv3d->gpuoffscreen)
1391                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
1392         else
1393                 glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
1394
1395         glClearColor(0.0, 0.0, 0.0, 0.0);
1396         if (v3d->zbuf) {
1397                 glEnable(GL_DEPTH_TEST);
1398                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1399         }
1400         else {
1401                 glClear(GL_COLOR_BUFFER_BIT);
1402                 glDisable(GL_DEPTH_TEST);
1403         }
1404         
1405         if (rv3d->rflag & RV3D_CLIPPING)
1406                 ED_view3d_clipping_set(rv3d);
1407         
1408         G.f |= G_BACKBUFSEL;
1409         
1410         if (base && (base->lay & v3d->lay))
1411                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1412         
1413         if (rv3d->gpuoffscreen)
1414                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
1415         else
1416                 ar->swap = 0; /* mark invalid backbuf for wm draw */
1417
1418         v3d->flag &= ~V3D_INVALID_BACKBUF;
1419
1420         G.f &= ~G_BACKBUFSEL;
1421         v3d->zbuf = false;
1422         glDisable(GL_DEPTH_TEST);
1423         glEnable(GL_DITHER);
1424         if (multisample_enabled)
1425                 glEnable(GL_MULTISAMPLE);
1426
1427         if (rv3d->rflag & RV3D_CLIPPING)
1428                 ED_view3d_clipping_disable();
1429 }
1430
1431 void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
1432 {
1433         RegionView3D *rv3d = ar->regiondata;
1434
1435         if (rv3d->gpuoffscreen) {
1436                 GPU_offscreen_bind(rv3d->gpuoffscreen, true);
1437                 glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
1438                 glReadPixels(x, y, w, h, format, type, data);
1439                 GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
1440         }
1441         else {
1442                 glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
1443         }
1444 }
1445
1446 /* XXX depth reading exception, for code not using gpu offscreen */
1447 static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
1448 {
1449
1450         glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
1451 }
1452
1453 void ED_view3d_backbuf_validate(ViewContext *vc)
1454 {
1455         if (vc->v3d->flag & V3D_INVALID_BACKBUF)
1456                 backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d);
1457 }
1458
1459 /**
1460  * allow for small values [0.5 - 2.5],
1461  * and large values, FLT_MAX by clamping by the area size
1462  */
1463 int ED_view3d_backbuf_sample_size_clamp(ARegion *ar, const float dist)
1464 {
1465         return (int)min_ff(ceilf(dist), (float)max_ii(ar->winx, ar->winx));
1466 }
1467
1468 /* samples a single pixel (copied from vpaint) */
1469 unsigned int ED_view3d_backbuf_sample(ViewContext *vc, int x, int y)
1470 {
1471         unsigned int col;
1472         
1473         if (x >= vc->ar->winx || y >= vc->ar->winy) {
1474                 return 0;
1475         }
1476
1477         ED_view3d_backbuf_validate(vc);
1478
1479         view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
1480         glReadBuffer(GL_BACK);
1481         
1482         if (ENDIAN_ORDER == B_ENDIAN) {
1483                 BLI_endian_switch_uint32(&col);
1484         }
1485         
1486         return GPU_select_to_index(col);
1487 }
1488
1489 /* reads full rect, converts indices */
1490 ImBuf *ED_view3d_backbuf_read(ViewContext *vc, int xmin, int ymin, int xmax, int ymax)
1491 {
1492         struct ImBuf *ibuf_clip;
1493         /* clip */
1494         const rcti clip = {
1495             max_ii(xmin, 0), min_ii(xmax, vc->ar->winx - 1),
1496             max_ii(ymin, 0), min_ii(ymax, vc->ar->winy - 1)};
1497         const int size_clip[2] = {
1498             BLI_rcti_size_x(&clip) + 1,
1499             BLI_rcti_size_y(&clip) + 1};
1500
1501         if (UNLIKELY((clip.xmin > clip.xmax) ||
1502                      (clip.ymin > clip.ymax)))
1503         {
1504                 return NULL;
1505         }
1506
1507         ibuf_clip = IMB_allocImBuf(size_clip[0], size_clip[1], 32, IB_rect);
1508
1509         ED_view3d_backbuf_validate(vc);
1510
1511         view3d_opengl_read_pixels(vc->ar, clip.xmin, clip.ymin, size_clip[0], size_clip[1], GL_RGBA, GL_UNSIGNED_BYTE, ibuf_clip->rect);
1512
1513         glReadBuffer(GL_BACK);
1514
1515         if (ENDIAN_ORDER == B_ENDIAN) {
1516                 IMB_convert_rgba_to_abgr(ibuf_clip);
1517         }
1518
1519         GPU_select_to_index_array(ibuf_clip->rect, size_clip[0] * size_clip[1]);
1520         
1521         if ((clip.xmin == xmin) &&
1522             (clip.xmax == xmax) &&
1523             (clip.ymin == ymin) &&
1524             (clip.ymax == ymax))
1525         {
1526                 return ibuf_clip;
1527         }
1528         else {
1529                 /* put clipped result into a non-clipped buffer */
1530                 struct ImBuf *ibuf_full;
1531                 const int size[2] = {
1532                     (xmax - xmin + 1),
1533                     (ymax - ymin + 1)};
1534
1535                 ibuf_full = IMB_allocImBuf(size[0], size[1], 32, IB_rect);
1536
1537                 IMB_rectcpy(
1538                         ibuf_full, ibuf_clip,
1539                         clip.xmin - xmin, clip.ymin - ymin,
1540                         0, 0,
1541                         size_clip[0], size_clip[1]);
1542                 IMB_freeImBuf(ibuf_clip);
1543                 return ibuf_full;
1544         }
1545 }
1546
1547 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1548 unsigned int ED_view3d_backbuf_sample_rect(
1549         ViewContext *vc, const int mval[2], int size,
1550         unsigned int min, unsigned int max, float *r_dist)
1551 {
1552         struct ImBuf *buf;
1553         const unsigned int *bufmin, *bufmax, *tbuf;
1554         int minx, miny;
1555         int a, b, rc, nr, amount, dirvec[4][2];
1556         unsigned int index = 0;
1557
1558         amount = (size - 1) / 2;
1559
1560         minx = mval[0] - (amount + 1);
1561         miny = mval[1] - (amount + 1);
1562         buf = ED_view3d_backbuf_read(vc, minx, miny, minx + size - 1, miny + size - 1);
1563         if (!buf) return 0;
1564
1565         rc = 0;
1566         
1567         dirvec[0][0] = 1; dirvec[0][1] = 0;
1568         dirvec[1][0] = 0; dirvec[1][1] = -size;
1569         dirvec[2][0] = -1; dirvec[2][1] = 0;
1570         dirvec[3][0] = 0; dirvec[3][1] = size;
1571         
1572         bufmin = buf->rect;
1573         tbuf = buf->rect;
1574         bufmax = buf->rect + size * size;
1575         tbuf += amount * size + amount;
1576         
1577         for (nr = 1; nr <= size; nr++) {
1578                 
1579                 for (a = 0; a < 2; a++) {
1580                         for (b = 0; b < nr; b++) {
1581                                 if (*tbuf && *tbuf >= min && *tbuf < max) {
1582                                         /* we got a hit */
1583
1584                                         /* get x,y pixel coords from the offset
1585                                          * (manhatten distance in keeping with other screen-based selection) */
1586                                         *r_dist = (float)(
1587                                                 abs(((int)(tbuf - buf->rect) % size) - (size / 2)) +
1588                                                 abs(((int)(tbuf - buf->rect) / size) - (size / 2)));
1589
1590                                         /* indices start at 1 here */
1591                                         index = (*tbuf - min) + 1;
1592                                         goto exit;
1593                                 }
1594                                 
1595                                 tbuf += (dirvec[rc][0] + dirvec[rc][1]);
1596                                 
1597                                 if (tbuf < bufmin || tbuf >= bufmax) {
1598                                         goto exit;
1599                                 }
1600                         }
1601                         rc++;
1602                         rc &= 3;
1603                 }
1604         }
1605
1606 exit:
1607         IMB_freeImBuf(buf);
1608         return index;
1609 }
1610
1611
1612 /* ************************************************************* */
1613
1614 static void view3d_stereo_bgpic_setup(Scene *scene, View3D *v3d, Image *ima, ImageUser *iuser)
1615 {
1616         if (BKE_image_is_stereo(ima)) {
1617                 iuser->flag |= IMA_SHOW_STEREO;
1618
1619                 if ((scene->r.scemode & R_MULTIVIEW) == 0) {
1620                         iuser->multiview_eye = STEREO_LEFT_ID;
1621                 }
1622                 else if (v3d->stereo3d_camera != STEREO_3D_ID) {
1623                         /* show only left or right camera */
1624                         iuser->multiview_eye = v3d->stereo3d_camera;
1625                 }
1626
1627                 BKE_image_multiview_index(ima, iuser);
1628         }
1629         else {
1630                 iuser->flag &= ~IMA_SHOW_STEREO;
1631         }
1632 }
1633
1634 static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
1635                               const bool do_foreground, const bool do_camera_frame)
1636 {
1637         RegionView3D *rv3d = ar->regiondata;
1638         BGpic *bgpic;
1639         int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
1640
1641         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1642                 bgpic->iuser.scene = scene;  /* Needed for render results. */
1643
1644                 if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
1645                         continue;
1646
1647                 if ((bgpic->view == 0) || /* zero for any */
1648                     (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
1649                     (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
1650                 {
1651                         float image_aspect[2];
1652                         float fac, asp, zoomx, zoomy;
1653                         float x1, y1, x2, y2, centx, centy;
1654
1655                         ImBuf *ibuf = NULL, *freeibuf, *releaseibuf;
1656                         void *lock;
1657                         rctf clip_rect;
1658
1659                         Image *ima = NULL;
1660                         MovieClip *clip = NULL;
1661
1662                         /* disable individual images */
1663                         if ((bgpic->flag & V3D_BGPIC_DISABLED))
1664                                 continue;
1665
1666                         freeibuf = NULL;
1667                         releaseibuf = NULL;
1668                         if (bgpic->source == V3D_BGPIC_IMAGE) {
1669                                 ima = bgpic->ima;
1670                                 if (ima == NULL)
1671                                         continue;
1672                                 BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
1673                                 if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
1674                                         ibuf = NULL; /* frame is out of range, dont show */
1675                                 }
1676                                 else {
1677                                         view3d_stereo_bgpic_setup(scene, v3d, ima, &bgpic->iuser);
1678                                         ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, &lock);
1679                                         releaseibuf = ibuf;
1680                                 }
1681
1682                                 image_aspect[0] = ima->aspx;
1683                                 image_aspect[1] = ima->aspy;
1684                         }
1685                         else if (bgpic->source == V3D_BGPIC_MOVIE) {
1686                                 /* TODO: skip drawing when out of frame range (as image sequences do above) */
1687
1688                                 if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
1689                                         if (scene->camera)
1690                                                 clip = BKE_object_movieclip_get(scene, scene->camera, true);
1691                                 }
1692                                 else {
1693                                         clip = bgpic->clip;
1694                                 }
1695
1696                                 if (clip == NULL)
1697                                         continue;
1698
1699                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
1700                                 ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
1701
1702                                 image_aspect[0] = clip->aspx;
1703                                 image_aspect[1] = clip->aspy;
1704
1705                                 /* working with ibuf from image and clip has got different workflow now.
1706                                  * ibuf acquired from clip is referenced by cache system and should
1707                                  * be dereferenced after usage. */
1708                                 freeibuf = ibuf;
1709                         }
1710                         else {
1711                                 /* perhaps when loading future files... */
1712                                 BLI_assert(0);
1713                                 copy_v2_fl(image_aspect, 1.0f);
1714                         }
1715
1716                         if (ibuf == NULL)
1717                                 continue;
1718
1719                         if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
1720                                 if (freeibuf)
1721                                         IMB_freeImBuf(freeibuf);
1722                                 if (releaseibuf)
1723                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
1724
1725                                 continue;
1726                         }
1727
1728                         if (ibuf->rect == NULL)
1729                                 IMB_rect_from_float(ibuf);
1730
1731                         if (rv3d->persp == RV3D_CAMOB) {
1732
1733                                 if (do_camera_frame) {
1734                                         rctf vb;
1735                                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
1736                                         x1 = vb.xmin;
1737                                         y1 = vb.ymin;
1738                                         x2 = vb.xmax;
1739                                         y2 = vb.ymax;
1740                                 }
1741                                 else {
1742                                         x1 = ar->winrct.xmin;
1743                                         y1 = ar->winrct.ymin;
1744                                         x2 = ar->winrct.xmax;
1745                                         y2 = ar->winrct.ymax;
1746                                 }
1747
1748                                 /* apply offset last - camera offset is different to offset in blender units */
1749                                 /* so this has some sane way of working - this matches camera's shift _exactly_ */
1750                                 {
1751                                         const float max_dim = max_ff(x2 - x1, y2 - y1);
1752                                         const float xof_scale = bgpic->xof * max_dim;
1753                                         const float yof_scale = bgpic->yof * max_dim;
1754
1755                                         x1 += xof_scale;
1756                                         y1 += yof_scale;
1757                                         x2 += xof_scale;
1758                                         y2 += yof_scale;
1759                                 }
1760
1761                                 centx = (x1 + x2) / 2.0f;
1762                                 centy = (y1 + y2) / 2.0f;
1763
1764                                 /* aspect correction */
1765                                 if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
1766                                         /* apply aspect from clip */
1767                                         const float w_src = ibuf->x * image_aspect[0];
1768                                         const float h_src = ibuf->y * image_aspect[1];
1769
1770                                         /* destination aspect is already applied from the camera frame */
1771                                         const float w_dst = x1 - x2;
1772                                         const float h_dst = y1 - y2;
1773
1774                                         const float asp_src = w_src / h_src;
1775                                         const float asp_dst = w_dst / h_dst;
1776
1777                                         if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
1778                                                 if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
1779                                                         /* fit X */
1780                                                         const float div = asp_src / asp_dst;
1781                                                         x1 = ((x1 - centx) * div) + centx;
1782                                                         x2 = ((x2 - centx) * div) + centx;
1783                                                 }
1784                                                 else {
1785                                                         /* fit Y */
1786                                                         const float div = asp_dst / asp_src;
1787                                                         y1 = ((y1 - centy) * div) + centy;
1788                                                         y2 = ((y2 - centy) * div) + centy;
1789                                                 }
1790                                         }
1791                                 }
1792                         }
1793                         else {
1794                                 float tvec[3];
1795                                 float sco[2];
1796                                 const float mval_f[2] = {1.0f, 0.0f};
1797                                 const float co_zero[3] = {0};
1798                                 float zfac;
1799
1800                                 /* calc window coord */
1801                                 zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
1802                                 ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
1803                                 fac = max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
1804                                 fac = 1.0f / fac;
1805
1806                                 asp = (float)ibuf->y / (float)ibuf->x;
1807
1808                                 zero_v3(tvec);
1809                                 ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
1810
1811                                 x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
1812                                 y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
1813                                 x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
1814                                 y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
1815
1816                                 centx = (x1 + x2) / 2.0f;
1817                                 centy = (y1 + y2) / 2.0f;
1818                         }
1819
1820                         /* complete clip? */
1821                         BLI_rctf_init(&clip_rect, x1, x2, y1, y2);
1822                         if (bgpic->rotation) {
1823                                 BLI_rctf_rotate_expand(&clip_rect, &clip_rect, bgpic->rotation);
1824                         }
1825
1826                         if (clip_rect.xmax < 0 || clip_rect.ymax < 0 || clip_rect.xmin > ar->winx || clip_rect.ymin > ar->winy) {
1827                                 if (freeibuf)
1828                                         IMB_freeImBuf(freeibuf);
1829                                 if (releaseibuf)
1830                                         BKE_image_release_ibuf(ima, releaseibuf, lock);
1831
1832                                 continue;
1833                         }
1834
1835                         zoomx = (x2 - x1) / ibuf->x;
1836                         zoomy = (y2 - y1) / ibuf->y;
1837
1838                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1839                         if (zoomx < 1.0f || zoomy < 1.0f) {
1840                                 float tzoom = min_ff(zoomx, zoomy);
1841                                 int mip = 0;
1842
1843                                 if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
1844                                         IMB_remakemipmap(ibuf, 0);
1845                                         ibuf->userflags &= ~IB_MIPMAP_INVALID;
1846                                 }
1847                                 else if (ibuf->mipmap[0] == NULL)
1848                                         IMB_makemipmap(ibuf, 0);
1849
1850                                 while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
1851                                         tzoom *= 2.0f;
1852                                         zoomx *= 2.0f;
1853                                         zoomy *= 2.0f;
1854                                         mip++;
1855                                 }
1856                                 if (mip > 0)
1857                                         ibuf = ibuf->mipmap[mip - 1];
1858                         }
1859
1860                         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1861                         glDepthMask(0);
1862
1863                         glEnable(GL_BLEND);
1864                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1865
1866                         glMatrixMode(GL_PROJECTION);
1867                         glPushMatrix();
1868                         glMatrixMode(GL_MODELVIEW);
1869                         glPushMatrix();
1870                         ED_region_pixelspace(ar);
1871
1872                         glTranslatef(centx, centy, 0.0);
1873                         glRotatef(RAD2DEGF(-bgpic->rotation), 0.0f, 0.0f, 1.0f);
1874
1875                         if (bgpic->flag & V3D_BGPIC_FLIP_X) {
1876                                 zoomx *= -1.0f;
1877                                 x1 = x2;
1878                         }
1879                         if (bgpic->flag & V3D_BGPIC_FLIP_Y) {
1880                                 zoomy *= -1.0f;
1881                                 y1 = y2;
1882                         }
1883                         glPixelZoom(zoomx, zoomy);
1884                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
1885
1886                         /* could not use glaDrawPixelsAuto because it could fallback to
1887                          * glaDrawPixelsSafe in some cases, which will end up in missing
1888                          * alpha transparency for the background image (sergey)
1889                          */
1890                         glaDrawPixelsTex(x1 - centx, y1 - centy, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect);
1891
1892                         glPixelZoom(1.0, 1.0);
1893                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1894
1895                         glMatrixMode(GL_PROJECTION);
1896                         glPopMatrix();
1897                         glMatrixMode(GL_MODELVIEW);
1898                         glPopMatrix();
1899
1900                         glDisable(GL_BLEND);
1901
1902                         glDepthMask(1);
1903                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1904
1905                         if (freeibuf)
1906                                 IMB_freeImBuf(freeibuf);
1907                         if (releaseibuf)
1908                                 BKE_image_release_ibuf(ima, releaseibuf, lock);
1909                 }
1910         }
1911 }
1912
1913 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
1914                                    const bool do_foreground, const bool do_camera_frame)
1915 {
1916         RegionView3D *rv3d = ar->regiondata;
1917
1918         if ((v3d->flag & V3D_DISPBGPICS) == 0)
1919                 return;
1920
1921         /* disabled - mango request, since footage /w only render is quite useful
1922          * and this option is easy to disable all background images at once */
1923 #if 0
1924         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
1925                 return;
1926 #endif
1927
1928         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
1929                 if (rv3d->persp == RV3D_CAMOB) {
1930                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1931                 }
1932         }
1933         else {
1934                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1935         }
1936 }
1937
1938 /* ****************** View3d afterdraw *************** */
1939
1940 typedef struct View3DAfter {
1941         struct View3DAfter *next, *prev;
1942         struct Base *base;
1943         short dflag;
1944 } View3DAfter;
1945
1946 /* temp storage of Objects that need to be drawn as last */
1947 void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
1948 {
1949         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
1950         BLI_assert((base->flag & OB_FROMDUPLI) == 0);
1951         BLI_addtail(lb, v3da);
1952         v3da->base = base;
1953         v3da->dflag = dflag;
1954 }
1955
1956 /* disables write in zbuffer and draws it over */
1957 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1958 {
1959         View3DAfter *v3da;
1960         
1961         glDepthMask(GL_FALSE);
1962         v3d->transp = true;
1963         
1964         while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
1965                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1966                 MEM_freeN(v3da);
1967         }
1968         v3d->transp = false;
1969         
1970         glDepthMask(GL_TRUE);
1971         
1972 }
1973
1974 /* clears zbuffer and draws it over */
1975 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
1976 {
1977         View3DAfter *v3da;
1978
1979         if (*clear && v3d->zbuf) {
1980                 glClear(GL_DEPTH_BUFFER_BIT);
1981                 *clear = false;
1982         }
1983
1984         v3d->xray = true;
1985         while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
1986                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1987                 MEM_freeN(v3da);
1988         }
1989         v3d->xray = false;
1990 }
1991
1992
1993 /* clears zbuffer and draws it over */
1994 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, const bool clear)
1995 {
1996         View3DAfter *v3da;
1997
1998         if (clear && v3d->zbuf)
1999                 glClear(GL_DEPTH_BUFFER_BIT);
2000
2001         v3d->xray = true;
2002         v3d->transp = true;
2003         
2004         glDepthMask(GL_FALSE);
2005
2006         while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
2007                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
2008                 MEM_freeN(v3da);
2009         }
2010
2011         v3d->transp = false;
2012         v3d->xray = false;
2013
2014         glDepthMask(GL_TRUE);
2015 }
2016
2017 /* *********************** */
2018
2019 /*
2020  * In most cases call draw_dupli_objects,
2021  * draw_dupli_objects_color was added because when drawing set dupli's
2022  * we need to force the color
2023  */
2024
2025 #if 0
2026 int dupli_ob_sort(void *arg1, void *arg2)
2027 {
2028         void *p1 = ((DupliObject *)arg1)->ob;
2029         void *p2 = ((DupliObject *)arg2)->ob;
2030         int val = 0;
2031         if (p1 < p2) val = -1;
2032         else if (p1 > p2) val = 1;
2033         return val;
2034 }
2035 #endif
2036
2037
2038 static DupliObject *dupli_step(DupliObject *dob)
2039 {
2040         while (dob && dob->no_draw)
2041                 dob = dob->next;
2042         return dob;
2043 }
2044
2045 static void draw_dupli_objects_color(
2046         Scene *scene, ARegion *ar, View3D *v3d, Base *base,
2047         const short dflag, const int color)
2048 {
2049         RegionView3D *rv3d = ar->regiondata;
2050         ListBase *lb;
2051         LodLevel *savedlod;
2052         DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
2053         Base tbase = {NULL};
2054         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
2055         GLuint displist = 0;
2056         unsigned char color_rgb[3];
2057         const short dflag_dupli = dflag | DRAW_CONSTCOLOR;
2058         short transflag;
2059         bool use_displist = false;  /* -1 is initialize */
2060         char dt;
2061         short dtx;
2062         DupliApplyData *apply_data;
2063
2064         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
2065         if ((base->object->restrictflag & OB_RESTRICT_RENDER) && (v3d->flag2 & V3D_RENDER_OVERRIDE)) return;
2066
2067         if (dflag & DRAW_CONSTCOLOR) {
2068                 BLI_assert(color == TH_UNDEFINED);
2069         }
2070         else {
2071                 UI_GetThemeColorBlend3ubv(color, TH_BACK, 0.5f, color_rgb);
2072         }
2073
2074         tbase.flag = OB_FROMDUPLI | base->flag;
2075         lb = object_duplilist(G.main->eval_ctx, scene, base->object);
2076         // BLI_listbase_sort(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
2077
2078         apply_data = duplilist_apply(base->object, scene, lb);
2079
2080         dob = dupli_step(lb->first);
2081         if (dob) dob_next = dupli_step(dob->next);
2082
2083         for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
2084                 bool testbb = false;
2085
2086                 tbase.object = dob->ob;
2087
2088                 /* Make sure lod is updated from dupli's position */
2089                 savedlod = dob->ob->currentlod;
2090
2091 #ifdef WITH_GAMEENGINE
2092                 if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
2093                         BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
2094                 }
2095 #endif
2096
2097                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
2098                  * to allow e.g. boundbox box objects in groups for LOD */
2099                 dt = tbase.object->dt;
2100                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
2101
2102                 /* inherit draw extra, but not if a boundbox under the assumption that this
2103                  * is intended to speed up drawing, and drawing extra (especially wire) can
2104                  * slow it down too much */
2105                 dtx = tbase.object->dtx;
2106                 if (tbase.object->dt != OB_BOUNDBOX)
2107                         tbase.object->dtx = base->object->dtx;
2108
2109                 /* negative scale flag has to propagate */
2110                 transflag = tbase.object->transflag;
2111
2112                 if (is_negative_m4(dob->mat))
2113                         tbase.object->transflag |= OB_NEG_SCALE;
2114                 else
2115                         tbase.object->transflag &= ~OB_NEG_SCALE;
2116                 
2117                 /* should move outside the loop but possible color is set in draw_object still */
2118                 if ((dflag & DRAW_CONSTCOLOR) == 0) {
2119                         glColor3ubv(color_rgb);
2120                 }
2121                 
2122                 /* generate displist, test for new object */
2123                 if (dob_prev && dob_prev->ob != dob->ob) {
2124                         if (use_displist == true)
2125                                 glDeleteLists(displist, 1);
2126                         
2127                         use_displist = false;
2128                 }
2129                 
2130                 if ((bb_tmp = BKE_object_boundbox_get(dob->ob))) {
2131                         bb = *bb_tmp; /* must make a copy  */
2132                         testbb = true;
2133                 }
2134
2135                 if (!testbb || ED_view3d_boundbox_clip_ex(rv3d, &bb, dob->mat)) {
2136                         /* generate displist */
2137                         if (use_displist == false) {
2138                                 
2139                                 /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
2140                                  * however this is very slow, it was probably needed for the NLA
2141                                  * offset feature (used in group-duplicate.blend but no longer works in 2.5)
2142                                  * so for now it should be ok to - campbell */
2143                                 
2144                                 if ( /* if this is the last no need  to make a displist */
2145                                      (dob_next == NULL || dob_next->ob != dob->ob) ||
2146                                      /* lamp drawing messes with matrices, could be handled smarter... but this works */
2147                                      (dob->ob->type == OB_LAMP) ||
2148                                      (dob->type == OB_DUPLIGROUP && dob->animated) ||
2149                                      !bb_tmp ||
2150                                      draw_glsl_material(scene, dob->ob, v3d, dt) ||
2151                                      check_object_draw_texture(scene, v3d, dt) ||
2152                                      (v3d->flag2 & V3D_SOLID_MATCAP) != 0)
2153                                 {
2154                                         // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name + 2);
2155                                         use_displist = false;
2156                                 }
2157                                 else {
2158                                         // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name + 2);
2159                                         
2160                                         /* disable boundbox check for list creation */
2161                                         BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 1);
2162                                         /* need this for next part of code */
2163                                         unit_m4(dob->ob->obmat);    /* obmat gets restored */
2164                                         
2165                                         displist = glGenLists(1);
2166                                         glNewList(displist, GL_COMPILE);
2167                                         draw_object(scene, ar, v3d, &tbase, dflag_dupli);
2168                                         glEndList();
2169                                         
2170                                         use_displist = true;
2171                                         BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 0);
2172                                 }               
2173                         }
2174                         
2175                         if (use_displist) {
2176                                 glPushMatrix();
2177                                 glMultMatrixf(dob->mat);
2178                                 glCallList(displist);
2179                                 glPopMatrix();
2180                         }       
2181                         else {
2182                                 copy_m4_m4(dob->ob->obmat, dob->mat);
2183                                 GPU_begin_dupli_object(dob);
2184                                 draw_object(scene, ar, v3d, &tbase, dflag_dupli);
2185                                 GPU_end_dupli_object();
2186                         }
2187                 }
2188                 
2189                 tbase.object->dt = dt;
2190                 tbase.object->dtx = dtx;
2191                 tbase.object->transflag = transflag;
2192                 tbase.object->currentlod = savedlod;
2193         }
2194
2195         if (apply_data) {
2196                 duplilist_restore(lb, apply_data);
2197                 duplilist_free_apply_data(apply_data);
2198         }
2199
2200         free_object_duplilist(lb);
2201         
2202         if (use_displist)
2203                 glDeleteLists(displist, 1);
2204 }
2205
2206 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
2207 {
2208         /* define the color here so draw_dupli_objects_color can be called
2209          * from the set loop */
2210         
2211         int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
2212         /* debug */
2213         if (base->object->dup_group && base->object->dup_group->id.us < 1)
2214                 color = TH_REDALERT;
2215         
2216         draw_dupli_objects_color(scene, ar, v3d, base, 0, color);
2217 }
2218
2219 /* XXX warning, not using gpu offscreen here */
2220 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
2221 {
2222         int x, y, w, h;
2223         rcti r;
2224         /* clamp rect by region */
2225
2226         r.xmin = 0;
2227         r.xmax = ar->winx - 1;
2228         r.ymin = 0;
2229         r.ymax = ar->winy - 1;
2230
2231         /* Constrain rect to depth bounds */
2232         BLI_rcti_isect(&r, rect, rect);
2233
2234         /* assign values to compare with the ViewDepths */
2235         x = rect->xmin;
2236         y = rect->ymin;
2237
2238         w = BLI_rcti_size_x(rect);
2239         h = BLI_rcti_size_y(rect);
2240
2241         if (w <= 0 || h <= 0) {
2242                 if (d->depths)
2243                         MEM_freeN(d->depths);
2244                 d->depths = NULL;
2245
2246                 d->damaged = false;
2247         }
2248         else if (d->w != w ||
2249                  d->h != h ||
2250                  d->x != x ||
2251                  d->y != y ||
2252                  d->depths == NULL
2253                  )
2254         {
2255                 d->x = x;
2256                 d->y = y;
2257                 d->w = w;
2258                 d->h = h;
2259
2260                 if (d->depths)
2261                         MEM_freeN(d->depths);
2262
2263                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
2264                 
2265                 d->damaged = true;
2266         }
2267
2268         if (d->damaged) {
2269                 /* XXX using special function here, it doesn't use the gpu offscreen system */
2270                 view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2271                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2272                 d->damaged = false;
2273         }
2274 }
2275
2276 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
2277 void ED_view3d_depth_update(ARegion *ar)
2278 {
2279         RegionView3D *rv3d = ar->regiondata;
2280         
2281         /* Create storage for, and, if necessary, copy depth buffer */
2282         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
2283         if (rv3d->depths) {
2284                 ViewDepths *d = rv3d->depths;
2285                 if (d->w != ar->winx ||
2286                     d->h != ar->winy ||
2287                     !d->depths)
2288                 {
2289                         d->w = ar->winx;
2290                         d->h = ar->winy;
2291                         if (d->depths)
2292                                 MEM_freeN(d->depths);
2293                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
2294                         d->damaged = true;
2295                 }
2296                 
2297                 if (d->damaged) {
2298                         view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2299                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2300                         
2301                         d->damaged = false;
2302                 }
2303         }
2304 }
2305
2306 /* utility function to find the closest Z value, use for autodepth */
2307 float view3d_depth_near(ViewDepths *d)
2308 {
2309         /* convert to float for comparisons */
2310         const float near = (float)d->depth_range[0];
2311         const float far_real = (float)d->depth_range[1];
2312         float far = far_real;
2313
2314         const float *depths = d->depths;
2315         float depth = FLT_MAX;
2316         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
2317
2318         /* far is both the starting 'far' value
2319          * and the closest value found. */
2320         while (i--) {
2321                 depth = *depths++;
2322                 if ((depth < far) && (depth > near)) {
2323                         far = depth;
2324                 }
2325         }
2326
2327         return far == far_real ? FLT_MAX : far;
2328 }
2329
2330 void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
2331 {
2332         short zbuf = v3d->zbuf;
2333         RegionView3D *rv3d = ar->regiondata;
2334
2335         view3d_winmatrix_set(ar, v3d, NULL);
2336         view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2337
2338         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2339         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2340         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2341
2342         glClear(GL_DEPTH_BUFFER_BIT);
2343
2344         glLoadMatrixf(rv3d->viewmat);
2345
2346         v3d->zbuf = true;
2347         glEnable(GL_DEPTH_TEST);
2348
2349         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2350                 ED_gpencil_draw_view3d(NULL, scene, v3d, ar, true);
2351         }
2352         
2353         v3d->zbuf = zbuf;
2354
2355 }
2356
2357 void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaoverride)
2358 {
2359         RegionView3D *rv3d = ar->regiondata;
2360         Base *base;
2361         short zbuf = v3d->zbuf;
2362         short flag = v3d->flag;
2363         float glalphaclip = U.glalphaclip;
2364         int obcenter_dia = U.obcenter_dia;
2365         /* no need for color when drawing depth buffer */
2366         const short dflag_depth = DRAW_CONSTCOLOR;
2367         /* temp set drawtype to solid */
2368         
2369         /* Setting these temporarily is not nice */
2370         v3d->flag &= ~V3D_SELECT_OUTLINE;
2371         U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
2372         U.obcenter_dia = 0;
2373         
2374         view3d_winmatrix_set(ar, v3d, NULL);
2375         view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2376         
2377         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2378         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2379         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2380         
2381         glClear(GL_DEPTH_BUFFER_BIT);
2382         
2383         glLoadMatrixf(rv3d->viewmat);
2384         
2385         if (rv3d->rflag & RV3D_CLIPPING) {
2386                 ED_view3d_clipping_set(rv3d);
2387         }
2388         /* get surface depth without bias */
2389         rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
2390
2391         v3d->zbuf = true;
2392         glEnable(GL_DEPTH_TEST);
2393         
2394         /* draw set first */
2395         if (scene->set) {
2396                 Scene *sce_iter;
2397                 for (SETLOOPER(scene->set, sce_iter, base)) {
2398                         if (v3d->lay & base->lay) {
2399                                 draw_object(scene, ar, v3d, base, 0);
2400                                 if (base->object->transflag & OB_DUPLI) {
2401                                         draw_dupli_objects_color(scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
2402                                 }
2403                         }
2404                 }
2405         }
2406         
2407         for (base = scene->base.first; base; base = base->next) {
2408                 if (v3d->lay & base->lay) {
2409                         /* dupli drawing */
2410                         if (base->object->transflag & OB_DUPLI) {
2411                                 draw_dupli_objects_color(scene, ar, v3d, base, dflag_depth, TH_UNDEFINED);
2412                         }
2413                         draw_object(scene, ar, v3d, base, dflag_depth);
2414                 }
2415         }
2416         
2417         /* this isn't that nice, draw xray objects as if they are normal */
2418         if (v3d->afterdraw_transp.first ||
2419             v3d->afterdraw_xray.first ||
2420             v3d->afterdraw_xraytransp.first)
2421         {
2422                 View3DAfter *v3da;
2423                 int mask_orig;
2424
2425                 v3d->xray = true;
2426                 
2427                 /* transp materials can change the depth mask, see #21388 */
2428                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2429
2430
2431                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2432                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2433                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = v3da->next) {
2434                                 draw_object(scene, ar, v3d, v3da->base, dflag_depth);
2435                         }
2436                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2437                 }
2438
2439                 /* draw 3 passes, transp/xray/xraytransp */
2440                 v3d->xray = false;
2441                 v3d->transp = true;
2442                 while ((v3da = BLI_pophead(&v3d->afterdraw_transp))) {
2443                         draw_object(scene, ar, v3d, v3da->base, dflag_depth);
2444                         MEM_freeN(v3da);
2445                 }
2446
2447                 v3d->xray = true;
2448                 v3d->transp = false;
2449                 while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
2450                         draw_object(scene, ar, v3d, v3da->base, dflag_depth);
2451                         MEM_freeN(v3da);
2452                 }
2453
2454                 v3d->xray = true;
2455                 v3d->transp = true;
2456                 while ((v3da = BLI_pophead(&v3d->afterdraw_xraytransp))) {
2457                         draw_object(scene, ar, v3d, v3da->base, dflag_depth);
2458                         MEM_freeN(v3da);
2459                 }
2460
2461                 
2462                 v3d->xray = false;
2463                 v3d->transp = false;
2464
2465                 glDepthMask(mask_orig);
2466         }
2467         
2468         if (rv3d->rflag & RV3D_CLIPPING) {
2469                 ED_view3d_clipping_disable();
2470         }
2471         rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
2472         
2473         v3d->zbuf = zbuf;
2474         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2475
2476         U.glalphaclip = glalphaclip;
2477         v3d->flag = flag;
2478         U.obcenter_dia = obcenter_dia;
2479 }
2480
2481 typedef struct View3DShadow {
2482         struct View3DShadow *next, *prev;
2483         GPULamp *lamp;
2484 } View3DShadow;
2485
2486 static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
2487                                    Object *ob, Object *par,
2488                                    float obmat[4][4], unsigned int lay,
2489                                    ListBase *shadows, SceneRenderLayer *srl)
2490 {
2491         GPULamp *lamp;
2492         Lamp *la = (Lamp *)ob->data;
2493         View3DShadow *shadow;
2494         unsigned int layers;
2495         
2496         lamp = GPU_lamp_from_blender(scene, ob, par);
2497         
2498         if (lamp) {
2499                 GPU_lamp_update(lamp, lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2500                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2501                 
2502                 layers = lay & v3d->lay;
2503                 if (srl)
2504                         layers &= srl->lay;
2505
2506                 if (layers &&
2507                     GPU_lamp_has_shadow_buffer(lamp) &&
2508                     /* keep last, may do string lookup */
2509                     GPU_lamp_override_visible(lamp, srl, NULL))
2510                 {
2511                         shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2512                         shadow->lamp = lamp;
2513                         BLI_addtail(shadows, shadow);
2514                 }
2515         }
2516 }
2517
2518 static void gpu_update_lamps_shadows_world(Scene *scene, View3D *v3d)
2519 {
2520         ListBase shadows;
2521         View3DShadow *shadow;
2522         Scene *sce_iter;
2523         Base *base;
2524         Object *ob;
2525         World *world = scene->world;
2526         SceneRenderLayer *srl = v3d->scenelock ? BLI_findlink(&scene->r.layers, scene->r.actlay) : NULL;
2527         
2528         BLI_listbase_clear(&shadows);
2529         
2530         /* update lamp transform and gather shadow lamps */
2531         for (SETLOOPER(scene, sce_iter, base)) {
2532                 ob = base->object;
2533                 
2534                 if (ob->type == OB_LAMP)
2535                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, ob->lay, &shadows, srl);
2536                 
2537                 if (ob->transflag & OB_DUPLI) {
2538                         DupliObject *dob;
2539                         ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
2540                         
2541                         for (dob = lb->first; dob; dob = dob->next)
2542                                 if (dob->ob->type == OB_LAMP)
2543                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, ob->lay, &shadows, srl);
2544                         
2545                         free_object_duplilist(lb);
2546                 }
2547         }
2548         
2549         /* render shadows after updating all lamps, nested object_duplilist
2550          * don't work correct since it's replacing object matrices */
2551         for (shadow = shadows.first; shadow; shadow = shadow->next) {
2552                 /* this needs to be done better .. */
2553                 float viewmat[4][4], winmat[4][4];
2554                 int drawtype, lay, winsize, flag2 = v3d->flag2;
2555                 ARegion ar = {NULL};
2556                 RegionView3D rv3d = {{{0}}};
2557                 
2558                 drawtype = v3d->drawtype;
2559                 lay = v3d->lay;
2560                 
2561                 v3d->drawtype = OB_SOLID;
2562                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2563                 v3d->flag2 &= ~(V3D_SOLID_TEX | V3D_SHOW_SOLID_MATCAP);
2564                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2565                 
2566                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2567
2568                 ar.regiondata = &rv3d;
2569                 ar.regiontype = RGN_TYPE_WINDOW;
2570                 rv3d.persp = RV3D_CAMOB;
2571                 copy_m4_m4(rv3d.winmat, winmat);
2572                 copy_m4_m4(rv3d.viewmat, viewmat);
2573                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2574                 mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2575                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2576
2577                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
2578                 ED_view3d_draw_offscreen(
2579                             scene, v3d, &ar, winsize, winsize, viewmat, winmat,
2580                             false, false, true,
2581                             NULL, NULL, NULL, NULL);
2582                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2583                 
2584                 v3d->drawtype = drawtype;
2585                 v3d->lay = lay;
2586                 v3d->flag2 = flag2;
2587         }
2588         
2589         BLI_freelistN(&shadows);
2590
2591         /* update world values */
2592         if (world) {
2593                 GPU_mist_update_enable(world->mode & WO_MIST);
2594                 GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr);
2595                 GPU_horizon_update_color(&world->horr);
2596                 GPU_ambient_update_color(&world->ambr);
2597                 GPU_zenith_update_color(&world->zenr);
2598         }
2599 }
2600
2601 /* *********************** customdata **************** */
2602
2603 CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d)
2604 {
2605         CustomDataMask mask = 0;
2606         const int drawtype = view3d_effective_drawtype(v3d);
2607
2608         if (ELEM(drawtype, OB_TEXTURE, OB_MATERIAL) ||
2609             ((drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
2610         {
2611                 mask |= CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
2612
2613                 if (BKE_scene_use_new_shading_nodes(scene)) {
2614                         if (drawtype == OB_MATERIAL)
2615                                 mask |= CD_MASK_ORCO;
2616                 }
2617                 else {
2618                         if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || 
2619                             (drawtype == OB_MATERIAL))
2620                         {
2621                                 mask |= CD_MASK_ORCO;
2622                         }
2623                 }
2624         }
2625
2626         return mask;
2627 }
2628
2629 /* goes over all modes and view3d settings */
2630 CustomDataMask ED_view3d_screen_datamask(const bScreen *screen)
2631 {
2632         const Scene *scene = screen->scene;
2633         CustomDataMask mask = CD_MASK_BAREMESH;
2634         const ScrArea *sa;
2635         
2636         /* check if we need tfaces & mcols due to view mode */
2637         for (sa = screen->areabase.first; sa; sa = sa->next) {
2638                 if (sa->spacetype == SPACE_VIEW3D) {
2639                         mask |= ED_view3d_datamask(scene, sa->spacedata.first);
2640                 }
2641         }
2642
2643         return mask;
2644 }
2645
2646 /**
2647  * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
2648  */
2649 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2650 {
2651         RegionView3D *rv3d = ar->regiondata;
2652         rctf cameraborder;
2653
2654         /* setup window matrices */
2655         if (winmat)
2656                 copy_m4_m4(rv3d->winmat, winmat);
2657         else
2658                 view3d_winmatrix_set(ar, v3d, NULL);
2659
2660         /* setup view matrix */
2661         if (viewmat)
2662                 copy_m4_m4(rv3d->viewmat, viewmat);
2663         else
2664                 view3d_viewmatrix_set(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2665
2666         /* update utilitity matrices */
2667         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2668         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2669         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2670         
2671         /* calculate GLSL view dependent values */
2672
2673         /* store window coordinates scaling/offset */
2674         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2675                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &cameraborder, false);
2676                 rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
2677                 rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
2678                 
2679                 rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
2680                 rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
2681         }
2682         else {
2683                 rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
2684                 rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
2685         }
2686         
2687         /* calculate pixelsize factor once, is used for lamps and obcenters */
2688         {
2689                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2690                  * because of float point precision problems at large values [#23908] */
2691                 float v1[3], v2[3];
2692                 float len_px, len_sc;
2693
2694                 v1[0] = rv3d->persmat[0][0];
2695                 v1[1] = rv3d->persmat[1][0];
2696                 v1[2] = rv3d->persmat[2][0];
2697
2698                 v2[0] = rv3d->persmat[0][1];
2699                 v2[1] = rv3d->persmat[1][1];
2700                 v2[2] = rv3d->persmat[2][1];
2701
2702                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
2703                 len_sc = (float)MAX2(ar->winx, ar->winy);
2704
2705                 rv3d->pixsize = len_px / len_sc;
2706         }
2707 }
2708
2709 /**
2710  * Shared by #ED_view3d_draw_offscreen and #view3d_main_region_draw_objects
2711  *
2712  * \note \a C and \a grid_unit will be NULL when \a draw_offscreen is set.
2713  * \note Drawing lamps and opengl render uses this, so dont do grease pencil or view widgets here.
2714  */
2715 static void view3d_draw_objects(
2716         const bContext *C,
2717         Scene *scene, View3D *v3d, ARegion *ar,
2718         const char **grid_unit,
2719         const bool do_bgpic, const bool draw_offscreen, GPUFX *fx)
2720 {
2721         RegionView3D *rv3d = ar->regiondata;
2722         Base *base;
2723         const bool do_camera_frame = !draw_offscreen;
2724         const bool draw_grids = !draw_offscreen && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0;
2725         const bool draw_floor = (rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO);
2726         /* only draw grids after in solid modes, else it hovers over mesh wires */
2727         const bool draw_grids_after = draw_grids && draw_floor && (v3d->drawtype > OB_WIRE) && fx;
2728         bool do_composite_xray = false;
2729         bool xrayclear = true;
2730
2731         if (!draw_offscreen) {
2732                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2733         }
2734
2735         if (rv3d->rflag & RV3D_CLIPPING)
2736                 view3d_draw_clipping(rv3d);
2737
2738         /* set zbuffer after we draw clipping region */
2739         if (v3d->drawtype > OB_WIRE) {
2740                 v3d->zbuf = true;
2741         }
2742         else {
2743                 v3d->zbuf = false;
2744         }
2745
2746         /* special case (depth for wire color) */
2747         if (v3d->drawtype <= OB_WIRE) {
2748                 if (scene->obedit && scene->obedit->type == OB_MESH) {
2749                         Mesh *me = scene->obedit->data;
2750                         if (me->drawflag & ME_DRAWEIGHT) {
2751                                 v3d->zbuf = true;
2752                         }
2753                 }
2754         }
2755
2756         if (v3d->zbuf) {
2757                 glEnable(GL_DEPTH_TEST);
2758         }
2759
2760         /* ortho grid goes first, does not write to depth buffer and doesn't need depth test so it will override
2761          * objects if done last */
2762         if (draw_grids) {
2763                 /* needs to be done always, gridview is adjusted in drawgrid() now, but only for ortho views. */
2764                 rv3d->gridview = ED_view3d_grid_scale(scene, v3d, grid_unit);
2765
2766                 if (!draw_floor) {
2767                         ED_region_pixelspace(ar);
2768                         *grid_unit = NULL;  /* drawgrid need this to detect/affect smallest valid unit... */
2769                         drawgrid(&scene->unit, ar, v3d, grid_unit);
2770                         /* XXX make function? replaces persp(1) */
2771                         glMatrixMode(GL_PROJECTION);
2772                         glLoadMatrixf(rv3d->winmat);
2773                         glMatrixMode(GL_MODELVIEW);
2774                         glLoadMatrixf(rv3d->viewmat);
2775                 }
2776                 else if (!draw_grids_after) {
2777                         drawfloor(scene, v3d, grid_unit, true);
2778                 }
2779         }
2780
2781         /* important to do before clipping */
2782         if (do_bgpic) {
2783                 view3d_draw_bgpic_test(scene, ar, v3d, false, do_camera_frame);
2784         }
2785
2786         if (rv3d->rflag & RV3D_CLIPPING) {
2787                 ED_view3d_clipping_set(rv3d);
2788         }
2789
2790         /* draw set first */
2791         if (scene->set) {
2792                 const short dflag = DRAW_CONSTCOLOR | DRAW_SCENESET;
2793                 Scene *sce_iter;
2794                 for (SETLOOPER(scene->set, sce_iter, base)) {
2795                         if (v3d->lay & base->lay) {
2796                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2797                                 draw_object(scene, ar, v3d, base, dflag);
2798
2799                                 if (base->object->transflag & OB_DUPLI) {
2800                                         draw_dupli_objects_color(scene, ar, v3d, base, dflag, TH_UNDEFINED);
2801                                 }
2802                         }
2803                 }
2804
2805                 /* Transp and X-ray afterdraw stuff for sets is done later */
2806         }
2807
2808
2809         if (draw_offscreen) {
2810                 for (base = scene->base.first; base; base = base->next) {
2811                         if (v3d->lay & base->lay) {
2812                                 /* dupli drawing */
2813                                 if (base->object->transflag & OB_DUPLI)
2814                                         draw_dupli_objects(scene, ar, v3d, base);
2815
2816                                 draw_object(scene, ar, v3d, base, 0);
2817                         }
2818                 }
2819         }
2820         else {
2821                 unsigned int lay_used = 0;
2822
2823                 /* then draw not selected and the duplis, but skip editmode object */
2824                 for (base = scene->base.first; base; base = base->next) {
2825                         lay_used |= base->lay;
2826
2827                         if (v3d->lay & base->lay) {
2828
2829                                 /* dupli drawing */
2830                                 if (base->object->transflag & OB_DUPLI) {
2831                                         draw_dupli_objects(scene, ar, v3d, base);
2832                                 }
2833                                 if ((base->flag & SELECT) == 0) {
2834                                         if (base->object != scene->obedit)
2835                                                 draw_object(scene, ar, v3d, base, 0);
2836                                 }
2837                         }
2838                 }
2839
2840                 /* mask out localview */
2841                 v3d->lay_used = lay_used & ((1 << 20) - 1);
2842
2843                 /* draw selected and editmode */
2844                 for (base = scene->base.first; base; base = base->next) {
2845                         if (v3d->lay & base->lay) {
2846                                 if (base->object == scene->obedit || (base->flag & SELECT)) {
2847                                         draw_object(scene, ar, v3d, base, 0);
2848                                 }
2849                         }
2850                 }
2851         }
2852
2853         /* perspective floor goes last to use scene depth and avoid writing to depth buffer */
2854         if (draw_grids_after) {
2855                 drawfloor(scene, v3d, grid_unit, false);
2856         }
2857
2858         /* must be before xray draw which clears the depth buffer */
2859         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2860                 wmWindowManager *wm = (C != NULL) ? CTX_wm_manager(C) : NULL;
2861                 
2862                 /* must be before xray draw which clears the depth buffer */
2863                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
2864                 ED_gpencil_draw_view3d(wm, scene, v3d, ar, true);
2865                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
2866         }
2867
2868         /* transp and X-ray afterdraw stuff */
2869         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, ar, v3d);
2870
2871         /* always do that here to cleanup depth buffers if none needed */
2872         if (fx) {
2873                 do_composite_xray = v3d->zbuf && (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first);
2874                 GPU_fx_compositor_setup_XRay_pass(fx, do_composite_xray);
2875         }
2876
2877         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, ar, v3d, &xrayclear);
2878         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, xrayclear);
2879
2880         if (fx && do_composite_xray) {
2881                 GPU_fx_compositor_XRay_resolve(fx);
2882         }
2883
2884         if (!draw_offscreen) {
2885                 ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2886         }
2887
2888         if (rv3d->rflag & RV3D_CLIPPING)
2889                 ED_view3d_clipping_disable();
2890
2891         /* important to do after clipping */
2892         if (do_bgpic) {
2893                 view3d_draw_bgpic_test(scene, ar, v3d, true, do_camera_frame);
2894         }
2895
2896         if (!draw_offscreen) {
2897                 BIF_draw_manipulator(C);
2898         }
2899
2900         /* cleanup */
2901         if (v3d->zbuf) {
2902                 v3d->zbuf = false;
2903                 glDisable(GL_DEPTH_TEST);
2904         }
2905
2906         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
2907                 GPU_free_images_old();
2908         }
2909 }
2910
2911 static void view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2912 {
2913         RegionView3D *rv3d = ar->regiondata;
2914
2915         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
2916
2917         /* set for opengl */
2918         glMatrixMode(GL_PROJECTION);
2919         glLoadMatrixf(rv3d->winmat);
2920         glMatrixMode(GL_MODELVIEW);
2921         glLoadMatrixf(rv3d->viewmat);
2922 }
2923
2924 /**
2925  * Store values from #RegionView3D, set when drawing.
2926  * This is needed when we draw with to a viewport using a different matrix (offscreen drawing for example).
2927  *
2928  * Values set by #ED_view3d_update_viewmat should be handled here.
2929  */
2930 struct RV3DMatrixStore {
2931         float winmat[4][4];
2932         float viewmat[4][4];
2933         float viewinv[4][4];
2934         float persmat[4][4];
2935         float persinv[4][4];
2936         float viewcamtexcofac[4];
2937         float pixsize;
2938 };
2939
2940 void *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
2941 {
2942         struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
2943         copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
2944         copy_m4_m4(rv3dmat->viewmat, rv3d->viewmat);
2945         copy_m4_m4(rv3dmat->persmat, rv3d->persmat);
2946         copy_m4_m4(rv3dmat->persinv, rv3d->persinv);
2947         copy_m4_m4(rv3dmat->viewinv, rv3d->viewinv);
2948         copy_v4_v4(rv3dmat->viewcamtexcofac, rv3d->viewcamtexcofac);
2949         rv3dmat->pixsize = rv3d->pixsize;
2950         return (void *)rv3dmat;
2951 }
2952
2953 void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, void *rv3dmat_pt)
2954 {
2955         struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
2956         copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
2957         copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
2958         copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
2959         copy_m4_m4(rv3d->persinv, rv3dmat->persinv);
2960         copy_m4_m4(rv3d->viewinv, rv3dmat->viewinv);
2961         copy_v4_v4(rv3d->viewcamtexcofac, rv3dmat->viewcamtexcofac);
2962         rv3d->pixsize = rv3dmat->pixsize;
2963 }
2964
2965 void ED_view3d_draw_offscreen_init(Scene *scene, View3D *v3d)
2966 {
2967         /* shadow buffers, before we setup matrices */
2968         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2969                 gpu_update_lamps_shadows_world(scene, v3d);
2970 }
2971
2972 /*
2973  * Function to clear the view
2974  */
2975 static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
2976 {
2977         if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
2978                 bool glsl = GPU_glsl_support();
2979                 if (glsl) {
2980                         RegionView3D *rv3d = ar->regiondata;
2981                         GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
2982
2983                         /* calculate full shader for background */
2984                         GPU_material_bind(gpumat, 1, 1, 1.0, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac, (v3d->scenelock != 0));
2985                         
2986                         bool material_not_bound = !GPU_material_bound(gpumat);
2987
2988                         if (material_not_bound) {
2989                                 glMatrixMode(GL_PROJECTION);
2990                                 glPushMatrix();
2991                                 glLoadIdentity();
2992                                 glMatrixMode(GL_MODELVIEW);
2993                                 glPushMatrix();
2994                                 glLoadIdentity();
2995                                 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
2996                         }
2997                         // Draw world
2998                         glEnable(GL_DEPTH_TEST);
2999                         glDepthFunc(GL_ALWAYS);
3000                         glBegin(GL_TRIANGLE_STRIP);
3001                         glVertex3f(-1.0, -1.0, 1.0);
3002                         glVertex3f(1.0, -1.0, 1.0);
3003                         glVertex3f(-1.0, 1.0, 1.0);
3004                         glVertex3f(1.0, 1.0, 1.0);
3005                         glEnd();
3006                         //
3007                         if (material_not_bound) {
3008                                 glMatrixMode(GL_PROJECTION);
3009                                 glPopMatrix();
3010                                 glMatrixMode(GL_MODELVIEW);
3011                                 glPopMatrix();
3012                         }
3013
3014                         GPU_material_unbind(gpumat);
3015                         
3016                         glDepthFunc(GL_LEQUAL);
3017                         glDisable(GL_DEPTH_TEST);
3018                 }
3019                 else if (scene->world->skytype & WO_SKYBLEND) {  /* blend sky */
3020                         int x, y;
3021                         float col_hor[3];
3022                         float col_zen[3];
3023
3024 #define VIEWGRAD_RES_X 16
3025 #define VIEWGRAD_RES_Y 16
3026
3027                         GLubyte grid_col[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][4];
3028                         static float grid_pos[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][3];
3029                         static GLushort indices[VIEWGRAD_RES_X - 1][VIEWGRAD_RES_X - 1][4];
3030                         static bool buf_calculated = false;
3031
3032                         IMB_colormanagement_pixel_to_display_space_v3(col_hor, &scene->world->horr, &scene->view_settings,
3033                                                                       &scene->display_settings);
3034                         IMB_colormanagement_pixel_to_display_space_v3(col_zen, &scene->world->zenr, &scene->view_settings,
3035                                                                       &scene->display_settings);
3036
3037                         glMatrixMode(GL_PROJECTION);
3038                         glPushMatrix();
3039                         glLoadIdentity();
3040                         glMatrixMode(GL_MODELVIEW);
3041                         glPushMatrix();
3042                         glLoadIdentity();
3043
3044                         /* calculate buffers the first time only */
3045                         if (!buf_calculated) {
3046                                 for (x = 0; x < VIEWGRAD_RES_X; x++) {
3047                   &nbs