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