a45dfe8a281141eee80d11b8b1528b58348a001e
[blender-staging.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
1002         /* note: quite un-scientific but without this bit extra
1003          * 0.0001 on the lower left the 2D border sometimes
1004          * obscures the 3D camera border */
1005         x1i= (int)(x1 - 1.0001f);
1006         y1i= (int)(y1 - 1.0001f);
1007         x2i= (int)(x2 + 1.0f);
1008         y2i= (int)(y2 + 1.0f);
1009         
1010         /* passepartout, specified in camera edit buttons */
1011         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
1012                 if (ca->passepartalpha == 1.0f) {
1013                         glColor3f(0, 0, 0);
1014                 } else {
1015                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1016                         glEnable(GL_BLEND);
1017                         glColor4f(0, 0, 0, ca->passepartalpha);
1018                 }
1019                 if (x1i > 0.0f)
1020                         glRectf(0.0, (float)ar->winy, x1i, 0.0);
1021                 if (x2i < (float)ar->winx)
1022                         glRectf(x2i, (float)ar->winy, (float)ar->winx, 0.0);
1023                 if (y2i < (float)ar->winy)
1024                         glRectf(x1i, (float)ar->winy, x2i, y2i);
1025                 if (y2i > 0.0f)
1026                         glRectf(x1i, y1i, x2i, 0.0);
1027                 
1028                 glDisable(GL_BLEND);
1029         }
1030
1031         /* edge */
1032         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);      
1033
1034         setlinestyle(0);
1035         UI_ThemeColor(TH_BACK);
1036         glRectf(x1i, y1i, x2i, y2i);
1037         
1038         setlinestyle(3);
1039         UI_ThemeColor(TH_WIRE);
1040         glRectf(x1i, y1i, x2i, y2i);
1041
1042         /* border */
1043         if(scene->r.mode & R_BORDER) {
1044                 
1045                 cpack(0);
1046                 x3= x1+ scene->r.border.xmin*(x2-x1);
1047                 y3= y1+ scene->r.border.ymin*(y2-y1);
1048                 x4= x1+ scene->r.border.xmax*(x2-x1);
1049                 y4= y1+ scene->r.border.ymax*(y2-y1);
1050                 
1051                 cpack(0x4040FF);
1052                 glRectf(x3,  y3,  x4,  y4); 
1053         }
1054
1055         /* safety border */
1056         if(ca) {
1057                 if (ca->dtx & CAM_DTX_CENTER) {
1058                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1059
1060                         x3= x1+ 0.5f*(x2-x1);
1061                         y3= y1+ 0.5f*(y2-y1);
1062
1063                         glBegin(GL_LINES);
1064                         glVertex2f(x1, y3);
1065                         glVertex2f(x2, y3);
1066
1067                         glVertex2f(x3, y1);
1068                         glVertex2f(x3, y2);
1069                         glEnd();
1070                 }
1071
1072                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
1073                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1074
1075                         glBegin(GL_LINES);
1076                         glVertex2f(x1, y1);
1077                         glVertex2f(x2, y2);
1078
1079                         glVertex2f(x1, y2);
1080                         glVertex2f(x2, y1);
1081                         glEnd();
1082                 }
1083
1084                 if (ca->dtx & CAM_DTX_THIRDS) {
1085                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1086                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f/3.0f, '\0');
1087                 }
1088
1089                 if (ca->dtx & CAM_DTX_GOLDEN) {
1090                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1091                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), '\0');
1092                 }
1093
1094                 if (ca->dtx & CAM_DTX_GOLDEN_DIAG_H) {
1095                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1096                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), 'H');
1097                 }
1098
1099                 if (ca->dtx & CAM_DTX_GOLDEN_DIAG_V) {
1100                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1101                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f-(1.0f/1.61803399), 'V');
1102                 }
1103
1104                 if (ca->flag & CAM_SHOWTITLESAFE) {
1105                         fac= 0.1;
1106
1107                         a= fac*(x2-x1);
1108                         x1+= a;
1109                         x2-= a;
1110
1111                         a= fac*(y2-y1);
1112                         y1+= a;
1113                         y2-= a;
1114
1115                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1116
1117                         uiSetRoundBox(15);
1118                         uiDrawBox(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1119                 }
1120         }
1121
1122         setlinestyle(0);
1123         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1124
1125         /* camera name - draw in highlighted text color */
1126         if (ca && (ca->flag & CAM_SHOWNAME)) {
1127                 UI_ThemeColor(TH_TEXT_HI);
1128                 BLF_draw_default(x1i, y1i-15, 0.0f, v3d->camera->id.name+2, sizeof(v3d->camera->id.name)-2);
1129                 UI_ThemeColor(TH_WIRE);
1130         }
1131 }
1132
1133 /* *********************** backdraw for selection *************** */
1134
1135 static void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1136 {
1137         RegionView3D *rv3d= ar->regiondata;
1138         struct Base *base = scene->basact;
1139         rcti winrct;
1140
1141         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1142                          paint_facesel_test(base->object)));
1143         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1144                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1145         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1146         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1147         else {
1148                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1149                 return;
1150         }
1151
1152         if( !(v3d->flag & V3D_INVALID_BACKBUF) ) return;
1153
1154 //      if(test) {
1155 //              if(qtest()) {
1156 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1157 //                      return;
1158 //              }
1159 //      }
1160
1161         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1162         
1163         glDisable(GL_DITHER);
1164
1165         region_scissor_winrct(ar, &winrct);
1166         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1167
1168         glClearColor(0.0, 0.0, 0.0, 0.0); 
1169         if(v3d->zbuf) {
1170                 glEnable(GL_DEPTH_TEST);
1171                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1172         }
1173         else {
1174                 glClear(GL_COLOR_BUFFER_BIT);
1175                 glDisable(GL_DEPTH_TEST);
1176         }
1177         
1178         if(rv3d->rflag & RV3D_CLIPPING)
1179                 view3d_set_clipping(rv3d);
1180         
1181         G.f |= G_BACKBUFSEL;
1182         
1183         if(base && (base->lay & v3d->lay)) {
1184                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1185         }
1186
1187         v3d->flag &= ~V3D_INVALID_BACKBUF;
1188         ar->swap= 0; /* mark invalid backbuf for wm draw */
1189
1190         G.f &= ~G_BACKBUFSEL;
1191         v3d->zbuf= FALSE; 
1192         glDisable(GL_DEPTH_TEST);
1193         glEnable(GL_DITHER);
1194
1195         if(rv3d->rflag & RV3D_CLIPPING)
1196                 view3d_clr_clipping();
1197
1198         /* it is important to end a view in a transform compatible with buttons */
1199 //      persp(PERSP_WIN);  // set ortho
1200
1201 }
1202
1203 void view3d_validate_backbuf(ViewContext *vc)
1204 {
1205         if(vc->v3d->flag & V3D_INVALID_BACKBUF)
1206                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1207 }
1208
1209 /* samples a single pixel (copied from vpaint) */
1210 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1211 {
1212         unsigned int col;
1213         
1214         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1215         x+= vc->ar->winrct.xmin;
1216         y+= vc->ar->winrct.ymin;
1217         
1218         view3d_validate_backbuf(vc);
1219
1220         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1221         glReadBuffer(GL_BACK);  
1222         
1223         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1224         
1225         return WM_framebuffer_to_index(col);
1226 }
1227
1228 /* reads full rect, converts indices */
1229 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1230 {
1231         unsigned int *dr, *rd;
1232         struct ImBuf *ibuf, *ibuf1;
1233         int a;
1234         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1235         
1236         /* clip */
1237         if(xmin<0) xminc= 0; else xminc= xmin;
1238         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1239         if(xminc > xmaxc) return NULL;
1240
1241         if(ymin<0) yminc= 0; else yminc= ymin;
1242         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1243         if(yminc > ymaxc) return NULL;
1244         
1245         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect);
1246
1247         view3d_validate_backbuf(vc); 
1248         
1249         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1250         glReadBuffer(GL_BACK);  
1251
1252         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1253
1254         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1255         dr= ibuf->rect;
1256         while(a--) {
1257                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1258                 dr++;
1259         }
1260         
1261         /* put clipped result back, if needed */
1262         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1263                 return ibuf;
1264         
1265         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect);
1266         rd= ibuf->rect;
1267         dr= ibuf1->rect;
1268                 
1269         for(ys= ymin; ys<=ymax; ys++) {
1270                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1271                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1272                                 *dr= *rd;
1273                                 rd++;
1274                         }
1275                 }
1276         }
1277         IMB_freeImBuf(ibuf);
1278         return ibuf1;
1279 }
1280
1281 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1282 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const short mval[2], int size,
1283                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1284                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1285 {
1286         struct ImBuf *buf;
1287         unsigned int *bufmin, *bufmax, *tbuf;
1288         int minx, miny;
1289         int a, b, rc, nr, amount, dirvec[4][2];
1290         int distance=0;
1291         unsigned int index = 0;
1292         short indexok = 0;      
1293
1294         amount= (size-1)/2;
1295
1296         minx = mval[0]-(amount+1);
1297         miny = mval[1]-(amount+1);
1298         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1299         if (!buf) return 0;
1300
1301         rc= 0;
1302         
1303         dirvec[0][0]= 1; dirvec[0][1]= 0;
1304         dirvec[1][0]= 0; dirvec[1][1]= -size;
1305         dirvec[2][0]= -1; dirvec[2][1]= 0;
1306         dirvec[3][0]= 0; dirvec[3][1]= size;
1307         
1308         bufmin = buf->rect;
1309         tbuf = buf->rect;
1310         bufmax = buf->rect + size*size;
1311         tbuf+= amount*size+ amount;
1312         
1313         for(nr=1; nr<=size; nr++) {
1314                 
1315                 for(a=0; a<2; a++) {
1316                         for(b=0; b<nr; b++, distance++) {
1317                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1318                                         if(strict){
1319                                                 indexok =  indextest(handle, *tbuf - min+1);
1320                                                 if(indexok){
1321                                                         *dist= (short) sqrt( (float)distance   );
1322                                                         index = *tbuf - min+1;
1323                                                         goto exit; 
1324                                                 }                                               
1325                                         }
1326                                         else{
1327                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1328                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1329                                                 goto exit;
1330                                         }                       
1331                                 }
1332                                 
1333                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1334                                 
1335                                 if(tbuf<bufmin || tbuf>=bufmax) {
1336                                         goto exit;
1337                                 }
1338                         }
1339                         rc++;
1340                         rc &= 3;
1341                 }
1342         }
1343
1344 exit:
1345         IMB_freeImBuf(buf);
1346         return index;
1347 }
1348
1349
1350 /* ************************************************************* */
1351
1352 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1353 {
1354         RegionView3D *rv3d= ar->regiondata;
1355         BGpic *bgpic;
1356         Image *ima;
1357         ImBuf *ibuf= NULL;
1358         float vec[4], fac, asp, zoomx, zoomy;
1359         float x1, y1, x2, y2, cx, cy;
1360
1361
1362         for ( bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next ) {
1363
1364                 if(     (bgpic->view == 0) || /* zero for any */
1365                         (bgpic->view & (1<<rv3d->view)) || /* check agaist flags */
1366                         (rv3d->persp==RV3D_CAMOB && bgpic->view == (1<<RV3D_VIEW_CAMERA))
1367                 ) {
1368                         ima= bgpic->ima;
1369                         if(ima==NULL)
1370                                 continue;
1371                         BKE_image_user_calc_frame(&bgpic->iuser, CFRA, 0);
1372                         ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1373                         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) )
1374                                 continue;
1375                         if(ibuf->channels!=4)
1376                                 continue;
1377                         if(ibuf->rect==NULL)
1378                                 IMB_rect_from_float(ibuf);
1379
1380                         if(rv3d->persp==RV3D_CAMOB) {
1381                                 rctf vb;
1382
1383                                 view3d_calc_camera_border(scene, ar, rv3d, v3d, &vb, FALSE);
1384
1385                                 x1= vb.xmin;
1386                                 y1= vb.ymin;
1387                                 x2= vb.xmax;
1388                                 y2= vb.ymax;
1389                         }
1390                         else {
1391                                 float sco[2];
1392
1393                                 /* calc window coord */
1394                                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1395                                 window_to_3d_delta(ar, vec, 1, 0);
1396                                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1397                                 fac= 1.0f/fac;
1398
1399                                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1400
1401                                 vec[0] = vec[1] = vec[2] = 0.0;
1402                                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1403                                 cx = sco[0];
1404                                 cy = sco[1];
1405
1406                                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1407                                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1408                                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1409                                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1410                         }
1411
1412                         /* complete clip? */
1413
1414                         if(x2 < 0 ) continue;
1415                         if(y2 < 0 ) continue;
1416                         if(x1 > ar->winx ) continue;
1417                         if(y1 > ar->winy ) continue;
1418
1419                         zoomx= (x2-x1)/ibuf->x;
1420                         zoomy= (y2-y1)/ibuf->y;
1421
1422                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1423                         if(zoomx < 1.0f || zoomy < 1.0f) {
1424                                 float tzoom= MIN2(zoomx, zoomy);
1425                                 int mip= 0;
1426
1427                                 if((ibuf->userflags&IB_MIPMAP_INVALID) != 0) {
1428                                         IMB_remakemipmap(ibuf, 0);
1429                                         ibuf->userflags&= ~IB_MIPMAP_INVALID;
1430                                 }
1431                                 else if(ibuf->mipmap[0]==NULL)
1432                                         IMB_makemipmap(ibuf, 0);
1433
1434                                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1435                                         tzoom*= 2.0f;
1436                                         zoomx*= 2.0f;
1437                                         zoomy*= 2.0f;
1438                                         mip++;
1439                                 }
1440                                 if(mip>0)
1441                                         ibuf= ibuf->mipmap[mip-1];
1442                         }
1443
1444                         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1445                         glDepthMask(0);
1446
1447                         glEnable(GL_BLEND);
1448                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1449
1450                         glMatrixMode(GL_PROJECTION);
1451                         glPushMatrix();
1452                         glMatrixMode(GL_MODELVIEW);
1453                         glPushMatrix();
1454                         ED_region_pixelspace(ar);
1455
1456                         glPixelZoom(zoomx, zoomy);
1457                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f-bgpic->blend);
1458                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1459
1460                         glPixelZoom(1.0, 1.0);
1461                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1462
1463                         glMatrixMode(GL_PROJECTION);
1464                         glPopMatrix();
1465                         glMatrixMode(GL_MODELVIEW);
1466                         glPopMatrix();
1467
1468                         glDisable(GL_BLEND);
1469
1470                         glDepthMask(1);
1471                         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1472                 }
1473         }
1474 }
1475
1476 /* ****************** View3d afterdraw *************** */
1477
1478 typedef struct View3DAfter {
1479         struct View3DAfter *next, *prev;
1480         struct Base *base;
1481         int flag;
1482 } View3DAfter;
1483
1484 /* temp storage of Objects that need to be drawn as last */
1485 void add_view3d_after(ListBase *lb, Base *base, int flag)
1486 {
1487         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1488         BLI_addtail(lb, v3da);
1489         v3da->base= base;
1490         v3da->flag= flag;
1491 }
1492
1493 /* disables write in zbuffer and draws it over */
1494 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1495 {
1496         View3DAfter *v3da, *next;
1497         
1498         glDepthMask(0);
1499         v3d->transp= TRUE;
1500         
1501         for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
1502                 next= v3da->next;
1503                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1504                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1505                 MEM_freeN(v3da);
1506         }
1507         v3d->transp= FALSE;
1508         
1509         glDepthMask(1);
1510         
1511 }
1512
1513 /* clears zbuffer and draws it over */
1514 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1515 {
1516         View3DAfter *v3da, *next;
1517
1518         if(clear && v3d->zbuf)
1519                 glClear(GL_DEPTH_BUFFER_BIT);
1520
1521         v3d->xray= TRUE;
1522         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1523                 next= v3da->next;
1524                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1525                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1526                 MEM_freeN(v3da);
1527         }
1528         v3d->xray= FALSE;
1529 }
1530
1531
1532 /* clears zbuffer and draws it over */
1533 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1534 {
1535         View3DAfter *v3da, *next;
1536
1537         if(clear && v3d->zbuf)
1538                 glClear(GL_DEPTH_BUFFER_BIT);
1539
1540         v3d->xray= TRUE;
1541         v3d->transp= TRUE;
1542         
1543         for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
1544                 next= v3da->next;
1545                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1546                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1547                 MEM_freeN(v3da);
1548         }
1549
1550         v3d->transp= FALSE;
1551         v3d->xray= FALSE;
1552
1553 }
1554
1555 /* *********************** */
1556
1557 /*
1558         In most cases call draw_dupli_objects,
1559         draw_dupli_objects_color was added because when drawing set dupli's
1560         we need to force the color
1561  */
1562
1563 #if 0
1564 int dupli_ob_sort(void *arg1, void *arg2)
1565 {
1566         void *p1= ((DupliObject *)arg1)->ob;
1567         void *p2= ((DupliObject *)arg2)->ob;
1568         int val = 0;
1569         if (p1 < p2)            val = -1;
1570         else if (p1 > p2)       val = 1;
1571         return val;
1572 }
1573 #endif
1574
1575
1576 static DupliObject *dupli_step(DupliObject *dob)
1577 {
1578         while(dob && dob->no_draw)
1579                 dob= dob->next;
1580         return dob;
1581 }
1582
1583 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1584 {
1585         RegionView3D *rv3d= ar->regiondata;
1586         ListBase *lb;
1587         DupliObject *dob_prev= NULL, *dob, *dob_next= NULL;
1588         Base tbase;
1589         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1590         GLuint displist=0;
1591         short transflag, use_displist= -1;      /* -1 is initialize */
1592         char dt, dtx;
1593         
1594         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1595         
1596         tbase.flag= OB_FROMDUPLI|base->flag;
1597         lb= object_duplilist(scene, base->object);
1598         // BLI_sortlist(lb, dupli_ob_sort); // might be nice to have if we have a dupli list with mixed objects.
1599
1600         dob=dupli_step(lb->first);
1601         if(dob) dob_next= dupli_step(dob->next);
1602
1603         for( ; dob ; dob_prev= dob, dob= dob_next, dob_next= dob_next ? dupli_step(dob_next->next) : NULL) {
1604                 tbase.object= dob->ob;
1605
1606                 /* extra service: draw the duplicator in drawtype of parent */
1607                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1608                 dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1609                 dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1610
1611                 /* negative scale flag has to propagate */
1612                 transflag= tbase.object->transflag;
1613                 if(base->object->transflag & OB_NEG_SCALE)
1614                         tbase.object->transflag ^= OB_NEG_SCALE;
1615
1616                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1617
1618                 /* generate displist, test for new object */
1619                 if(dob_prev && dob_prev->ob != dob->ob) {
1620                         if(use_displist==1)
1621                                 glDeleteLists(displist, 1);
1622
1623                         use_displist= -1;
1624                 }
1625
1626                 /* generate displist */
1627                 if(use_displist == -1) {
1628
1629                         /* note, since this was added, its checked dob->type==OB_DUPLIGROUP
1630                          * however this is very slow, it was probably needed for the NLA
1631                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1632                          * so for now it should be ok to - campbell */
1633
1634                         if(             (dob_next==NULL || dob_next->ob != dob->ob) || /* if this is the last no need  to make a displist */
1635                                         (dob->ob->type == OB_LAMP) || /* lamp drawing messes with matrices, could be handled smarter... but this works */
1636                                         (dob->type == OB_DUPLIGROUP && dob->animated) ||
1637                                         !(bb_tmp= object_get_boundbox(dob->ob))
1638                         ) {
1639                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1640                                 use_displist= 0;
1641                         }
1642                         else {
1643                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1644                                 bb= *bb_tmp; /* must make a copy  */
1645
1646                                 /* disable boundbox check for list creation */
1647                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1648                                 /* need this for next part of code */
1649                                 unit_m4(dob->ob->obmat);        /* obmat gets restored */
1650
1651                                 displist= glGenLists(1);
1652                                 glNewList(displist, GL_COMPILE);
1653                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1654                                 glEndList();
1655
1656                                 use_displist= 1;
1657                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1658                         }
1659                 }
1660                 if(use_displist) {
1661                         glMultMatrixf(dob->mat);
1662                         if(boundbox_clip(rv3d, dob->mat, &bb))
1663                                 glCallList(displist);
1664                         glLoadMatrixf(rv3d->viewmat);
1665                 }
1666                 else {
1667                         copy_m4_m4(dob->ob->obmat, dob->mat);
1668                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1669                 }
1670
1671                 tbase.object->dt= dt;
1672                 tbase.object->dtx= dtx;
1673                 tbase.object->transflag= transflag;
1674         }
1675         
1676         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1677         
1678         free_object_duplilist(lb);      /* does restore */
1679         
1680         if(use_displist)
1681                 glDeleteLists(displist, 1);
1682 }
1683
1684 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1685 {
1686         /* define the color here so draw_dupli_objects_color can be called
1687         * from the set loop */
1688         
1689         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1690         /* debug */
1691         if(base->object->dup_group && base->object->dup_group->id.us<1)
1692                 color= TH_REDALERT;
1693         
1694         draw_dupli_objects_color(scene, ar, v3d, base, color);
1695 }
1696
1697 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1698 {
1699         int x, y, w, h; 
1700         rcti r;
1701         /* clamp rect by area */
1702
1703         r.xmin= 0;
1704         r.xmax= ar->winx-1;
1705         r.ymin= 0;
1706         r.ymax= ar->winy-1;
1707
1708         /* Constrain rect to depth bounds */
1709         BLI_isect_rcti(&r, rect, rect);
1710
1711         /* assign values to compare with the ViewDepths */
1712         x= rect->xmin;
1713         y= rect->ymin;
1714
1715         w= rect->xmax - rect->xmin;
1716         h= rect->ymax - rect->ymin;
1717
1718         if(w <= 0 || h <= 0) {
1719                 if(d->depths)
1720                         MEM_freeN(d->depths);
1721                 d->depths= NULL;
1722
1723                 d->damaged= FALSE;
1724         }
1725         else if(        d->w != w ||
1726                 d->h != h ||
1727                 d->x != x ||
1728                 d->y != y ||
1729                 d->depths==NULL
1730         ) {
1731                 d->x= x;
1732                 d->y= y;
1733                 d->w= w;
1734                 d->h= h;
1735
1736                 if(d->depths)
1737                         MEM_freeN(d->depths);
1738
1739                 d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths Subset");
1740                 
1741                 d->damaged= TRUE;
1742         }
1743
1744         if(d->damaged) {
1745                 glReadPixels(ar->winrct.xmin+d->x,ar->winrct.ymin+d->y, d->w,d->h, GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1746                 glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1747                 d->damaged= FALSE;
1748         }
1749 }
1750
1751 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1752 void view3d_update_depths(ARegion *ar)
1753 {
1754         RegionView3D *rv3d= ar->regiondata;
1755         
1756         /* Create storage for, and, if necessary, copy depth buffer */
1757         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1758         if(rv3d->depths) {
1759                 ViewDepths *d= rv3d->depths;
1760                 if(d->w != ar->winx ||
1761                    d->h != ar->winy ||
1762                    !d->depths) {
1763                         d->w= ar->winx;
1764                         d->h= ar->winy;
1765                         if(d->depths)
1766                                 MEM_freeN(d->depths);
1767                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1768                         d->damaged= 1;
1769                 }
1770                 
1771                 if(d->damaged) {
1772                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1773                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1774                         
1775                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1776                         
1777                         d->damaged= 0;
1778                 }
1779         }
1780 }
1781
1782 /* utility function to find the closest Z value, use for autodepth */
1783 float view3d_depth_near(ViewDepths *d)
1784 {
1785         /* convert to float for comparisons */
1786         const float near= (float)d->depth_range[0];
1787         const float far_real= (float)d->depth_range[1];
1788         float far= far_real;
1789
1790         const float *depths= d->depths;
1791         float depth= FLT_MAX;
1792         int i= (int)d->w * (int)d->h; /* cast to avoid short overflow */
1793
1794         /* far is both the starting 'far' value
1795          * and the closest value found. */      
1796         while(i--) {
1797                 depth= *depths++;
1798                 if((depth < far) && (depth > near)) {
1799                         far= depth;
1800                 }
1801         }
1802
1803         return far == far_real ? FLT_MAX : far;
1804 }
1805
1806 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1807 {
1808         short zbuf= v3d->zbuf;
1809         RegionView3D *rv3d= ar->regiondata;
1810
1811         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1812         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1813
1814         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1815         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1816         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1817
1818         glClear(GL_DEPTH_BUFFER_BIT);
1819
1820         glLoadMatrixf(rv3d->viewmat);
1821
1822         v3d->zbuf= TRUE;
1823         glEnable(GL_DEPTH_TEST);
1824
1825         draw_gpencil_view3d_ext(scene, v3d, ar, 1);
1826         
1827         v3d->zbuf= zbuf;
1828
1829 }
1830
1831 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1832 {
1833         RegionView3D *rv3d= ar->regiondata;
1834         Base *base;
1835         short zbuf= v3d->zbuf;
1836         short flag= v3d->flag;
1837         float glalphaclip= U.glalphaclip;
1838         int obcenter_dia= U.obcenter_dia;
1839         /* temp set drawtype to solid */
1840         
1841         /* Setting these temporarily is not nice */
1842         v3d->flag &= ~V3D_SELECT_OUTLINE;
1843         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1844         U.obcenter_dia= 0;
1845         
1846         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1847         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1848         
1849         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1850         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1851         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1852         
1853         glClear(GL_DEPTH_BUFFER_BIT);
1854         
1855         glLoadMatrixf(rv3d->viewmat);
1856 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1857         
1858         if(rv3d->rflag & RV3D_CLIPPING) {
1859                 view3d_set_clipping(rv3d);
1860         }
1861         
1862         v3d->zbuf= TRUE;
1863         glEnable(GL_DEPTH_TEST);
1864         
1865         /* draw set first */
1866         if(scene->set) {
1867                 Scene *sce_iter;
1868                 for(SETLOOPER(scene->set, sce_iter, base)) {
1869                         if(v3d->lay & base->lay) {
1870                                 if (func == NULL || func(base)) {
1871                                         draw_object(scene, ar, v3d, base, 0);
1872                                         if(base->object->transflag & OB_DUPLI) {
1873                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1874                                         }
1875                                 }
1876                         }
1877                 }
1878         }
1879         
1880         for(base= scene->base.first; base; base= base->next) {
1881                 if(v3d->lay & base->lay) {
1882                         if (func == NULL || func(base)) {
1883                                 /* dupli drawing */
1884                                 if(base->object->transflag & OB_DUPLI) {
1885                                         draw_dupli_objects(scene, ar, v3d, base);
1886                                 }
1887                                 draw_object(scene, ar, v3d, base, 0);
1888                         }
1889                 }
1890         }
1891         
1892         /* this isnt that nice, draw xray objects as if they are normal */
1893         if (    v3d->afterdraw_transp.first ||
1894                         v3d->afterdraw_xray.first || 
1895                         v3d->afterdraw_xraytransp.first
1896         ) {
1897                 View3DAfter *v3da, *next;
1898                 int mask_orig;
1899
1900                 v3d->xray= TRUE;
1901                 
1902                 /* transp materials can change the depth mask, see #21388 */
1903                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
1904
1905
1906                 if(v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
1907                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1908                         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1909                                 next= v3da->next;
1910                                 draw_object(scene, ar, v3d, v3da->base, 0);
1911                         }
1912                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1913                 }
1914
1915                 /* draw 3 passes, transp/xray/xraytransp */
1916                 v3d->xray= FALSE;
1917                 v3d->transp= TRUE;
1918                 for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
1919                         next= v3da->next;
1920                         draw_object(scene, ar, v3d, v3da->base, 0);
1921                         BLI_remlink(&v3d->afterdraw_transp, v3da);
1922                         MEM_freeN(v3da);
1923                 }
1924
1925                 v3d->xray= TRUE;
1926                 v3d->transp= FALSE;  
1927                 for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1928                         next= v3da->next;
1929                         draw_object(scene, ar, v3d, v3da->base, 0);
1930                         BLI_remlink(&v3d->afterdraw_xray, v3da);
1931                         MEM_freeN(v3da);
1932                 }
1933
1934                 v3d->xray= TRUE;
1935                 v3d->transp= TRUE;
1936                 for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
1937                         next= v3da->next;
1938                         draw_object(scene, ar, v3d, v3da->base, 0);
1939                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1940                         MEM_freeN(v3da);
1941                 }
1942
1943                 
1944                 v3d->xray= FALSE;
1945                 v3d->transp= FALSE;
1946
1947                 glDepthMask(mask_orig);
1948         }
1949         
1950         if(rv3d->rflag & RV3D_CLIPPING)
1951                 view3d_clr_clipping();
1952         
1953         v3d->zbuf = zbuf;
1954         if(!v3d->zbuf) glDisable(GL_DEPTH_TEST);
1955
1956         U.glalphaclip = glalphaclip;
1957         v3d->flag = flag;
1958         U.obcenter_dia= obcenter_dia;
1959 }
1960
1961 typedef struct View3DShadow {
1962         struct View3DShadow *next, *prev;
1963         GPULamp *lamp;
1964 } View3DShadow;
1965
1966 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1967 {
1968         GPULamp *lamp;
1969         Lamp *la = (Lamp*)ob->data;
1970         View3DShadow *shadow;
1971         
1972         lamp = GPU_lamp_from_blender(scene, ob, par);
1973         
1974         if(lamp) {
1975                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
1976                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1977                 
1978                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1979                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1980                         shadow->lamp = lamp;
1981                         BLI_addtail(shadows, shadow);
1982                 }
1983         }
1984 }
1985
1986 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1987 {
1988         ListBase shadows;
1989         View3DShadow *shadow;
1990         Scene *sce_iter;
1991         Base *base;
1992         Object *ob;
1993         
1994         shadows.first= shadows.last= NULL;
1995         
1996         /* update lamp transform and gather shadow lamps */
1997         for(SETLOOPER(scene, sce_iter, base)) {
1998                 ob= base->object;
1999                 
2000                 if(ob->type == OB_LAMP)
2001                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2002                 
2003                 if (ob->transflag & OB_DUPLI) {
2004                         DupliObject *dob;
2005                         ListBase *lb = object_duplilist(scene, ob);
2006                         
2007                         for(dob=lb->first; dob; dob=dob->next)
2008                                 if(dob->ob->type==OB_LAMP)
2009                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2010                         
2011                         free_object_duplilist(lb);
2012                 }
2013         }
2014         
2015         /* render shadows after updating all lamps, nested object_duplilist
2016                 * don't work correct since it's replacing object matrices */
2017         for(shadow=shadows.first; shadow; shadow=shadow->next) {
2018                 /* this needs to be done better .. */
2019                 float viewmat[4][4], winmat[4][4];
2020                 int drawtype, lay, winsize, flag2=v3d->flag2;
2021                 ARegion ar= {NULL};
2022                 RegionView3D rv3d= {{{0}}};
2023                 
2024                 drawtype= v3d->drawtype;
2025                 lay= v3d->lay;
2026                 
2027                 v3d->drawtype = OB_SOLID;
2028                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2029                 v3d->flag2 &= ~V3D_SOLID_TEX;
2030                 v3d->flag2 |= V3D_RENDER_OVERRIDE;
2031                 
2032                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2033
2034                 ar.regiondata= &rv3d;
2035                 ar.regiontype= RGN_TYPE_WINDOW;
2036                 rv3d.persp= RV3D_CAMOB;
2037                 copy_m4_m4(rv3d.winmat, winmat);
2038                 copy_m4_m4(rv3d.viewmat, viewmat);
2039                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2040                 mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2041                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2042
2043                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat);
2044                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2045                 
2046                 v3d->drawtype= drawtype;
2047                 v3d->lay= lay;
2048                 v3d->flag2 = flag2;
2049         }
2050         
2051         BLI_freelistN(&shadows);
2052 }
2053
2054 /* *********************** customdata **************** */
2055
2056 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2057 {
2058         CustomDataMask mask= 0;
2059         if(v3d->drawtype == OB_SHADED) {
2060                 /* this includes normals for mesh_create_shadedColors */
2061                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
2062         }
2063         if((v3d->drawtype == OB_TEXTURE) || ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX))) {
2064                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2065
2066                 if(scene->gm.matmode == GAME_MAT_GLSL)
2067                         mask |= CD_MASK_ORCO;
2068         }
2069
2070         return mask;
2071 }
2072 /* goes over all modes and view3d settings */
2073 CustomDataMask ED_viewedit_datamask(bScreen *screen)
2074 {
2075         Scene *scene= screen->scene;
2076         Object *ob= scene->basact ? scene->basact->object : NULL;
2077         CustomDataMask mask = CD_MASK_BAREMESH;
2078         ScrArea *sa;
2079         
2080         /* check if we need tfaces & mcols due to face select or texture paint */
2081         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
2082                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2083         
2084         /* check if we need tfaces & mcols due to view mode */
2085         for(sa = screen->areabase.first; sa; sa = sa->next) {
2086                 if(sa->spacetype == SPACE_VIEW3D) {
2087                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2088                 }
2089         }
2090         
2091         /* check if we need mcols due to vertex paint or weightpaint */
2092         if(ob) {
2093                 if(ob->mode & OB_MODE_VERTEX_PAINT)
2094                         mask |= CD_MASK_MCOL;
2095                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
2096                         mask |= CD_MASK_WEIGHT_MCOL;
2097         }
2098
2099         return mask;
2100 }
2101
2102 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2103 {
2104         RegionView3D *rv3d= ar->regiondata;
2105
2106         /* setup window matrices */
2107         if(winmat)
2108                 copy_m4_m4(rv3d->winmat, winmat);
2109         else
2110                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
2111         
2112         /* setup view matrix */
2113         if(viewmat)
2114                 copy_m4_m4(rv3d->viewmat, viewmat);
2115         else
2116                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
2117         
2118         /* update utilitity matrices */
2119         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
2120         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2121         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2122
2123         /* calculate pixelsize factor once, is used for lamps and obcenters */
2124         {
2125                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2126                  * because of float point precision problems at large values [#23908] */
2127                 float v1[3], v2[3];
2128                 float len1, len2;
2129
2130                 v1[0]= rv3d->persmat[0][0];
2131                 v1[1]= rv3d->persmat[1][0];
2132                 v1[2]= rv3d->persmat[2][0];
2133
2134                 v2[0]= rv3d->persmat[0][1];
2135                 v2[1]= rv3d->persmat[1][1];
2136                 v2[2]= rv3d->persmat[2][1];
2137                 
2138                 len1= 1.0f / len_v3(v1);
2139                 len2= 1.0f / len_v3(v2);
2140
2141                 rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
2142         }
2143
2144         /* set for opengl */
2145         glMatrixMode(GL_PROJECTION);
2146         glLoadMatrixf(rv3d->winmat);
2147         glMatrixMode(GL_MODELVIEW);
2148         glLoadMatrixf(rv3d->viewmat);
2149 }
2150
2151 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
2152 {
2153         Base *base;
2154         float backcol[3];
2155         int bwinx, bwiny;
2156         rcti brect;
2157
2158         glPushMatrix();
2159
2160         /* set temporary new size */
2161         bwinx= ar->winx;
2162         bwiny= ar->winy;
2163         brect= ar->winrct;
2164         
2165         ar->winx= winx;
2166         ar->winy= winy; 
2167         ar->winrct.xmin= 0;
2168         ar->winrct.ymin= 0;
2169         ar->winrct.xmax= winx;
2170         ar->winrct.ymax= winy;
2171         
2172         
2173         /* set flags */
2174         G.f |= G_RENDER_OGL;
2175
2176         /* free images which can have changed on frame-change
2177          * warning! can be slow so only free animated images - campbell */
2178         GPU_free_images_anim();
2179         
2180         /* shadow buffers, before we setup matrices */
2181         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2182                 gpu_update_lamps_shadows(scene, v3d);
2183
2184         /* set background color, fallback on the view background color */
2185         if(scene->world) {
2186                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2187                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2188                 else
2189                         copy_v3_v3(backcol, &scene->world->horr);
2190                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2191         }
2192         else {
2193                 UI_ThemeClearColor(TH_BACK);    
2194         }
2195
2196         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2197
2198         /* setup view matrices */
2199         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2200
2201         /* set zbuffer */
2202         if(v3d->drawtype > OB_WIRE) {
2203                 v3d->zbuf= TRUE;
2204                 glEnable(GL_DEPTH_TEST);
2205         }
2206         else
2207                 v3d->zbuf= FALSE;
2208
2209         /* draw set first */
2210         if(scene->set) {
2211                 Scene *sce_iter;
2212                 for(SETLOOPER(scene->set, sce_iter, base)) {
2213                         if(v3d->lay & base->lay) {
2214                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2215                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2216                                 
2217                                 if(base->object->transflag & OB_DUPLI)
2218                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2219                         }
2220                 }
2221         }
2222         
2223         /* then draw not selected and the duplis, but skip editmode object */
2224         for(base= scene->base.first; base; base= base->next) {
2225                 if(v3d->lay & base->lay) {
2226                         /* dupli drawing */
2227                         if(base->object->transflag & OB_DUPLI)
2228                                 draw_dupli_objects(scene, ar, v3d, base);
2229
2230                         draw_object(scene, ar, v3d, base, 0);
2231                 }
2232         }
2233
2234         /* must be before xray draw which clears the depth buffer */
2235         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2236         draw_gpencil_view3d_ext(scene, v3d, ar, 1);
2237         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2238
2239         /* transp and X-ray afterdraw stuff */
2240         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2241         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2242         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2243
2244         /* cleanup */
2245         if(v3d->zbuf) {
2246                 v3d->zbuf= FALSE;
2247                 glDisable(GL_DEPTH_TEST);
2248         }
2249
2250         /* draw grease-pencil stuff */
2251         ED_region_pixelspace(ar);
2252
2253         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2254         draw_gpencil_view3d_ext(scene, v3d, ar, 0);
2255
2256         /* freeing the images again here could be done after the operator runs, leaving for now */
2257         GPU_free_images_anim();
2258
2259         /* restore size */
2260         ar->winx= bwinx;
2261         ar->winy= bwiny;
2262         ar->winrct = brect;
2263
2264         glPopMatrix();
2265
2266         glColor4ub(255, 255, 255, 255); // XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell
2267
2268         G.f &= ~G_RENDER_OGL;
2269 }
2270
2271 /* utility func for ED_view3d_draw_offscreen */
2272 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey, unsigned int flag, char err_out[256])
2273 {
2274         RegionView3D *rv3d= ar->regiondata;
2275         ImBuf *ibuf;
2276         GPUOffScreen *ofs;
2277         
2278         /* state changes make normal drawing go weird otherwise */
2279         glPushAttrib(GL_LIGHTING_BIT);
2280
2281         /* bind */
2282         ofs= GPU_offscreen_create(&sizex, &sizey, err_out);
2283         if(ofs == NULL)
2284                 return NULL;
2285
2286         GPU_offscreen_bind(ofs);
2287
2288         /* render 3d view */
2289         if(rv3d->persp==RV3D_CAMOB && v3d->camera) {
2290                 float winmat[4][4];
2291                 float _clipsta, _clipend, _lens, _yco, _dx, _dy;
2292                 rctf _viewplane;
2293
2294                 object_camera_matrix(&scene->r, v3d->camera, sizex, sizey, 0, winmat, &_viewplane, &_clipsta, &_clipend, &_lens, &_yco, &_dx, &_dy);
2295
2296                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
2297         }
2298         else {
2299                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL);
2300         }
2301
2302         /* read in pixels & stamp */
2303         ibuf= IMB_allocImBuf(sizex, sizey, 32, flag);
2304
2305         if(ibuf->rect_float)
2306                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2307         else if(ibuf->rect)
2308                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2309         
2310         //if((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
2311         //      BKE_stamp_buf(scene, NULL, rr->rectf, rr->rectx, rr->recty, 4);
2312
2313         /* unbind */
2314         GPU_offscreen_unbind(ofs);
2315         GPU_offscreen_free(ofs);
2316
2317         glPopAttrib();
2318         
2319         if(ibuf->rect_float && ibuf->rect)
2320                 IMB_rect_from_float(ibuf);
2321         
2322         return ibuf;
2323 }
2324
2325 /* creates own 3d views, used by the sequencer */
2326 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height, unsigned int flag, int drawtype, char err_out[256])
2327 {
2328         View3D v3d= {NULL};
2329         ARegion ar= {NULL};
2330         RegionView3D rv3d= {{{0}}};
2331
2332         /* connect data */
2333         v3d.regionbase.first= v3d.regionbase.last= &ar;
2334         ar.regiondata= &rv3d;
2335         ar.regiontype= RGN_TYPE_WINDOW;
2336
2337         v3d.camera= camera;
2338         v3d.lay= scene->lay;
2339         v3d.drawtype = drawtype;
2340         v3d.flag2 = V3D_RENDER_OVERRIDE;
2341
2342         rv3d.persp= RV3D_CAMOB;
2343
2344         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2345         normalize_m4(rv3d.viewinv);
2346         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2347
2348         {
2349                 float _yco, _dx, _dy;
2350                 rctf _viewplane;
2351                 object_camera_matrix(&scene->r, v3d.camera, width, height, 0, rv3d.winmat, &_viewplane, &v3d.near, &v3d.far, &v3d.lens, &_yco, &_dx, &_dy);
2352         }
2353
2354         mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2355         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2356
2357         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag, err_out);
2358
2359         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2360 }
2361
2362
2363 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2364  * which currently gets called during SCREEN_OT_animation_step.
2365  */
2366 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2367 {
2368         ScreenFrameRateInfo *fpsi= scene->fps_info;
2369         float fps;
2370         char printable[16];
2371         int i, tot;
2372         
2373         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2374                 return;
2375         
2376         printable[0] = '\0';
2377         
2378 #if 0
2379         /* this is too simple, better do an average */
2380         fps = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime))
2381 #else
2382         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime));
2383         
2384         for (i=0, tot=0, fps=0.0f ; i < REDRAW_FRAME_AVERAGE ; i++) {
2385                 if (fpsi->redrawtimes_fps[i]) {
2386                         fps += fpsi->redrawtimes_fps[i];
2387                         tot++;
2388                 }
2389         }
2390         if (tot) {
2391                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2392                 
2393                 //fpsi->redrawtime_index++;
2394                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2395                 //      fpsi->redrawtime = 0;
2396                 
2397                 fps = fps / tot;
2398         }
2399 #endif
2400
2401         /* is this more then half a frame behind? */
2402         if (fps+0.5f < (float)(FPS)) {
2403                 UI_ThemeColor(TH_REDALERT);
2404                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2405         } 
2406         else {
2407                 UI_ThemeColor(TH_TEXT_HI);
2408                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps+0.5f));
2409         }
2410         
2411         BLF_draw_default(22,  ar->winy-17, 0.0f, printable, sizeof(printable)-1);
2412 }
2413
2414 /* warning: this function has duplicate drawing in ED_view3d_draw_offscreen() */
2415 void view3d_main_area_draw(const bContext *C, ARegion *ar)
2416 {
2417         Scene *scene= CTX_data_scene(C);
2418         View3D *v3d = CTX_wm_view3d(C);
2419         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2420         Base *base;
2421         Object *ob;
2422         float backcol[3];
2423         unsigned int lay_used;
2424         const char *grid_unit= NULL;
2425
2426         /* shadow buffers, before we setup matrices */
2427         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2428                 gpu_update_lamps_shadows(scene, v3d);
2429         
2430         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2431         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2432                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2433                 GPU_default_lights();
2434         }
2435
2436         /* clear background */
2437         if((v3d->flag2 & V3D_RENDER_OVERRIDE) && scene->world) {
2438                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2439                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2440                 else
2441                         copy_v3_v3(backcol, &scene->world->horr);
2442                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2443         }
2444         else
2445                 UI_ThemeClearColor(TH_BACK);
2446
2447         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2448         
2449         /* setup view matrices */
2450         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2451
2452         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2453
2454         if(rv3d->rflag & RV3D_CLIPPING)
2455                 view3d_draw_clipping(rv3d);
2456         
2457         /* set zbuffer after we draw clipping region */
2458         if(v3d->drawtype > OB_WIRE) {
2459                 v3d->zbuf= TRUE;
2460                 glEnable(GL_DEPTH_TEST);
2461         }
2462         else
2463                 v3d->zbuf= FALSE;
2464
2465         /* enables anti-aliasing for 3D view drawing */
2466         /*if (!(U.gameflags & USER_DISABLE_AA))
2467                 glEnable(GL_MULTISAMPLE_ARB);*/
2468         
2469         // needs to be done always, gridview is adjusted in drawgrid() now
2470         rv3d->gridview= v3d->grid;
2471
2472         if(rv3d->view==0 || rv3d->persp != RV3D_ORTHO) {
2473                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2474                         drawfloor(scene, v3d, &grid_unit);
2475                 }
2476                 if(rv3d->persp==RV3D_CAMOB) {
2477                         if(scene->world) {
2478                                 if(scene->world->mode & WO_STARS) {
2479                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2480                                                                   star_stuff_term_func);
2481                                 }
2482                         }
2483                         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2484                                 if(v3d->flag & V3D_DISPBGPICS) draw_bgpic(scene, ar, v3d);
2485                         }
2486                 }
2487         }
2488         else {
2489                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2490                         ED_region_pixelspace(ar);
2491                         drawgrid(&scene->unit, ar, v3d, &grid_unit);
2492                         /* XXX make function? replaces persp(1) */
2493                         glMatrixMode(GL_PROJECTION);
2494                         glLoadMatrixf(rv3d->winmat);
2495                         glMatrixMode(GL_MODELVIEW);
2496                         glLoadMatrixf(rv3d->viewmat);
2497
2498                         if(v3d->flag & V3D_DISPBGPICS) {
2499                                 draw_bgpic(scene, ar, v3d);
2500                         }
2501                 }
2502         }
2503         
2504         if(rv3d->rflag & RV3D_CLIPPING)
2505                 view3d_set_clipping(rv3d);
2506
2507         /* draw set first */
2508         if(scene->set) {
2509                 Scene *sce_iter;
2510                 for(SETLOOPER(scene->set, sce_iter, base)) {
2511                         
2512                         if(v3d->lay & base->lay) {
2513                                 
2514                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2515                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2516                                 
2517                                 if(base->object->transflag & OB_DUPLI) {
2518                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2519                                 }
2520                         }
2521                 }
2522                 
2523                 /* Transp and X-ray afterdraw stuff for sets is done later */
2524         }
2525
2526         lay_used= 0;
2527
2528         /* then draw not selected and the duplis, but skip editmode object */
2529         for(base= scene->base.first; base; base= base->next) {
2530                 lay_used |= base->lay & ((1<<20)-1);
2531
2532                 if(v3d->lay & base->lay) {
2533                         
2534                         /* dupli drawing */
2535                         if(base->object->transflag & OB_DUPLI) {
2536                                 draw_dupli_objects(scene, ar, v3d, base);
2537                         }
2538                         if((base->flag & SELECT)==0) {
2539                                 if(base->object!=scene->obedit) 
2540                                         draw_object(scene, ar, v3d, base, 0);
2541                         }
2542                 }
2543         }
2544
2545         if(v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2546                 ARegion *ar_iter;
2547                 ScrArea *sa= CTX_wm_area(C);
2548
2549                 /* find header and force tag redraw */
2550                 for(ar_iter= sa->regionbase.first; ar_iter; ar_iter= ar_iter->next)
2551                         if(ar_iter->regiontype==RGN_TYPE_HEADER) {
2552                                 ED_region_tag_redraw(ar_iter);
2553                                 break;
2554                         }
2555
2556                 v3d->lay_used= lay_used;
2557         }
2558
2559         /* draw selected and editmode */
2560         for(base= scene->base.first; base; base= base->next) {
2561                 if(v3d->lay & base->lay) {
2562                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2563                                 draw_object(scene, ar, v3d, base, 0);
2564                 }
2565         }
2566
2567 //      REEB_draw();
2568
2569         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2570                 /* must be before xray draw which clears the depth buffer */
2571                 if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2572                 draw_gpencil_view3d((bContext *)C, 1);
2573                 if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2574         }
2575
2576         /* Transp and X-ray afterdraw stuff */
2577         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2578         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2579         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2580         
2581         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2582
2583         if(rv3d->rflag & RV3D_CLIPPING)
2584                 view3d_clr_clipping();
2585         
2586         BIF_draw_manipulator(C);
2587         
2588         /* Disable back anti-aliasing */
2589         /*if (!(U.gameflags & USER_DISABLE_AA))
2590                 glDisable(GL_MULTISAMPLE_ARB);*/
2591
2592         if(v3d->zbuf) {
2593                 v3d->zbuf= FALSE;
2594                 glDisable(GL_DEPTH_TEST);
2595         }
2596
2597         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2598                 BDR_drawSketch(C);
2599         }
2600
2601         ED_region_pixelspace(ar);
2602         
2603 //      retopo_paint_view_update(v3d);
2604 //      retopo_draw_paint_lines();
2605         
2606         /* Draw particle edit brush XXX (removed) */
2607         
2608
2609         if(rv3d->persp==RV3D_CAMOB)
2610                 drawviewborder(scene, ar, v3d);
2611
2612         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2613                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2614         //      if (v3d->flag2 & V3D_DISPGP)
2615                         draw_gpencil_view3d((bContext *)C, 0);
2616
2617                 drawcursor(scene, ar, v3d);
2618         }
2619         
2620         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2621                 draw_view_axis(rv3d);
2622         else    
2623                 draw_view_icon(rv3d);
2624         
2625         if((U.uiflag & USER_SHOW_FPS) && (CTX_wm_screen(C)->animtimer)) {
2626                 draw_viewport_fps(scene, ar);
2627         }
2628         else if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2629                 draw_viewport_name(ar, v3d);
2630         }
2631         if (grid_unit) { /* draw below the viewport name */
2632                 char tstr[32]= "";
2633
2634                 UI_ThemeColor(TH_TEXT_HI);
2635                 if(v3d->grid != 1.0f) {
2636                         BLI_snprintf(tstr, sizeof(tstr), "%s x %.4g", grid_unit, v3d->grid);
2637                 }
2638
2639                 BLF_draw_default(22,  ar->winy-(USER_SHOW_VIEWPORTNAME?40:20), 0.0f, tstr[0]?tstr : grid_unit, sizeof(tstr)); /* XXX, use real length */
2640         }
2641
2642         ob= OBACT;
2643         if(U.uiflag & USER_DRAWVIEWINFO) 
2644                 draw_selected_name(scene, ob, v3d);
2645         
2646         /* XXX here was the blockhandlers for floating panels */
2647
2648         v3d->flag |= V3D_INVALID_BACKBUF;
2649 }