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