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