svn merge -r36583:36603 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / editors / space_view3d / view3d_draw.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2008 Blender Foundation.
21  * All rights reserved.
22  *
23  * 
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/editors/space_view3d/view3d_draw.c
30  *  \ingroup spview3d
31  */
32
33
34 #include <string.h>
35 #include <stdio.h>
36 #include <math.h>
37
38 #include "DNA_armature_types.h"
39 #include "DNA_camera_types.h"
40 #include "DNA_customdata_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_group_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_lamp_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_world_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_rand.h"
53 #include "BLI_utildefines.h"
54
55 #include "BKE_anim.h"
56 #include "BKE_context.h"
57 #include "BKE_customdata.h"
58 #include "BKE_image.h"
59 #include "BKE_key.h"
60 #include "BKE_object.h"
61 #include "BKE_global.h"
62 #include "BKE_paint.h"
63 #include "BKE_scene.h"
64 #include "BKE_unit.h"
65
66 #include "RE_pipeline.h"        // make_stars
67
68 #include "IMB_imbuf_types.h"
69 #include "IMB_imbuf.h"
70
71 #include "BIF_gl.h"
72 #include "BIF_glutil.h"
73
74 #include "WM_api.h"
75 #include "BLF_api.h"
76
77 #include "ED_armature.h"
78 #include "ED_keyframing.h"
79 #include "ED_gpencil.h"
80 #include "ED_screen.h"
81 #include "ED_space_api.h"
82 #include "ED_screen_types.h"
83 #include "ED_transform.h"
84
85 #include "UI_interface.h"
86 #include "UI_interface_icons.h"
87 #include "UI_resources.h"
88
89 #include "GPU_draw.h"
90 #include "GPU_material.h"
91 #include "GPU_extensions.h"
92
93 #include "view3d_intern.h"      // own include
94
95
96
97 static void star_stuff_init_func(void)
98 {
99         cpack(-1);
100         glPointSize(1.0);
101         glBegin(GL_POINTS);
102 }
103 static void star_stuff_vertex_func(float* i)
104 {
105         glVertex3fv(i);
106 }
107 static void star_stuff_term_func(void)
108 {
109         glEnd();
110 }
111
112 void circf(float x, float y, float rad)
113 {
114         GLUquadricObj *qobj = gluNewQuadric(); 
115         
116         gluQuadricDrawStyle(qobj, GLU_FILL); 
117         
118         glPushMatrix(); 
119         
120         glTranslatef(x,  y, 0.); 
121         
122         gluDisk( qobj, 0.0,  rad, 32, 1); 
123         
124         glPopMatrix(); 
125         
126         gluDeleteQuadric(qobj);
127 }
128
129 void circ(float x, float y, float rad)
130 {
131         GLUquadricObj *qobj = gluNewQuadric(); 
132         
133         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
134         
135         glPushMatrix(); 
136         
137         glTranslatef(x,  y, 0.); 
138         
139         gluDisk( qobj, 0.0,  rad, 32, 1); 
140         
141         glPopMatrix(); 
142         
143         gluDeleteQuadric(qobj);
144 }
145
146
147 /* ********* custom clipping *********** */
148
149 static void view3d_draw_clipping(RegionView3D *rv3d)
150 {
151         BoundBox *bb= rv3d->clipbb;
152         
153         if(bb) {
154                 UI_ThemeColorShade(TH_BACK, -8);
155                 
156                 glBegin(GL_QUADS);
157                 
158                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[3]);
159                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[1]);
160                 glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[5]);
161                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[3]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[6]);
162                 glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[2]);
163                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[3]);
164                 
165                 glEnd();
166         }
167 }
168
169 void view3d_set_clipping(RegionView3D *rv3d)
170 {
171         double plane[4];
172         int a, tot=4;
173         
174         if(rv3d->viewlock) tot= 6;
175         
176         for(a=0; a<tot; a++) {
177                 QUATCOPY(plane, rv3d->clip[a]);
178                 glClipPlane(GL_CLIP_PLANE0+a, plane);
179                 glEnable(GL_CLIP_PLANE0+a);
180         }
181 }
182
183 void view3d_clr_clipping(void)
184 {
185         int a;
186         
187         for(a=0; a<6; a++) {
188                 glDisable(GL_CLIP_PLANE0+a);
189         }
190 }
191
192 static int test_clipping(const float vec[3], float clip[][4])
193 {
194         float view[3];
195         copy_v3_v3(view, vec);
196         
197         if(0.0f < clip[0][3] + INPR(view, clip[0]))
198                 if(0.0f < clip[1][3] + INPR(view, clip[1]))
199                         if(0.0f < clip[2][3] + INPR(view, clip[2]))
200                                 if(0.0f < clip[3][3] + INPR(view, clip[3]))
201                                         return 0;
202
203         return 1;
204 }
205
206 /* for 'local' ED_view3d_local_clipping must run first
207  * then all comparisons can be done in localspace */
208 int view3d_test_clipping(RegionView3D *rv3d, const float vec[3], const int local)
209 {
210         return test_clipping(vec, local ? rv3d->clip_local : rv3d->clip);
211 }
212
213 /* ********* end custom clipping *********** */
214
215
216 static void drawgrid_draw(ARegion *ar, float wx, float wy, float x, float y, float dx)
217 {       
218         float v1[2], v2[2];
219
220         x+= (wx); 
221         y+= (wy);
222
223         v1[1]= 0.0f;
224         v2[1]= (float)ar->winy;
225
226         v1[0] = v2[0] = x-dx*floorf(x/dx);
227         
228         glBegin(GL_LINES);
229         
230         while(v1[0] < ar->winx) {
231                 glVertex2fv(v1);
232                 glVertex2fv(v2);
233                 v1[0] = v2[0] = v1[0] + dx;
234         }
235
236         v1[0]= 0.0f;
237         v2[0]= (float)ar->winx;
238
239         v1[1]= v2[1]= y-dx*floorf(y/dx);
240
241         while(v1[1] < ar->winy) {
242                 glVertex2fv(v1);
243                 glVertex2fv(v2);
244                 v1[1] = v2[1] = v1[1] + dx;
245         }
246
247         glEnd();
248 }
249
250 #define GRID_MIN_PX 6.0f
251
252 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
253 {
254         /* extern short bgpicmode; */
255         RegionView3D *rv3d= ar->regiondata;
256         float wx, wy, x, y, fw, fx, fy, dx;
257         float vec4[4];
258         unsigned char col[3], col2[3];
259
260         vec4[0]=vec4[1]=vec4[2]=0.0; 
261         vec4[3]= 1.0;
262         mul_m4_v4(rv3d->persmat, vec4);
263         fx= vec4[0]; 
264         fy= vec4[1]; 
265         fw= vec4[3];
266
267         wx= (ar->winx/2.0);     /* because of rounding errors, grid at wrong location */
268         wy= (ar->winy/2.0);
269
270         x= (wx)*fx/fw;
271         y= (wy)*fy/fw;
272
273         vec4[0]=vec4[1]= v3d->grid;
274
275         vec4[2]= 0.0;
276         vec4[3]= 1.0;
277         mul_m4_v4(rv3d->persmat, vec4);
278         fx= vec4[0]; 
279         fy= vec4[1]; 
280         fw= vec4[3];
281
282         dx= fabs(x-(wx)*fx/fw);
283         if(dx==0) dx= fabs(y-(wy)*fy/fw);
284         
285         glDepthMask(0);         // disable write in zbuffer
286
287         /* check zoom out */
288         UI_ThemeColor(TH_GRID);
289         
290         if(unit->system) {
291                 /* Use GRID_MIN_PX*2 for units because very very small grid
292                  * items are less useful when dealing with units */
293                 void *usys;
294                 int len, i;
295                 float dx_scalar;
296                 float blend_fac;
297
298                 bUnit_GetSystem(&usys, &len, unit->system, B_UNIT_LENGTH);
299
300                 if(usys) {
301                         i= len;
302                         while(i--) {
303                                 float scalar= bUnit_GetScaler(usys, i);
304
305                                 dx_scalar = dx * scalar / unit->scale_length;
306                                 if (dx_scalar < (GRID_MIN_PX*2))
307                                         continue;
308
309                                 /* Store the smallest drawn grid size units name so users know how big each grid cell is */
310                                 if(*grid_unit==NULL) {
311                                         *grid_unit= bUnit_GetNameDisplay(usys, i);
312                                         rv3d->gridview= (scalar * v3d->grid) / unit->scale_length;
313                                 }
314                                 blend_fac= 1-((GRID_MIN_PX*2)/dx_scalar);
315
316                                 /* tweak to have the fade a bit nicer */
317                                 blend_fac= (blend_fac * blend_fac) * 2.0f;
318                                 CLAMP(blend_fac, 0.3f, 1.0f);
319
320
321                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, blend_fac);
322
323                                 drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
324                         }
325                 }
326         }
327         else {
328                 short sublines = v3d->gridsubdiv;
329
330                 if(dx<GRID_MIN_PX) {
331                         rv3d->gridview*= sublines;
332                         dx*= sublines;
333                         
334                         if(dx<GRID_MIN_PX) {
335                                 rv3d->gridview*= sublines;
336                                 dx*= sublines;
337
338                                 if(dx<GRID_MIN_PX) {
339                                         rv3d->gridview*= sublines;
340                                         dx*=sublines;
341                                         if(dx<GRID_MIN_PX);
342                                         else {
343                                                 UI_ThemeColor(TH_GRID);
344                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
345                                         }
346                                 }
347                                 else {  // start blending out
348                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
349                                         drawgrid_draw(ar, wx, wy, x, y, dx);
350
351                                         UI_ThemeColor(TH_GRID);
352                                         drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
353                                 }
354                         }
355                         else {  // start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX*10))
356                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
357                                 drawgrid_draw(ar, wx, wy, x, y, dx);
358
359                                 UI_ThemeColor(TH_GRID);
360                                 drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
361                         }
362                 }
363                 else {
364                         if(dx>(GRID_MIN_PX*10)) {               // start blending in
365                                 rv3d->gridview/= sublines;
366                                 dx/= sublines;
367                                 if(dx>(GRID_MIN_PX*10)) {               // start blending in
368                                         rv3d->gridview/= sublines;
369                                         dx/= sublines;
370                                         if(dx>(GRID_MIN_PX*10)) {
371                                                 UI_ThemeColor(TH_GRID);
372                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
373                                         }
374                                         else {
375                                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
376                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
377                                                 UI_ThemeColor(TH_GRID);
378                                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
379                                         }
380                                 }
381                                 else {
382                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
383                                         drawgrid_draw(ar, wx, wy, x, y, dx);
384                                         UI_ThemeColor(TH_GRID);
385                                         drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
386                                 }
387                         }
388                         else {
389                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
390                                 drawgrid_draw(ar, wx, wy, x, y, dx);
391                                 UI_ThemeColor(TH_GRID);
392                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
393                         }
394                 }
395         }
396
397
398         x+= (wx); 
399         y+= (wy);
400         UI_GetThemeColor3ubv(TH_GRID, col);
401
402         setlinestyle(0);
403         
404         /* center cross */
405         /* horizontal line */
406         if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
407                 UI_make_axis_color(col, col2, 'Y');
408         else UI_make_axis_color(col, col2, 'X');
409         glColor3ubv(col2);
410         
411         fdrawline(0.0,  y,  (float)ar->winx,  y); 
412         
413         /* vertical line */
414         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
415                 UI_make_axis_color(col, col2, 'Y');
416         else UI_make_axis_color(col, col2, 'Z');
417         glColor3ubv(col2);
418
419         fdrawline(x, 0.0, x, (float)ar->winy); 
420
421         glDepthMask(1);         // enable write in zbuffer
422 }
423 #undef GRID_MIN_PX
424
425 static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit)
426 {
427         float vert[3], grid, grid_scale;
428         int a, gridlines, emphasise;
429         unsigned char col[3], col2[3];
430         short draw_line = 0;
431         
432         vert[2]= 0.0;
433         
434         if(v3d->gridlines<3) return;
435         
436         grid_scale= v3d->grid;
437         /* use 'grid_scale' instead of 'v3d->grid' from now on */
438
439         /* apply units */
440         if(scene->unit.system) {
441                 void *usys;
442                 int len;
443
444                 bUnit_GetSystem(&usys, &len, scene->unit.system, B_UNIT_LENGTH);
445
446                 if(usys) {
447                         int i= bUnit_GetBaseUnit(usys);
448                         *grid_unit= bUnit_GetNameDisplay(usys, i);
449                          grid_scale = (grid_scale * (float)bUnit_GetScaler(usys, i)) / scene->unit.scale_length;
450                 }
451         }
452         
453         if(v3d->zbuf && scene->obedit) glDepthMask(0);  // for zbuffer-select
454         
455         gridlines= v3d->gridlines/2;
456         grid= gridlines * grid_scale;
457
458         UI_GetThemeColor3ubv(TH_GRID, col);
459         UI_GetThemeColor3ubv(TH_BACK, col2);
460         
461         /* emphasise division lines lighter instead of darker, if background is darker than grid */
462         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
463                 emphasise = 20;
464         else
465                 emphasise = -10;
466         
467         /* draw the Y axis and/or grid lines */
468         for(a= -gridlines;a<=gridlines;a++) {
469                 if(a==0) {
470                         /* check for the 'show Y axis' preference */
471                         if (v3d->gridflag & V3D_SHOW_Y) { 
472                                 UI_make_axis_color(col, col2, 'Y');
473                                 glColor3ubv(col2);
474                                 
475                                 draw_line = 1;
476                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
477                                 UI_ThemeColorShade(TH_GRID, emphasise);
478                         } else {
479                                 draw_line = 0;
480                         }
481                 } else {
482                         /* check for the 'show grid floor' preference */
483                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
484                                 if( (a % 10)==0) {
485                                         UI_ThemeColorShade(TH_GRID, emphasise);
486                                 }
487                                 else UI_ThemeColorShade(TH_GRID, 10);
488                                 
489                                 draw_line = 1;
490                         } else {
491                                 draw_line = 0;
492                         }
493                 }
494                 
495                 if (draw_line) {
496                         glBegin(GL_LINE_STRIP);
497                         vert[0]= a * grid_scale;
498                         vert[1]= grid;
499                         glVertex3fv(vert);
500                         vert[1]= -grid;
501                         glVertex3fv(vert);
502                         glEnd();
503                 }
504         }
505         
506         /* draw the X axis and/or grid lines */
507         for(a= -gridlines;a<=gridlines;a++) {
508                 if(a==0) {
509                         /* check for the 'show X axis' preference */
510                         if (v3d->gridflag & V3D_SHOW_X) { 
511                                 UI_make_axis_color(col, col2, 'X');
512                                 glColor3ubv(col2);
513                                 
514                                 draw_line = 1;
515                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
516                                 UI_ThemeColorShade(TH_GRID, emphasise);
517                         } else {
518                                 draw_line = 0;
519                         }
520                 } else {
521                         /* check for the 'show grid floor' preference */
522                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
523                                 if( (a % 10)==0) {
524                                         UI_ThemeColorShade(TH_GRID, emphasise);
525                                 }
526                                 else UI_ThemeColorShade(TH_GRID, 10);
527                                 
528                                 draw_line = 1;
529                         } else {
530                                 draw_line = 0;
531                         }
532                 }
533                 
534                 if (draw_line) {
535                         glBegin(GL_LINE_STRIP);
536                         vert[1]= a * grid_scale;
537                         vert[0]= grid;
538                         glVertex3fv(vert );
539                         vert[0]= -grid;
540                         glVertex3fv(vert);
541                         glEnd();
542                 }
543         }
544         
545         /* draw the Z axis line */      
546         /* check for the 'show Z axis' preference */
547         if (v3d->gridflag & V3D_SHOW_Z) {
548                 UI_make_axis_color(col, col2, 'Z');
549                 glColor3ubv(col2);
550                 
551                 glBegin(GL_LINE_STRIP);
552                 vert[0]= 0;
553                 vert[1]= 0;
554                 vert[2]= grid;
555                 glVertex3fv(vert );
556                 vert[2]= -grid;
557                 glVertex3fv(vert);
558                 glEnd();
559         }
560         
561         if(v3d->zbuf && scene->obedit) glDepthMask(1);  
562         
563 }
564
565 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
566 {
567         short mx,my,co[2];
568         int flag;
569         
570         /* we dont want the clipping for cursor */
571         flag= v3d->flag;
572         v3d->flag= 0;
573         project_short(ar, give_cursor(scene, v3d), co);
574         v3d->flag= flag;
575         
576         mx = co[0];
577         my = co[1];
578         
579         if(mx!=IS_CLIPPED) {
580                 setlinestyle(0); 
581                 cpack(0xFF);
582                 circ((float)mx, (float)my, 10.0);
583                 setlinestyle(4); 
584                 cpack(0xFFFFFF);
585                 circ((float)mx, (float)my, 10.0);
586                 setlinestyle(0);
587                 cpack(0x0);
588                 
589                 sdrawline(mx-20, my, mx-5, my);
590                 sdrawline(mx+5, my, mx+20, my);
591                 sdrawline(mx, my-20, mx, my-5);
592                 sdrawline(mx, my+5, mx, my+20);
593         }
594 }
595
596 /* Draw a live substitute of the view icon, which is always shown
597  * colors copied from transform_manipulator.c, we should keep these matching. */
598 static void draw_view_axis(RegionView3D *rv3d)
599 {
600         const float k = U.rvisize;   /* axis size */
601         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
602         const float start = k + 1.0f;/* axis center in screen coordinates, x=y */
603         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
604         int bright = 25*(float)U.rvibright + 5; /* axis alpha (rvibright has range 0-10) */
605
606         float vec[3];
607         float dx, dy;
608         
609         /* thickness of lines is proportional to k */
610         glLineWidth(2);
611
612         glEnable(GL_BLEND);
613         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
614
615         /* X */
616         vec[0] = 1;
617         vec[1] = vec[2] = 0;
618         mul_qt_v3(rv3d->viewquat, vec);
619         dx = vec[0] * k;
620         dy = vec[1] * k;
621
622         glColor4ub(220, 0, 0, bright);
623         glBegin(GL_LINES);
624         glVertex2f(start, start + ydisp);
625         glVertex2f(start + dx, start + dy + ydisp);
626         glEnd();
627
628         if (fabsf(dx) > toll || fabsf(dy) > toll) {
629                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "x", 1);
630         }
631         
632         /* BLF_draw_default disables blending */
633         glEnable(GL_BLEND);
634
635         /* Y */
636         vec[1] = 1;
637         vec[0] = vec[2] = 0;
638         mul_qt_v3(rv3d->viewquat, vec);
639         dx = vec[0] * k;
640         dy = vec[1] * k;
641
642         glColor4ub(0, 220, 0, bright);
643         glBegin(GL_LINES);
644         glVertex2f(start, start + ydisp);
645         glVertex2f(start + dx, start + dy + ydisp);
646         glEnd();
647
648         if (fabsf(dx) > toll || fabsf(dy) > toll) {
649                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "y", 1);
650         }
651
652         glEnable(GL_BLEND);
653         
654         /* Z */
655         vec[2] = 1;
656         vec[1] = vec[0] = 0;
657         mul_qt_v3(rv3d->viewquat, vec);
658         dx = vec[0] * k;
659         dy = vec[1] * k;
660
661         glColor4ub(30, 30, 220, bright);
662         glBegin(GL_LINES);
663         glVertex2f(start, start + ydisp);
664         glVertex2f(start + dx, start + dy + ydisp);
665         glEnd();
666
667         if (fabsf(dx) > toll || fabsf(dy) > toll) {
668                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "z", 1);
669         }
670
671         /* restore line-width */
672         
673         glLineWidth(1.0);
674         glDisable(GL_BLEND);
675 }
676
677
678 static void draw_view_icon(RegionView3D *rv3d)
679 {
680         BIFIconID icon;
681         
682         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
683                 icon= ICON_AXIS_TOP;
684         else if( ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) 
685                 icon= ICON_AXIS_FRONT;
686         else if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
687                 icon= ICON_AXIS_SIDE;
688         else return ;
689         
690         glEnable(GL_BLEND);
691         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
692         
693         UI_icon_draw(5.0, 5.0, icon);
694         
695         glDisable(GL_BLEND);
696 }
697
698 static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
699 {
700         const char *name = NULL;
701         
702         switch (rv3d->view) {
703                 case RV3D_VIEW_FRONT:
704                         if (rv3d->persp == RV3D_ORTHO) name = "Front Ortho";
705                         else name = "Front Persp";
706                         break;
707                 case RV3D_VIEW_BACK:
708                         if (rv3d->persp == RV3D_ORTHO) name = "Back Ortho";
709                         else name = "Back Persp";
710                         break;
711                 case RV3D_VIEW_TOP:
712                         if (rv3d->persp == RV3D_ORTHO) name = "Top Ortho";
713                         else name = "Top Persp";
714                         break;
715                 case RV3D_VIEW_BOTTOM:
716                         if (rv3d->persp == RV3D_ORTHO) name = "Bottom Ortho";
717                         else name = "Bottom Persp";
718                         break;
719                 case RV3D_VIEW_RIGHT:
720                         if (rv3d->persp == RV3D_ORTHO) name = "Right Ortho";
721                         else name = "Right Persp";
722                         break;
723                 case RV3D_VIEW_LEFT:
724                         if (rv3d->persp == RV3D_ORTHO) name = "Left Ortho";
725                         else name = "Left Persp";
726                         break;
727                         
728                 default:
729                         if (rv3d->persp==RV3D_CAMOB) {
730                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
731                                         Camera *cam;
732                                         cam = v3d->camera->data;
733                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
734                                 } else {
735                                         name = "Object as Camera";
736                                 }
737                         } else { 
738                                 name = (rv3d->persp == RV3D_ORTHO) ? "User Ortho" : "User Persp";
739                         }
740                         break;
741         }
742         
743         return name;
744 }
745
746 static void draw_viewport_name(ARegion *ar, View3D *v3d)
747 {
748         RegionView3D *rv3d= ar->regiondata;
749         const char *name= view3d_get_name(v3d, rv3d);
750         char tmpstr[24];
751         
752         if (v3d->localvd) {
753                 BLI_snprintf(tmpstr, sizeof(tmpstr), "%s (Local)", name);
754                 name= tmpstr;
755         }
756
757         if (name) {
758                 UI_ThemeColor(TH_TEXT_HI);
759                 BLF_draw_default(22,  ar->winy-17, 0.0f, name, sizeof(tmpstr));
760         }
761 }
762
763 /* draw info beside axes in bottom left-corner: 
764 *       framenum, object name, bone name (if available), marker name (if available)
765 */
766 static void draw_selected_name(Scene *scene, Object *ob, View3D *v3d)
767 {
768         char info[256], *markern;
769         short offset=30;
770         
771         /* get name of marker on current frame (if available) */
772         markern= scene_find_marker_name(scene, CFRA);
773         
774         /* check if there is an object */
775         if(ob) {
776                 /* name(s) to display depends on type of object */
777                 if(ob->type==OB_ARMATURE) {
778                         bArmature *arm= ob->data;
779                         char *name= NULL;
780                         
781                         /* show name of active bone too (if possible) */
782                         if(arm->edbo) {
783
784                                 if(arm->act_edbone)
785                                         name= ((EditBone *)arm->act_edbone)->name;
786
787                         }
788                         else if(ob->mode & OB_MODE_POSE) {
789                                 if(arm->act_bone) {
790
791                                         if(arm->act_bone->layer & arm->layer)
792                                                 name= arm->act_bone->name;
793
794                                 }
795                         }
796                         if(name && markern)
797                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, name, markern);
798                         else if(name)
799                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
800                         else
801                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
802                 }
803                 else if(ELEM3(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
804                         Key *key= NULL;
805                         KeyBlock *kb = NULL;
806                         char shapes[75];
807                         
808                         /* try to display active shapekey too */
809                         shapes[0] = 0;
810                         key = ob_get_key(ob);
811                         if(key){
812                                 kb = BLI_findlink(&key->block, ob->shapenr-1);
813                                 if(kb){
814                                         sprintf(shapes, ": %s ", kb->name);             
815                                         if(ob->shapeflag == OB_SHAPE_LOCK){
816                                                 strcat(shapes, " (Pinned)");
817                                         }
818                                 }
819                         }
820                         
821                         if(markern)
822                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, shapes, markern);
823                         else
824                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
825                 }
826                 else {
827                         /* standard object */
828                         if (markern)
829                                 sprintf(info, "(%d) %s <%s>", CFRA, ob->id.name+2, markern);
830                         else
831                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
832                 }
833                 
834                 /* color depends on whether there is a keyframe */
835                 if (id_frame_has_keyframe((ID *)ob, /*BKE_curframe(scene)*/(float)(CFRA), v3d->keyflags))
836                         UI_ThemeColor(TH_VERTEX_SELECT);
837                 else
838                         UI_ThemeColor(TH_TEXT_HI);
839         }
840         else {
841                 /* no object */
842                 if (markern)
843                         sprintf(info, "(%d) <%s>", CFRA, markern);
844                 else
845                         sprintf(info, "(%d)", CFRA);
846                 
847                 /* color is always white */
848                 UI_ThemeColor(TH_TEXT_HI);
849         }
850         
851         if (U.uiflag & USER_SHOW_ROTVIEWICON)
852                 offset = 14 + (U.rvisize * 2);
853
854         BLF_draw_default(offset,  10, 0.0f, info, sizeof(info)-1);
855 }
856
857 void view3d_viewborder_size_get(Scene *scene, ARegion *ar, float size_r[2])
858 {
859         float winmax= MAX2(ar->winx, ar->winy);
860         float aspect= (scene->r.xsch*scene->r.xasp) / (scene->r.ysch*scene->r.yasp);
861         
862         if(aspect > 1.0f) {
863                 size_r[0]= winmax;
864                 size_r[1]= winmax/aspect;
865         } else {
866                 size_r[0]= winmax*aspect;
867                 size_r[1]= winmax;
868         }
869 }
870
871 void view3d_calc_camera_border(Scene *scene, ARegion *ar, RegionView3D *rv3d, View3D *v3d, rctf *viewborder_r, short do_shift)
872 {
873         float zoomfac, size[2];
874         float dx= 0.0f, dy= 0.0f;
875         
876         view3d_viewborder_size_get(scene, ar, size);
877         
878         if (rv3d == NULL)
879                 rv3d = ar->regiondata;
880         
881         /* magic zoom calculation, no idea what
882                 * it signifies, if you find out, tell me! -zr
883                 */
884         /* simple, its magic dude!
885                 * well, to be honest, this gives a natural feeling zooming
886                 * with multiple keypad presses (ton)
887                 */
888         
889         zoomfac= ((float)M_SQRT2 + rv3d->camzoom/50.0f);
890         zoomfac= (zoomfac*zoomfac) * 0.25f;
891         
892         size[0]= size[0]*zoomfac;
893         size[1]= size[1]*zoomfac;
894         
895         /* center in window */
896         viewborder_r->xmin= 0.5f * ar->winx - 0.5f * size[0];
897         viewborder_r->ymin= 0.5f * ar->winy - 0.5f * size[1];
898         viewborder_r->xmax= viewborder_r->xmin + size[0];
899         viewborder_r->ymax= viewborder_r->ymin + size[1];
900         
901         dx= ar->winx*rv3d->camdx*zoomfac*2.0f;
902         dy= ar->winy*rv3d->camdy*zoomfac*2.0f;
903         
904         /* apply offset */
905         viewborder_r->xmin-= dx;
906         viewborder_r->ymin-= dy;
907         viewborder_r->xmax-= dx;
908         viewborder_r->ymax-= dy;
909         
910         if(do_shift && v3d->camera && v3d->camera->type==OB_CAMERA) {
911                 Camera *cam= v3d->camera->data;
912                 float w = viewborder_r->xmax - viewborder_r->xmin;
913                 float h = viewborder_r->ymax - viewborder_r->ymin;
914                 float side = MAX2(w, h);
915
916                 if(do_shift == -1) side *= -1;
917                 viewborder_r->xmin+= cam->shiftx*side;
918                 viewborder_r->xmax+= cam->shiftx*side;
919                 viewborder_r->ymin+= cam->shifty*side;
920                 viewborder_r->ymax+= cam->shifty*side;
921         }
922 }
923
924 static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac, char diagonal)
925 {
926         float x3, y3, x4, y4;
927
928         x3= x1 + fac * (x2-x1);
929         y3= y1 + fac * (y2-y1);
930         x4= x1 + (1.0f - fac) * (x2-x1);
931         y4= y1 + (1.0f - fac) * (y2-y1);
932
933         glBegin(GL_LINES);
934         switch(diagonal) {
935         case '\0':
936                 glVertex2f(x1, y3);
937                 glVertex2f(x2, y3);
938
939                 glVertex2f(x1, y4);
940                 glVertex2f(x2, y4);
941
942                 glVertex2f(x3, y1);
943                 glVertex2f(x3, y2);
944
945                 glVertex2f(x4, y1);
946                 glVertex2f(x4, y2);
947                 break;
948         case 'H': /* hoz */
949                 glVertex2f(x1, y1);
950                 glVertex2f(x2, y4);
951
952                 glVertex2f(x1, y3);
953                 glVertex2f(x2, y2);
954
955                 glVertex2f(x2, y1);
956                 glVertex2f(x1, y4);
957
958                 glVertex2f(x2, y3);
959                 glVertex2f(x1, y2);
960                 break;
961         case 'V': /* vert */
962                 glVertex2f(x1, y1);
963                 glVertex2f(x4, y2);
964
965                 glVertex2f(x3, y1);
966                 glVertex2f(x2, y2);
967
968                 glVertex2f(x1, y2);
969                 glVertex2f(x4, y1);
970
971                 glVertex2f(x3, y2);
972                 glVertex2f(x2, y1);
973                 break;
974         }
975         glEnd();
976 }
977
978 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
979 {
980         float fac, a;
981         float x1, x2, y1, y2;
982         float x1i, x2i, y1i, y2i;
983         float x3, y3, x4, y4;
984         rctf viewborder;
985         Camera *ca= NULL;
986         RegionView3D *rv3d= (RegionView3D *)ar->regiondata;
987         
988         if(v3d->camera==NULL)
989                 return;
990         if(v3d->camera->type==OB_CAMERA)
991                 ca = v3d->camera->data;
992         
993         view3d_calc_camera_border(scene, ar, rv3d, v3d, &viewborder, FALSE);
994         /* the offsets */
995         x1= viewborder.xmin;
996         y1= viewborder.ymin;
997         x2= viewborder.xmax;
998         y2= viewborder.ymax;
999         
1000         /* apply offsets so the real 3D camera shows through */
1001         x1i= (int)(x1 - 1.0f);
1002         y1i= (int)(y1 - 1.0f);
1003         x2i= (int)(x2 + 1.0f);
1004         y2i= (int)(y2 + 1.0f);
1005         
1006         /* passepartout, specified in camera edit buttons */
1007         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
1008                 if (ca->passepartalpha == 1.0f) {
1009                         glColor3f(0, 0, 0);
1010                 } else {
1011                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1012                         glEnable(GL_BLEND);
1013                         glColor4f(0, 0, 0, ca->passepartalpha);
1014                 }
1015                 if (x1i > 0.0f)
1016                         glRectf(0.0, (float)ar->winy, x1i, 0.0);
1017                 if (x2i < (float)ar->winx)
1018                         glRectf(x2i, (float)ar->winy, (float)ar->winx, 0.0);
1019                 if (y2i < (float)ar->winy)
1020                         glRectf(x1i, (float)ar->winy, x2i, y2i);
1021                 if (y2i > 0.0f)
1022                         glRectf(x1i, y1i, x2i, 0.0);
1023                 
1024                 glDisable(GL_BLEND);
1025         }
1026
1027         /* edge */
1028         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);      
1029
1030         setlinestyle(0);
1031         UI_ThemeColor(TH_BACK);
1032         glRectf(x1i, y1i, x2i, y2i);
1033         
1034         setlinestyle(3);
1035         UI_ThemeColor(TH_WIRE);
1036         glRectf(x1i, y1i, x2i, y2i);
1037
1038         /* border */
1039         if(scene->r.mode & R_BORDER) {
1040                 
1041                 cpack(0);
1042                 x3= x1+ scene->r.border.xmin*(x2-x1);
1043                 y3= y1+ scene->r.border.ymin*(y2-y1);
1044                 x4= x1+ scene->r.border.xmax*(x2-x1);
1045                 y4= y1+ scene->r.border.ymax*(y2-y1);
1046                 
1047                 cpack(0x4040FF);
1048                 glRectf(x3,  y3,  x4,  y4); 
1049         }
1050
1051         /* safety border */
1052         if(ca) {
1053                 if (ca->dtx & CAM_DTX_CENTER) {
1054                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1055
1056                         x3= x1+ 0.5f*(x2-x1);
1057                         y3= y1+ 0.5f*(y2-y1);
1058
1059                         glBegin(GL_LINES);
1060                         glVertex2f(x1, y3);
1061                         glVertex2f(x2, y3);
1062
1063                         glVertex2f(x3, y1);
1064                         glVertex2f(x3, y2);
1065                         glEnd();
1066                 }
1067
1068                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
1069                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1070
1071                         glBegin(GL_LINES);
1072                         glVertex2f(x1, y1);
1073                         glVertex2f(x2, y2);
1074
1075                         glVertex2f(x1, y2);
1076                         glVertex2f(x2, y1);
1077                         glEnd();
1078                 }
1079
1080                 if (ca->dtx & CAM_DTX_THIRDS) {
1081                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1082                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f/3.0f, '\0');
1083                 }
1084
1085                 if (ca->dtx & CAM_DTX_GOLDEN) {
1086                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1087                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), '\0');
1088                 }
1089
1090                 if (ca->dtx & CAM_DTX_GOLDEN_DIAG_H) {
1091                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1092                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), 'H');
1093                 }
1094
1095                 if (ca->dtx & CAM_DTX_GOLDEN_DIAG_V) {
1096                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1097                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), 'V');
1098                 }
1099
1100                 if (ca->flag & CAM_SHOWTITLESAFE) {
1101                         fac= 0.1;
1102
1103                         a= fac*(x2-x1);
1104                         x1+= a;
1105                         x2-= a;
1106
1107                         a= fac*(y2-y1);
1108                         y1+= a;
1109                         y2-= a;
1110
1111                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1112
1113                         uiSetRoundBox(15);
1114                         uiDrawBox(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1115                 }
1116         }
1117
1118         setlinestyle(0);
1119         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1120
1121         /* camera name - draw in highlighted text color */
1122         if (ca && (ca->flag & CAM_SHOWNAME)) {
1123                 UI_ThemeColor(TH_TEXT_HI);
1124                 BLF_draw_default(x1i, y1i-15, 0.0f, v3d->camera->id.name+2, sizeof(v3d->camera->id.name)-2);
1125                 UI_ThemeColor(TH_WIRE);
1126         }
1127 }
1128
1129 /* *********************** backdraw for selection *************** */
1130
1131 static void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1132 {
1133         RegionView3D *rv3d= ar->regiondata;
1134         struct Base *base = scene->basact;
1135         rcti winrct;
1136
1137         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1138                          paint_facesel_test(base->object)));
1139         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1140                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1141         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1142         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1143         else {
1144                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1145                 return;
1146         }
1147
1148         if( !(v3d->flag & V3D_INVALID_BACKBUF) ) return;
1149
1150 //      if(test) {
1151 //              if(qtest()) {
1152 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1153 //                      return;
1154 //              }
1155 //      }
1156
1157         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1158         
1159         glDisable(GL_DITHER);
1160
1161         region_scissor_winrct(ar, &winrct);
1162         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1163
1164         glClearColor(0.0, 0.0, 0.0, 0.0); 
1165         if(v3d->zbuf) {
1166                 glEnable(GL_DEPTH_TEST);
1167                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1168         }
1169         else {
1170                 glClear(GL_COLOR_BUFFER_BIT);
1171                 glDisable(GL_DEPTH_TEST);
1172         }
1173         
1174         if(rv3d->rflag & RV3D_CLIPPING)
1175                 view3d_set_clipping(rv3d);
1176         
1177         G.f |= G_BACKBUFSEL;
1178         
1179         if(base && (base->lay & v3d->lay)) {
1180                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1181         }
1182
1183         v3d->flag &= ~V3D_INVALID_BACKBUF;
1184         ar->swap= 0; /* mark invalid backbuf for wm draw */
1185
1186         G.f &= ~G_BACKBUFSEL;
1187         v3d->zbuf= FALSE; 
1188         glDisable(GL_DEPTH_TEST);
1189         glEnable(GL_DITHER);
1190
1191         if(rv3d->rflag & RV3D_CLIPPING)
1192                 view3d_clr_clipping();
1193
1194         /* it is important to end a view in a transform compatible with buttons */
1195 //      persp(PERSP_WIN);  // set ortho
1196
1197 }
1198
1199 void view3d_validate_backbuf(ViewContext *vc)
1200 {
1201         if(vc->v3d->flag & V3D_INVALID_BACKBUF)
1202                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1203 }
1204
1205 /* samples a single pixel (copied from vpaint) */
1206 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1207 {
1208         unsigned int col;
1209         
1210         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1211         x+= vc->ar->winrct.xmin;
1212         y+= vc->ar->winrct.ymin;
1213         
1214         view3d_validate_backbuf(vc);
1215
1216         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1217         glReadBuffer(GL_BACK);  
1218         
1219         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1220         
1221         return WM_framebuffer_to_index(col);
1222 }
1223
1224 /* reads full rect, converts indices */
1225 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1226 {
1227         unsigned int *dr, *rd;
1228         struct ImBuf *ibuf, *ibuf1;
1229         int a;
1230         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1231         
1232         /* clip */
1233         if(xmin<0) xminc= 0; else xminc= xmin;
1234         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1235         if(xminc > xmaxc) return NULL;
1236
1237         if(ymin<0) yminc= 0; else yminc= ymin;
1238         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1239         if(yminc > ymaxc) return NULL;
1240         
1241         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect);
1242
1243         view3d_validate_backbuf(vc); 
1244         
1245         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1246         glReadBuffer(GL_BACK);  
1247
1248         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1249
1250         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1251         dr= ibuf->rect;
1252         while(a--) {
1253                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1254                 dr++;
1255         }
1256         
1257         /* put clipped result back, if needed */
1258         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1259                 return ibuf;
1260         
1261         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect);
1262         rd= ibuf->rect;
1263         dr= ibuf1->rect;
1264                 
1265         for(ys= ymin; ys<=ymax; ys++) {
1266                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1267                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1268                                 *dr= *rd;
1269                                 rd++;
1270                         }
1271                 }
1272         }
1273         IMB_freeImBuf(ibuf);
1274         return ibuf1;
1275 }
1276
1277 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1278 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const short mval[2], int size,
1279                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1280                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1281 {
1282         struct ImBuf *buf;
1283         unsigned int *bufmin, *bufmax, *tbuf;
1284         int minx, miny;
1285         int a, b, rc, nr, amount, dirvec[4][2];
1286         int distance=0;
1287         unsigned int index = 0;
1288         short indexok = 0;      
1289
1290         amount= (size-1)/2;
1291
1292         minx = mval[0]-(amount+1);
1293         miny = mval[1]-(amount+1);
1294         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1295         if (!buf) return 0;
1296
1297         rc= 0;
1298         
1299         dirvec[0][0]= 1; dirvec[0][1]= 0;
1300         dirvec[1][0]= 0; dirvec[1][1]= -size;
1301         dirvec[2][0]= -1; dirvec[2][1]= 0;
1302         dirvec[3][0]= 0; dirvec[3][1]= size;
1303         
1304         bufmin = buf->rect;
1305         tbuf = buf->rect;
1306         bufmax = buf->rect + size*size;
1307         tbuf+= amount*size+ amount;
1308         
1309         for(nr=1; nr<=size; nr++) {
1310                 
1311                 for(a=0; a<2; a++) {
1312                         for(b=0; b<nr; b++, distance++) {
1313                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1314                                         if(strict){
1315                                                 indexok =  indextest(handle, *tbuf - min+1);
1316                                                 if(indexok){
1317                                                         *dist= (short) sqrt( (float)distance   );
1318                                                         index = *tbuf - min+1;
1319                                                         goto exit; 
1320                                                 }                                               
1321                                         }
1322                                         else{
1323                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1324                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1325                                                 goto exit;
1326                                         }                       
1327                                 }
1328                                 
1329                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1330                                 
1331                                 if(tbuf<bufmin || tbuf>=bufmax) {
1332                                         goto exit;
1333                                 }
1334                         }
1335                         rc++;
1336                         rc &= 3;
1337                 }
1338         }
1339
1340 exit:
1341         IMB_freeImBuf(buf);
1342         return index;
1343 }
1344
1345
1346 /* ************************************************************* */
1347
1348 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1349 {
1350         RegionView3D *rv3d= ar->regiondata;
1351         BGpic *bgpic;
1352         Image *ima;
1353         ImBuf *ibuf= NULL;
1354         float vec[4], fac, asp, zoomx, zoomy;
1355         float x1, y1, x2, y2, cx, cy;
1356
1357
1358         for ( bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next ) {
1359
1360                 if(     (bgpic->view == 0) || /* zero for any */
1361                         (bgpic->view & (1<<rv3d->view)) || /* check agaist flags */
1362                         (rv3d->persp==RV3D_CAMOB && bgpic->view == (1<<RV3D_VIEW_CAMERA))
1363                 ) {
1364                         ima= bgpic->ima;
1365                         if(ima==NULL)
1366                                 continue;
1367                         BKE_image_user_calc_frame(&bgpic->iuser, CFRA, 0);
1368                         ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1369                         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) )
1370                                 continue;
1371                         if(ibuf->channels!=4)
1372                                 continue;
1373                         if(ibuf->rect==NULL)
1374                                 IMB_rect_from_float(ibuf);
1375
1376                         if(rv3d->persp==RV3D_CAMOB) {
1377                                 rctf vb;
1378
1379                                 view3d_calc_camera_border(scene, ar, rv3d, v3d, &vb, FALSE);
1380
1381                                 x1= vb.xmin;
1382                                 y1= vb.ymin;
1383                                 x2= vb.xmax;
1384                                 y2= vb.ymax;
1385                         }
1386                         else {
1387                                 float sco[2];
1388
1389                                 /* calc window coord */
1390                                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1391                                 window_to_3d_delta(ar, vec, 1, 0);
1392                                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1393                                 fac= 1.0f/fac;
1394
1395                                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1396
1397                                 vec[0] = vec[1] = vec[2] = 0.0;
1398                                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1399                                 cx = sco[0];
1400                                 cy = sco[1];
1401
1402                                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1403                                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1404                                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1405                                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1406                         }
1407
1408                         /* complete clip? */
1409
1410                         if(x2 < 0 ) continue;
1411                         if(y2 < 0 ) continue;
1412                         if(x1 > ar->winx ) continue;
1413                         if(y1 > ar->winy ) continue;
1414
1415                         zoomx= (x2-x1)/ibuf->x;
1416                         zoomy= (y2-y1)/ibuf->y;
1417
1418                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1419                         if(zoomx < 1.0f || zoomy < 1.0f) {
1420                                 float tzoom= MIN2(zoomx, zoomy);
1421                                 int mip= 0;
1422
1423                                 if((ibuf->userflags&IB_MIPMAP_INVALID) != 0) {
1424                                         IMB_remakemipmap(ibuf, 0);
1425                                         ibuf->userflags&= ~IB_MIPMAP_INVALID;
1426                                 }
1427                                 else if(ibuf->mipmap[0]==NULL)
1428                                         IMB_makemipmap(ibuf, 0);
1429
1430                                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1431                                         tzoom*= 2.0f;
1432                                         zoomx*= 2.0f;
1433                                         zoomy*= 2.0f;
1434                                         mip++;
1435                                 }
1436                                 if(mip>0)
1437                                         ibuf= ibuf->mipmap[mip-1];
1438                         }
1439
1440                         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1441                         glDepthMask(0);
1442
1443                         glEnable(GL_BLEND);
1444                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1445
1446                         glMatrixMode(GL_PROJECTION);
1447                         glPushMatrix();
1448                         glMatrixMode(GL_MODELVIEW);
1449                         glPushMatrix();
1450                         ED_region_pixelspace(ar);
1451
1452                         glPixelZoom(zoomx, zoomy);
1453                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f-bgpic->blend);
1454                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1455
1456                         glPixelZoom(1.0, 1.0);
1457                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1458
1459                         glMatrixMode(GL_PROJECTION);
1460                         glPopMatrix();
1461                         glMatrixMode(GL_MODELVIEW);
1462                         glPopMatrix();
1463
1464                         glDisable(GL_BLEND);
1465
1466                         glDepthMask(1);
1467                         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1468                 }
1469         }
1470 }
1471
1472 /* ****************** View3d afterdraw *************** */
1473
1474 typedef struct View3DAfter {
1475         struct View3DAfter *next, *prev;
1476         struct Base *base;
1477         int flag;
1478 } View3DAfter;
1479
1480 /* temp storage of Objects that need to be drawn as last */
1481 void add_view3d_after(ListBase *lb, Base *base, int flag)
1482 {
1483         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1484         BLI_addtail(lb, v3da);
1485         v3da->base= base;
1486         v3da->flag= flag;
1487 }
1488
1489 /* disables write in zbuffer and draws it over */
1490 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1491 {
1492         View3DAfter *v3da, *next;
1493         
1494         glDepthMask(0);
1495         v3d->transp= TRUE;
1496         
1497         for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
1498                 next= v3da->next;
1499                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1500                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1501                 MEM_freeN(v3da);
1502         }
1503         v3d->transp= FALSE;
1504         
1505         glDepthMask(1);
1506         
1507 }
1508
1509 /* clears zbuffer and draws it over */
1510 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1511 {
1512         View3DAfter *v3da, *next;
1513
1514         if(clear && v3d->zbuf)
1515                 glClear(GL_DEPTH_BUFFER_BIT);
1516
1517         v3d->xray= TRUE;
1518         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1519                 next= v3da->next;
1520                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1521                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1522                 MEM_freeN(v3da);
1523         }
1524         v3d->xray= FALSE;
1525 }
1526
1527
1528 /* clears zbuffer and draws it over */
1529 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1530 {
1531         View3DAfter *v3da, *next;
1532
1533         if(clear && v3d->zbuf)
1534                 glClear(GL_DEPTH_BUFFER_BIT);
1535
1536         v3d->xray= TRUE;
1537         v3d->transp= TRUE;
1538         
1539         for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
1540                 next= v3da->next;
1541                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1542                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1543                 MEM_freeN(v3da);
1544         }
1545
1546         v3d->transp= FALSE;
1547         v3d->xray= FALSE;
1548
1549 }
1550
1551 /* *********************** */
1552
1553 /*
1554         In most cases call draw_dupli_objects,
1555         draw_dupli_objects_color was added because when drawing set dupli's
1556         we need to force the color
1557  */
1558
1559 #if 0
1560 int dupli_ob_sort(void *arg1, void *arg2)
1561 {
1562         void *p1= ((DupliObject *)arg1)->ob;
1563         void *p2= ((DupliObject *)arg2)->ob;
1564         int val = 0;
1565         if (p1 < p2)            val = -1;
1566         else if (p1 > p2)       val = 1;
1567         return val;
1568 }
1569 #endif
1570
1571
1572 static DupliObject *dupli_step(DupliObject *dob)
1573 {
1574         while(dob && dob->no_draw)
1575                 dob= dob->next;
1576         return dob;
1577 }
1578
1579 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1580 {
1581         RegionView3D *rv3d= ar->regiondata;
1582         ListBase *lb;
1583         DupliObject *dob_prev= NULL, *dob, *dob_next= NULL;
1584         Base tbase;
1585         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1586         GLuint displist=0;
1587         short transflag, use_displist= -1;      /* -1 is initialize */
1588         char dt, dtx;
1589         
1590         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1591         
1592         tbase.flag= OB_FROMDUPLI|base->flag;
1593         lb= object_duplilist(scene, base->object);
1594         // BLI_sortlist(lb, dupli_ob_sort); // might be nice to have if we have a dupli list with mixed objects.
1595
1596         dob=dupli_step(lb->first);
1597         if(dob) dob_next= dupli_step(dob->next);
1598
1599         for( ; dob ; dob_prev= dob, dob= dob_next, dob_next= dob_next ? dupli_step(dob_next->next) : NULL) {
1600                 tbase.object= dob->ob;
1601
1602                 /* extra service: draw the duplicator in drawtype of parent */
1603                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1604                 dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1605                 dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1606
1607                 /* negative scale flag has to propagate */
1608                 transflag= tbase.object->transflag;
1609                 if(base->object->transflag & OB_NEG_SCALE)
1610                         tbase.object->transflag ^= OB_NEG_SCALE;
1611
1612                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1613
1614                 /* generate displist, test for new object */
1615                 if(dob_prev && dob_prev->ob != dob->ob) {
1616                         if(use_displist==1)
1617                                 glDeleteLists(displist, 1);
1618
1619                         use_displist= -1;
1620                 }
1621
1622                 /* generate displist */
1623                 if(use_displist == -1) {
1624
1625                         /* note, since this was added, its checked dob->type==OB_DUPLIGROUP
1626                          * however this is very slow, it was probably needed for the NLA
1627                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1628                          * so for now it should be ok to - campbell */
1629
1630                         if(             (dob_next==NULL || dob_next->ob != dob->ob) || /* if this is the last no need  to make a displist */
1631                                         (dob->ob->type == OB_LAMP) || /* lamp drawing messes with matrices, could be handled smarter... but this works */
1632                                         (dob->type == OB_DUPLIGROUP && dob->animated) ||
1633                                         !(bb_tmp= object_get_boundbox(dob->ob))
1634                         ) {
1635                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1636                                 use_displist= 0;
1637                         }
1638                         else {
1639                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1640                                 bb= *bb_tmp; /* must make a copy  */
1641
1642                                 /* disable boundbox check for list creation */
1643                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1644                                 /* need this for next part of code */
1645                                 unit_m4(dob->ob->obmat);        /* obmat gets restored */
1646
1647                                 displist= glGenLists(1);
1648                                 glNewList(displist, GL_COMPILE);
1649                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1650                                 glEndList();
1651
1652                                 use_displist= 1;
1653                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1654                         }
1655                 }
1656                 if(use_displist) {
1657                         glMultMatrixf(dob->mat);
1658                         if(boundbox_clip(rv3d, dob->mat, &bb))
1659                                 glCallList(displist);
1660                         glLoadMatrixf(rv3d->viewmat);
1661                 }
1662                 else {
1663                         copy_m4_m4(dob->ob->obmat, dob->mat);
1664                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1665                 }
1666
1667                 tbase.object->dt= dt;
1668                 tbase.object->dtx= dtx;
1669                 tbase.object->transflag= transflag;
1670         }
1671         
1672         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1673         
1674         free_object_duplilist(lb);      /* does restore */
1675         
1676         if(use_displist)
1677                 glDeleteLists(displist, 1);
1678 }
1679
1680 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1681 {
1682         /* define the color here so draw_dupli_objects_color can be called
1683         * from the set loop */
1684         
1685         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1686         /* debug */
1687         if(base->object->dup_group && base->object->dup_group->id.us<1)
1688                 color= TH_REDALERT;
1689         
1690         draw_dupli_objects_color(scene, ar, v3d, base, color);
1691 }
1692
1693 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1694 {
1695         int x, y, w, h; 
1696         rcti r;
1697         /* clamp rect by area */
1698
1699         r.xmin= 0;
1700         r.xmax= ar->winx-1;
1701         r.ymin= 0;
1702         r.ymax= ar->winy-1;
1703
1704         /* Constrain rect to depth bounds */
1705         BLI_isect_rcti(&r, rect, rect);
1706
1707         /* assign values to compare with the ViewDepths */
1708         x= rect->xmin;
1709         y= rect->ymin;
1710
1711         w= rect->xmax - rect->xmin;
1712         h= rect->ymax - rect->ymin;
1713
1714         if(w <= 0 || h <= 0) {
1715                 if(d->depths)
1716                         MEM_freeN(d->depths);
1717                 d->depths= NULL;
1718
1719                 d->damaged= FALSE;
1720         }
1721         else if(        d->w != w ||
1722                 d->h != h ||
1723                 d->x != x ||
1724                 d->y != y ||
1725                 d->depths==NULL
1726         ) {
1727                 d->x= x;
1728                 d->y= y;
1729                 d->w= w;
1730                 d->h= h;
1731
1732                 if(d->depths)
1733                         MEM_freeN(d->depths);
1734
1735                 d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths Subset");
1736                 
1737                 d->damaged= TRUE;
1738         }
1739
1740         if(d->damaged) {
1741                 glReadPixels(ar->winrct.xmin+d->x,ar->winrct.ymin+d->y, d->w,d->h, GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1742                 glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1743                 d->damaged= FALSE;
1744         }
1745 }
1746
1747 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1748 void view3d_update_depths(ARegion *ar)
1749 {
1750         RegionView3D *rv3d= ar->regiondata;
1751         
1752         /* Create storage for, and, if necessary, copy depth buffer */
1753         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1754         if(rv3d->depths) {
1755                 ViewDepths *d= rv3d->depths;
1756                 if(d->w != ar->winx ||
1757                    d->h != ar->winy ||
1758                    !d->depths) {
1759                         d->w= ar->winx;
1760                         d->h= ar->winy;
1761                         if(d->depths)
1762                                 MEM_freeN(d->depths);
1763                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1764                         d->damaged= 1;
1765                 }
1766                 
1767                 if(d->damaged) {
1768                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1769                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1770                         
1771                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1772                         
1773                         d->damaged= 0;
1774                 }
1775         }
1776 }
1777
1778 /* utility function to find the closest Z value, use for autodepth */
1779 float view3d_depth_near(ViewDepths *d)
1780 {
1781         /* convert to float for comparisons */
1782         const float near= (float)d->depth_range[0];
1783         const float far_real= (float)d->depth_range[1];
1784         float far= far_real;
1785
1786         const float *depths= d->depths;
1787         float depth= FLT_MAX;
1788         int i= (int)d->w * (int)d->h; /* cast to avoid short overflow */
1789
1790         /* far is both the starting 'far' value
1791          * and the closest value found. */      
1792         while(i--) {
1793                 depth= *depths++;
1794                 if((depth < far) && (depth > near)) {
1795                         far= depth;
1796                 }
1797         }
1798
1799         return far == far_real ? FLT_MAX : far;
1800 }
1801
1802 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1803 {
1804         short zbuf= v3d->zbuf;
1805         RegionView3D *rv3d= ar->regiondata;
1806
1807         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1808         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1809
1810         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1811         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1812         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1813
1814         glClear(GL_DEPTH_BUFFER_BIT);
1815
1816         glLoadMatrixf(rv3d->viewmat);
1817
1818         v3d->zbuf= TRUE;
1819         glEnable(GL_DEPTH_TEST);
1820
1821         draw_gpencil_view3d_ext(scene, v3d, ar, 1);
1822         
1823         v3d->zbuf= zbuf;
1824
1825 }
1826
1827 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1828 {
1829         RegionView3D *rv3d= ar->regiondata;
1830         Base *base;
1831         short zbuf= v3d->zbuf;
1832         short flag= v3d->flag;
1833         float glalphaclip= U.glalphaclip;
1834         int obcenter_dia= U.obcenter_dia;
1835         /* temp set drawtype to solid */
1836         
1837         /* Setting these temporarily is not nice */
1838         v3d->flag &= ~V3D_SELECT_OUTLINE;
1839         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1840         U.obcenter_dia= 0;
1841         
1842         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1843         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1844         
1845         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1846         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1847         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1848         
1849         glClear(GL_DEPTH_BUFFER_BIT);
1850         
1851         glLoadMatrixf(rv3d->viewmat);
1852 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1853         
1854         if(rv3d->rflag & RV3D_CLIPPING) {
1855                 view3d_set_clipping(rv3d);
1856         }
1857         
1858         v3d->zbuf= TRUE;
1859         glEnable(GL_DEPTH_TEST);
1860         
1861         /* draw set first */
1862         if(scene->set) {
1863                 Scene *sce_iter;
1864                 for(SETLOOPER(scene->set, sce_iter, base)) {
1865                         if(v3d->lay & base->lay) {
1866                                 if (func == NULL || func(base)) {
1867                                         draw_object(scene, ar, v3d, base, 0);
1868                                         if(base->object->transflag & OB_DUPLI) {
1869                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1870                                         }
1871                                 }
1872                         }
1873                 }
1874         }
1875         
1876         for(base= scene->base.first; base; base= base->next) {
1877                 if(v3d->lay & base->lay) {
1878                         if (func == NULL || func(base)) {
1879                                 /* dupli drawing */
1880                                 if(base->object->transflag & OB_DUPLI) {
1881                                         draw_dupli_objects(scene, ar, v3d, base);
1882                                 }
1883                                 draw_object(scene, ar, v3d, base, 0);
1884                         }
1885                 }
1886         }
1887         
1888         /* this isnt that nice, draw xray objects as if they are normal */
1889         if (    v3d->afterdraw_transp.first ||
1890                         v3d->afterdraw_xray.first || 
1891                         v3d->afterdraw_xraytransp.first
1892         ) {
1893                 View3DAfter *v3da, *next;
1894                 int mask_orig;
1895
1896                 v3d->xray= TRUE;
1897                 
1898                 /* transp materials can change the depth mask, see #21388 */
1899                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
1900
1901
1902                 if(v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
1903                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1904                         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1905                                 next= v3da->next;
1906                                 draw_object(scene, ar, v3d, v3da->base, 0);
1907                         }
1908                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1909                 }
1910
1911                 /* draw 3 passes, transp/xray/xraytransp */
1912                 v3d->xray= FALSE;
1913                 v3d->transp= TRUE;
1914                 for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
1915                         next= v3da->next;
1916                         draw_object(scene, ar, v3d, v3da->base, 0);
1917                         BLI_remlink(&v3d->afterdraw_transp, v3da);
1918                         MEM_freeN(v3da);
1919                 }
1920
1921                 v3d->xray= TRUE;
1922                 v3d->transp= FALSE;  
1923                 for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1924                         next= v3da->next;
1925                         draw_object(scene, ar, v3d, v3da->base, 0);
1926                         BLI_remlink(&v3d->afterdraw_xray, v3da);
1927                         MEM_freeN(v3da);
1928                 }
1929
1930                 v3d->xray= TRUE;
1931                 v3d->transp= TRUE;
1932                 for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
1933                         next= v3da->next;
1934                         draw_object(scene, ar, v3d, v3da->base, 0);
1935                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1936                         MEM_freeN(v3da);
1937                 }
1938
1939                 
1940                 v3d->xray= FALSE;
1941                 v3d->transp= FALSE;
1942
1943                 glDepthMask(mask_orig);
1944         }
1945         
1946         if(rv3d->rflag & RV3D_CLIPPING)
1947                 view3d_clr_clipping();
1948         
1949         v3d->zbuf = zbuf;
1950         if(!v3d->zbuf) glDisable(GL_DEPTH_TEST);
1951
1952         U.glalphaclip = glalphaclip;
1953         v3d->flag = flag;
1954         U.obcenter_dia= obcenter_dia;
1955 }
1956
1957 typedef struct View3DShadow {
1958         struct View3DShadow *next, *prev;
1959         GPULamp *lamp;
1960 } View3DShadow;
1961
1962 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1963 {
1964         GPULamp *lamp;
1965         Lamp *la = (Lamp*)ob->data;
1966         View3DShadow *shadow;
1967         
1968         lamp = GPU_lamp_from_blender(scene, ob, par);
1969         
1970         if(lamp) {
1971                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
1972                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1973                 
1974                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1975                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1976                         shadow->lamp = lamp;
1977                         BLI_addtail(shadows, shadow);
1978                 }
1979         }
1980 }
1981
1982 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1983 {
1984         ListBase shadows;
1985         View3DShadow *shadow;
1986         Scene *sce_iter;
1987         Base *base;
1988         Object *ob;
1989         
1990         shadows.first= shadows.last= NULL;
1991         
1992         /* update lamp transform and gather shadow lamps */
1993         for(SETLOOPER(scene, sce_iter, base)) {
1994                 ob= base->object;
1995                 
1996                 if(ob->type == OB_LAMP)
1997                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
1998                 
1999                 if (ob->transflag & OB_DUPLI) {
2000                         DupliObject *dob;
2001                         ListBase *lb = object_duplilist(scene, ob);
2002                         
2003                         for(dob=lb->first; dob; dob=dob->next)
2004                                 if(dob->ob->type==OB_LAMP)
2005                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2006                         
2007                         free_object_duplilist(lb);
2008                 }
2009         }
2010         
2011         /* render shadows after updating all lamps, nested object_duplilist
2012                 * don't work correct since it's replacing object matrices */
2013         for(shadow=shadows.first; shadow; shadow=shadow->next) {
2014                 /* this needs to be done better .. */
2015                 float viewmat[4][4], winmat[4][4];
2016                 int drawtype, lay, winsize, flag2=v3d->flag2;
2017                 ARegion ar= {NULL};
2018                 RegionView3D rv3d= {{{0}}};
2019                 
2020                 drawtype= v3d->drawtype;
2021                 lay= v3d->lay;
2022                 
2023                 v3d->drawtype = OB_SOLID;
2024                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2025                 v3d->flag2 &= ~V3D_SOLID_TEX;
2026                 v3d->flag2 |= V3D_RENDER_OVERRIDE;
2027                 
2028                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2029
2030                 ar.regiondata= &rv3d;
2031                 ar.regiontype= RGN_TYPE_WINDOW;
2032                 rv3d.persp= RV3D_CAMOB;
2033                 copy_m4_m4(rv3d.winmat, winmat);
2034                 copy_m4_m4(rv3d.viewmat, viewmat);
2035                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2036                 mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2037                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2038
2039                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat);
2040                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2041                 
2042                 v3d->drawtype= drawtype;
2043                 v3d->lay= lay;
2044                 v3d->flag2 = flag2;
2045         }
2046         
2047         BLI_freelistN(&shadows);
2048 }
2049
2050 /* *********************** customdata **************** */
2051
2052 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2053 {
2054         CustomDataMask mask= 0;
2055         if(v3d->drawtype == OB_SHADED) {
2056                 /* this includes normals for mesh_create_shadedColors */
2057                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
2058         }
2059         if((v3d->drawtype == OB_TEXTURE) || ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX))) {
2060                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2061
2062                 if(scene->gm.matmode == GAME_MAT_GLSL)
2063                         mask |= CD_MASK_ORCO;
2064         }
2065
2066         return mask;
2067 }
2068 /* goes over all modes and view3d settings */
2069 CustomDataMask ED_viewedit_datamask(bScreen *screen)
2070 {
2071         Scene *scene= screen->scene;
2072         Object *ob= scene->basact ? scene->basact->object : NULL;
2073         CustomDataMask mask = CD_MASK_BAREMESH;
2074         ScrArea *sa;
2075         
2076         /* check if we need tfaces & mcols due to face select or texture paint */
2077         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
2078                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2079         
2080         /* check if we need tfaces & mcols due to view mode */
2081         for(sa = screen->areabase.first; sa; sa = sa->next) {
2082                 if(sa->spacetype == SPACE_VIEW3D) {
2083                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2084                 }
2085         }
2086         
2087         /* check if we need mcols due to vertex paint or weightpaint */
2088         if(ob) {
2089                 if(ob->mode & OB_MODE_VERTEX_PAINT)
2090                         mask |= CD_MASK_MCOL;
2091                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
2092                         mask |= CD_MASK_WEIGHT_MCOL;
2093         }
2094
2095         return mask;
2096 }
2097
2098 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2099 {
2100         RegionView3D *rv3d= ar->regiondata;
2101
2102         /* setup window matrices */
2103         if(winmat)
2104                 copy_m4_m4(rv3d->winmat, winmat);
2105         else
2106                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
2107         
2108         /* setup view matrix */
2109         if(viewmat)
2110                 copy_m4_m4(rv3d->viewmat, viewmat);
2111         else
2112                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
2113         
2114         /* update utilitity matrices */
2115         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
2116         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2117         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2118
2119         /* calculate pixelsize factor once, is used for lamps and obcenters */
2120         {
2121                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2122                  * because of float point precision problems at large values [#23908] */
2123                 float v1[3], v2[3];
2124                 float len1, len2;
2125
2126                 v1[0]= rv3d->persmat[0][0];
2127                 v1[1]= rv3d->persmat[1][0];
2128                 v1[2]= rv3d->persmat[2][0];
2129
2130                 v2[0]= rv3d->persmat[0][1];
2131                 v2[1]= rv3d->persmat[1][1];
2132                 v2[2]= rv3d->persmat[2][1];
2133                 
2134                 len1= 1.0f / len_v3(v1);
2135                 len2= 1.0f / len_v3(v2);
2136
2137                 rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
2138         }
2139
2140         /* set for opengl */
2141         glMatrixMode(GL_PROJECTION);
2142         glLoadMatrixf(rv3d->winmat);
2143         glMatrixMode(GL_MODELVIEW);
2144         glLoadMatrixf(rv3d->viewmat);
2145 }
2146
2147 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
2148 {
2149         Base *base;
2150         float backcol[3];
2151         int bwinx, bwiny;
2152         rcti brect;
2153
2154         glPushMatrix();
2155
2156         /* set temporary new size */
2157         bwinx= ar->winx;
2158         bwiny= ar->winy;
2159         brect= ar->winrct;
2160         
2161         ar->winx= winx;
2162         ar->winy= winy; 
2163         ar->winrct.xmin= 0;
2164         ar->winrct.ymin= 0;
2165         ar->winrct.xmax= winx;
2166         ar->winrct.ymax= winy;
2167         
2168         
2169         /* set flags */
2170         G.f |= G_RENDER_OGL;
2171
2172         /* free images which can have changed on frame-change
2173          * warning! can be slow so only free animated images - campbell */
2174         GPU_free_images_anim();
2175         
2176         /* shadow buffers, before we setup matrices */
2177         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2178                 gpu_update_lamps_shadows(scene, v3d);
2179
2180         /* set background color, fallback on the view background color */
2181         if(scene->world) {
2182                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2183                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2184                 else
2185                         copy_v3_v3(backcol, &scene->world->horr);
2186                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2187         }
2188         else {
2189                 UI_ThemeClearColor(TH_BACK);    
2190         }
2191
2192         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2193
2194         /* setup view matrices */
2195         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2196
2197         /* set zbuffer */
2198         if(v3d->drawtype > OB_WIRE) {
2199                 v3d->zbuf= TRUE;
2200                 glEnable(GL_DEPTH_TEST);
2201         }
2202         else
2203                 v3d->zbuf= FALSE;
2204
2205         /* draw set first */
2206         if(scene->set) {
2207                 Scene *sce_iter;
2208                 for(SETLOOPER(scene->set, sce_iter, base)) {
2209                         if(v3d->lay & base->lay) {
2210                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2211                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2212                                 
2213                                 if(base->object->transflag & OB_DUPLI)
2214                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2215                         }
2216                 }
2217         }
2218         
2219         /* then draw not selected and the duplis, but skip editmode object */
2220         for(base= scene->base.first; base; base= base->next) {
2221                 if(v3d->lay & base->lay) {
2222                         /* dupli drawing */
2223                         if(base->object->transflag & OB_DUPLI)
2224                                 draw_dupli_objects(scene, ar, v3d, base);
2225
2226                         draw_object(scene, ar, v3d, base, 0);
2227                 }
2228         }
2229
2230         /* must be before xray draw which clears the depth buffer */
2231         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2232         draw_gpencil_view3d_ext(scene, v3d, ar, 1);
2233         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2234
2235         /* transp and X-ray afterdraw stuff */
2236         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2237         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2238         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2239
2240         /* cleanup */
2241         if(v3d->zbuf) {
2242                 v3d->zbuf= FALSE;
2243                 glDisable(GL_DEPTH_TEST);
2244         }
2245
2246         /* draw grease-pencil stuff */
2247         ED_region_pixelspace(ar);
2248
2249         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2250         draw_gpencil_view3d_ext(scene, v3d, ar, 0);
2251
2252         /* freeing the images again here could be done after the operator runs, leaving for now */
2253         GPU_free_images_anim();
2254
2255         /* restore size */
2256         ar->winx= bwinx;
2257         ar->winy= bwiny;
2258         ar->winrct = brect;
2259
2260         glPopMatrix();
2261
2262         glColor4ub(255, 255, 255, 255); // XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell
2263
2264         G.f &= ~G_RENDER_OGL;
2265 }
2266
2267 /* utility func for ED_view3d_draw_offscreen */
2268 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey, unsigned int flag, char err_out[256])
2269 {
2270         RegionView3D *rv3d= ar->regiondata;
2271         ImBuf *ibuf;
2272         GPUOffScreen *ofs;
2273         
2274         /* state changes make normal drawing go weird otherwise */
2275         glPushAttrib(GL_LIGHTING_BIT);
2276
2277         /* bind */
2278         ofs= GPU_offscreen_create(&sizex, &sizey, err_out);
2279         if(ofs == NULL)
2280                 return NULL;
2281
2282         GPU_offscreen_bind(ofs);
2283
2284         /* render 3d view */
2285         if(rv3d->persp==RV3D_CAMOB && v3d->camera) {
2286                 float winmat[4][4];
2287                 float _clipsta, _clipend, _lens, _yco, _dx, _dy;
2288                 rctf _viewplane;
2289
2290                 object_camera_matrix(&scene->r, v3d->camera, sizex, sizey, 0, winmat, &_viewplane, &_clipsta, &_clipend, &_lens, &_yco, &_dx, &_dy);
2291
2292                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
2293         }
2294         else {
2295                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL);
2296         }
2297
2298         /* read in pixels & stamp */
2299         ibuf= IMB_allocImBuf(sizex, sizey, 32, flag);
2300
2301         if(ibuf->rect_float)
2302                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2303         else if(ibuf->rect)
2304                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2305         
2306         //if((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
2307         //      BKE_stamp_buf(scene, NULL, rr->rectf, rr->rectx, rr->recty, 4);
2308
2309         /* unbind */
2310         GPU_offscreen_unbind(ofs);
2311         GPU_offscreen_free(ofs);
2312
2313         glPopAttrib();
2314         
2315         if(ibuf->rect_float && ibuf->rect)
2316                 IMB_rect_from_float(ibuf);
2317         
2318         return ibuf;
2319 }
2320
2321 /* creates own 3d views, used by the sequencer */
2322 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height, unsigned int flag, int drawtype, char err_out[256])
2323 {
2324         View3D v3d= {NULL};
2325         ARegion ar= {NULL};
2326         RegionView3D rv3d= {{{0}}};
2327
2328         /* connect data */
2329         v3d.regionbase.first= v3d.regionbase.last= &ar;
2330         ar.regiondata= &rv3d;
2331         ar.regiontype= RGN_TYPE_WINDOW;
2332
2333         v3d.camera= camera;
2334         v3d.lay= scene->lay;
2335         v3d.drawtype = drawtype;
2336         v3d.flag2 = V3D_RENDER_OVERRIDE;
2337
2338         rv3d.persp= RV3D_CAMOB;
2339
2340         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2341         normalize_m4(rv3d.viewinv);
2342         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2343
2344         {
2345                 float _yco, _dx, _dy;
2346                 rctf _viewplane;
2347                 object_camera_matrix(&scene->r, v3d.camera, width, height, 0, rv3d.winmat, &_viewplane, &v3d.near, &v3d.far, &v3d.lens, &_yco, &_dx, &_dy);
2348         }
2349
2350         mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2351         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2352
2353         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag, err_out);
2354
2355         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2356 }
2357
2358
2359 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2360  * which currently gets called during SCREEN_OT_animation_step.
2361  */
2362 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2363 {
2364         ScreenFrameRateInfo *fpsi= scene->fps_info;
2365         float fps;
2366         char printable[16];
2367         int i, tot;
2368         
2369         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2370                 return;
2371         
2372         printable[0] = '\0';
2373         
2374 #if 0
2375         /* this is too simple, better do an average */
2376         fps = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime))
2377 #else
2378         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime));
2379         
2380         for (i=0, tot=0, fps=0.0f ; i < REDRAW_FRAME_AVERAGE ; i++) {
2381                 if (fpsi->redrawtimes_fps[i]) {
2382                         fps += fpsi->redrawtimes_fps[i];
2383                         tot++;
2384                 }
2385         }
2386         if (tot) {
2387                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2388                 
2389                 //fpsi->redrawtime_index++;
2390                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2391                 //      fpsi->redrawtime = 0;
2392                 
2393                 fps = fps / tot;
2394         }
2395 #endif
2396
2397         /* is this more then half a frame behind? */
2398         if (fps+0.5f < (float)(FPS)) {
2399                 UI_ThemeColor(TH_REDALERT);
2400                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2401         } 
2402         else {
2403                 UI_ThemeColor(TH_TEXT_HI);
2404                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps+0.5f));
2405         }
2406         
2407         BLF_draw_default(22,  ar->winy-17, 0.0f, printable, sizeof(printable)-1);
2408 }
2409
2410 /* warning: this function has duplicate drawing in ED_view3d_draw_offscreen() */
2411 void view3d_main_area_draw(const bContext *C, ARegion *ar)
2412 {
2413         Scene *scene= CTX_data_scene(C);
2414         View3D *v3d = CTX_wm_view3d(C);
2415         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2416         Base *base;
2417         Object *ob;
2418         float backcol[3];
2419         unsigned int lay_used;
2420         const char *grid_unit= NULL;
2421
2422         /* shadow buffers, before we setup matrices */
2423         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2424                 gpu_update_lamps_shadows(scene, v3d);
2425         
2426         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2427         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2428                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2429                 GPU_default_lights();
2430         }
2431
2432         /* clear background */
2433         if((v3d->flag2 & V3D_RENDER_OVERRIDE) && scene->world) {
2434                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2435                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2436                 else
2437                         copy_v3_v3(backcol, &scene->world->horr);
2438                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2439         }
2440         else
2441                 UI_ThemeClearColor(TH_BACK);
2442
2443         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2444         
2445         /* setup view matrices */
2446         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2447
2448         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2449
2450         if(rv3d->rflag & RV3D_CLIPPING)
2451                 view3d_draw_clipping(rv3d);
2452         
2453         /* set zbuffer after we draw clipping region */
2454         if(v3d->drawtype > OB_WIRE) {
2455                 v3d->zbuf= TRUE;
2456                 glEnable(GL_DEPTH_TEST);
2457         }
2458         else
2459                 v3d->zbuf= FALSE;
2460
2461         /* enables anti-aliasing for 3D view drawing */
2462         /*if (!(U.gameflags & USER_DISABLE_AA))
2463                 glEnable(GL_MULTISAMPLE_ARB);*/
2464         
2465         // needs to be done always, gridview is adjusted in drawgrid() now
2466         rv3d->gridview= v3d->grid;
2467
2468         if(rv3d->view==0 || rv3d->persp != RV3D_ORTHO) {
2469                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2470                         drawfloor(scene, v3d, &grid_unit);
2471                 }
2472                 if(rv3d->persp==RV3D_CAMOB) {
2473                         if(scene->world) {
2474                                 if(scene->world->mode & WO_STARS) {
2475                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2476                                                                   star_stuff_term_func);
2477                                 }
2478                         }
2479                         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2480                                 if(v3d->flag & V3D_DISPBGPICS) draw_bgpic(scene, ar, v3d);
2481                         }
2482                 }
2483         }
2484         else {
2485                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2486                         ED_region_pixelspace(ar);
2487                         drawgrid(&scene->unit, ar, v3d, &grid_unit);
2488                         /* XXX make function? replaces persp(1) */
2489                         glMatrixMode(GL_PROJECTION);
2490                         glLoadMatrixf(rv3d->winmat);
2491                         glMatrixMode(GL_MODELVIEW);
2492                         glLoadMatrixf(rv3d->viewmat);
2493
2494                         if(v3d->flag & V3D_DISPBGPICS) {
2495                                 draw_bgpic(scene, ar, v3d);
2496                         }
2497                 }
2498         }
2499         
2500         if(rv3d->rflag & RV3D_CLIPPING)
2501                 view3d_set_clipping(rv3d);
2502
2503         /* draw set first */
2504         if(scene->set) {
2505                 Scene *sce_iter;
2506                 for(SETLOOPER(scene->set, sce_iter, base)) {
2507                         
2508                         if(v3d->lay & base->lay) {
2509                                 
2510                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2511                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2512                                 
2513                                 if(base->object->transflag & OB_DUPLI) {
2514                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2515                                 }
2516                         }
2517                 }
2518                 
2519                 /* Transp and X-ray afterdraw stuff for sets is done later */
2520         }
2521
2522         lay_used= 0;
2523
2524         /* then draw not selected and the duplis, but skip editmode object */
2525         for(base= scene->base.first; base; base= base->next) {
2526                 lay_used |= base->lay & ((1<<20)-1);
2527
2528                 if(v3d->lay & base->lay) {
2529                         
2530                         /* dupli drawing */
2531                         if(base->object->transflag & OB_DUPLI) {
2532                                 draw_dupli_objects(scene, ar, v3d, base);
2533                         }
2534                         if((base->flag & SELECT)==0) {
2535                                 if(base->object!=scene->obedit) 
2536                                         draw_object(scene, ar, v3d, base, 0);
2537                         }
2538                 }
2539         }
2540
2541         if(v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2542                 ARegion *ar_iter;
2543                 ScrArea *sa= CTX_wm_area(C);
2544
2545                 /* find header and force tag redraw */
2546                 for(ar_iter= sa->regionbase.first; ar_iter; ar_iter= ar_iter->next)
2547                         if(ar_iter->regiontype==RGN_TYPE_HEADER) {
2548                                 ED_region_tag_redraw(ar_iter);
2549                                 break;
2550                         }
2551
2552                 v3d->lay_used= lay_used;
2553         }
2554
2555         /* draw selected and editmode */
2556         for(base= scene->base.first; base; base= base->next) {
2557                 if(v3d->lay & base->lay) {
2558                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2559                                 draw_object(scene, ar, v3d, base, 0);
2560                 }
2561         }
2562
2563 //      REEB_draw();
2564
2565         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2566                 /* must be before xray draw which clears the depth buffer */
2567                 if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2568                 draw_gpencil_view3d((bContext *)C, 1);
2569                 if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2570         }
2571
2572         /* Transp and X-ray afterdraw stuff */
2573         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2574         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2575         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2576         
2577         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2578
2579         if(rv3d->rflag & RV3D_CLIPPING)
2580                 view3d_clr_clipping();
2581         
2582         BIF_draw_manipulator(C);
2583         
2584         /* Disable back anti-aliasing */
2585         /*if (!(U.gameflags & USER_DISABLE_AA))
2586                 glDisable(GL_MULTISAMPLE_ARB);*/
2587
2588         if(v3d->zbuf) {
2589                 v3d->zbuf= FALSE;
2590                 glDisable(GL_DEPTH_TEST);
2591         }
2592
2593         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2594                 BDR_drawSketch(C);
2595         }
2596
2597         ED_region_pixelspace(ar);
2598         
2599 //      retopo_paint_view_update(v3d);
2600 //      retopo_draw_paint_lines();
2601         
2602         /* Draw particle edit brush XXX (removed) */
2603         
2604
2605         if(rv3d->persp==RV3D_CAMOB)
2606                 drawviewborder(scene, ar, v3d);
2607
2608         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2609                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2610         //      if (v3d->flag2 & V3D_DISPGP)
2611                         draw_gpencil_view3d((bContext *)C, 0);
2612
2613                 drawcursor(scene, ar, v3d);
2614         }
2615         
2616         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2617                 draw_view_axis(rv3d);
2618         else    
2619                 draw_view_icon(rv3d);
2620         
2621         if((U.uiflag & USER_SHOW_FPS) && (CTX_wm_screen(C)->animtimer)) {
2622                 draw_viewport_fps(scene, ar);
2623         }
2624         else if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2625                 draw_viewport_name(ar, v3d);
2626         }
2627         if (grid_unit) { /* draw below the viewport name */
2628                 char tstr[32]= "";
2629
2630                 UI_ThemeColor(TH_TEXT_HI);
2631                 if(v3d->grid != 1.0f) {
2632                         BLI_snprintf(tstr, sizeof(tstr), "%s x %.4g", grid_unit, v3d->grid);
2633                 }
2634
2635                 BLF_draw_default(22,  ar->winy-(USER_SHOW_VIEWPORTNAME?40:20), 0.0f, tstr[0]?tstr : grid_unit, sizeof(tstr)); /* XXX, use real length */
2636         }
2637
2638         ob= OBACT;
2639         if(U.uiflag & USER_DRAWVIEWINFO) 
2640                 draw_selected_name(scene, ob, v3d);
2641         
2642         /* XXX here was the blockhandlers for floating panels */
2643
2644         v3d->flag |= V3D_INVALID_BACKBUF;
2645 }