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