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