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