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