2.5: code consistency
[blender-staging.git] / source / blender / editors / space_view3d / view3d_draw.c
1 /**
2  * $Id:
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2008 Blender Foundation.
21  * All rights reserved.
22  *
23  * 
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <math.h>
32
33 #include "DNA_action_types.h"
34 #include "DNA_armature_types.h"
35 #include "DNA_camera_types.h"
36 #include "DNA_customdata_types.h"
37 #include "DNA_group_types.h"
38 #include "DNA_key_types.h"
39 #include "DNA_lamp_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_space_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_userdef_types.h"
45 #include "DNA_view3d_types.h"
46 #include "DNA_world_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_arithb.h"
52 #include "BLI_rand.h"
53
54 #include "BKE_anim.h"
55 #include "BKE_context.h"
56 #include "BKE_customdata.h"
57 #include "BKE_image.h"
58 #include "BKE_ipo.h"
59 #include "BKE_key.h"
60 #include "BKE_object.h"
61 #include "BKE_global.h"
62 #include "BKE_scene.h"
63 #include "BKE_screen.h"
64 #include "BKE_utildefines.h"
65
66 #include "RE_pipeline.h"        // make_stars
67
68 #include "IMB_imbuf_types.h"
69 #include "IMB_imbuf.h"
70
71 #include "BIF_gl.h"
72 #include "BIF_glutil.h"
73
74 #include "WM_api.h"
75 #include "BLF_api.h"
76
77 #include "ED_armature.h"
78 #include "ED_keyframing.h"
79 #include "ED_mesh.h"
80 #include "ED_screen.h"
81 #include "ED_space_api.h"
82 #include "ED_util.h"
83 #include "ED_transform.h"
84 #include "ED_types.h"
85
86 #include "UI_interface.h"
87 #include "UI_interface_icons.h"
88 #include "UI_resources.h"
89 #include "UI_view2d.h"
90
91 #include "GPU_draw.h"
92 #include "GPU_material.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 int view3d_test_clipping(RegionView3D *rv3d, float *vec)
194 {
195         /* vec in world coordinates, returns 1 if clipped */
196         float view[3];
197         
198         VECCOPY(view, vec);
199         
200         if(0.0f < rv3d->clip[0][3] + INPR(view, rv3d->clip[0]))
201                 if(0.0f < rv3d->clip[1][3] + INPR(view, rv3d->clip[1]))
202                         if(0.0f < rv3d->clip[2][3] + INPR(view, rv3d->clip[2]))
203                                 if(0.0f < rv3d->clip[3][3] + INPR(view, rv3d->clip[3]))
204                                         return 0;
205         
206         return 1;
207 }
208
209 /* ********* end custom clipping *********** */
210
211
212 static void drawgrid_draw(ARegion *ar, float wx, float wy, float x, float y, float dx)
213 {
214         float fx, fy;
215         
216         x+= (wx); 
217         y+= (wy);
218         fx= x/dx;
219         fx= x-dx*floor(fx);
220         
221         while(fx< ar->winx) {
222                 fdrawline(fx,  0.0,  fx,  (float)ar->winy); 
223                 fx+= dx; 
224         }
225
226         fy= y/dx;
227         fy= y-dx*floor(fy);
228         
229
230         while(fy< ar->winy) {
231                 fdrawline(0.0,  fy,  (float)ar->winx,  fy); 
232                 fy+= dx;
233         }
234
235 }
236
237 static void drawgrid(ARegion *ar, View3D *v3d)
238 {
239         /* extern short bgpicmode; */
240         RegionView3D *rv3d= ar->regiondata;
241         float wx, wy, x, y, fw, fx, fy, dx;
242         float vec4[4];
243         char col[3], col2[3];
244         short sublines = v3d->gridsubdiv;
245         
246         vec4[0]=vec4[1]=vec4[2]=0.0; 
247         vec4[3]= 1.0;
248         Mat4MulVec4fl(rv3d->persmat, vec4);
249         fx= vec4[0]; 
250         fy= vec4[1]; 
251         fw= vec4[3];
252
253         wx= (ar->winx/2.0);     /* because of rounding errors, grid at wrong location */
254         wy= (ar->winy/2.0);
255
256         x= (wx)*fx/fw;
257         y= (wy)*fy/fw;
258
259         vec4[0]=vec4[1]=v3d->grid; 
260         vec4[2]= 0.0;
261         vec4[3]= 1.0;
262         Mat4MulVec4fl(rv3d->persmat, vec4);
263         fx= vec4[0]; 
264         fy= vec4[1]; 
265         fw= vec4[3];
266
267         dx= fabs(x-(wx)*fx/fw);
268         if(dx==0) dx= fabs(y-(wy)*fy/fw);
269         
270         glDepthMask(0);         // disable write in zbuffer
271
272         /* check zoom out */
273         UI_ThemeColor(TH_GRID);
274         
275         if(dx<6.0) {
276                 v3d->gridview*= sublines;
277                 dx*= sublines;
278                 
279                 if(dx<6.0) {    
280                         v3d->gridview*= sublines;
281                         dx*= sublines;
282                         
283                         if(dx<6.0) {
284                                 v3d->gridview*= sublines;
285                                 dx*=sublines;
286                                 if(dx<6.0);
287                                 else {
288                                         UI_ThemeColor(TH_GRID);
289                                         drawgrid_draw(ar, wx, wy, x, y, dx);
290                                 }
291                         }
292                         else {  // start blending out
293                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
294                                 drawgrid_draw(ar, wx, wy, x, y, dx);
295                         
296                                 UI_ThemeColor(TH_GRID);
297                                 drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
298                         }
299                 }
300                 else {  // start blending out (6 < dx < 60)
301                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
302                         drawgrid_draw(ar, wx, wy, x, y, dx);
303                         
304                         UI_ThemeColor(TH_GRID);
305                         drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
306                 }
307         }
308         else {
309                 if(dx>60.0) {           // start blending in
310                         v3d->gridview/= sublines;
311                         dx/= sublines;                  
312                         if(dx>60.0) {           // start blending in
313                                 v3d->gridview/= sublines;
314                                 dx/= sublines;
315                                 if(dx>60.0) {
316                                         UI_ThemeColor(TH_GRID);
317                                         drawgrid_draw(ar, wx, wy, x, y, dx);
318                                 }
319                                 else {
320                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
321                                         drawgrid_draw(ar, wx, wy, x, y, dx);
322                                         UI_ThemeColor(TH_GRID);
323                                         drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
324                                 }
325                         }
326                         else {
327                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
328                                 drawgrid_draw(ar, wx, wy, x, y, dx);
329                                 UI_ThemeColor(TH_GRID);                         
330                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
331                         }
332                 }
333                 else {
334                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
335                         drawgrid_draw(ar, wx, wy, x, y, dx);
336                         UI_ThemeColor(TH_GRID);
337                         drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
338                 }
339         }
340
341         x+= (wx); 
342         y+= (wy);
343         UI_GetThemeColor3ubv(TH_GRID, col);
344
345         setlinestyle(0);
346         
347         /* center cross */
348         if( ELEM(rv3d->view, V3D_VIEW_RIGHT, V3D_VIEW_LEFT)) 
349                 UI_make_axis_color(col, col2, 'y');
350         else UI_make_axis_color(col, col2, 'x');
351         glColor3ubv((GLubyte *)col2);
352         
353         fdrawline(0.0,  y,  (float)ar->winx,  y); 
354         
355         if( ELEM(rv3d->view, V3D_VIEW_TOP, V3D_VIEW_BOTTOM)) 
356                 UI_make_axis_color(col, col2, 'y');
357         else UI_make_axis_color(col, col2, 'z');
358         glColor3ubv((GLubyte *)col2);
359
360         fdrawline(x, 0.0, x, (float)ar->winy); 
361
362         glDepthMask(1);         // enable write in zbuffer
363 }
364
365
366 static void drawfloor(Scene *scene, View3D *v3d)
367 {
368         float vert[3], grid;
369         int a, gridlines, emphasise;
370         char col[3], col2[3];
371         short draw_line = 0;
372         
373         vert[2]= 0.0;
374         
375         if(v3d->gridlines<3) return;
376         
377         if(v3d->zbuf && scene->obedit) glDepthMask(0);  // for zbuffer-select
378         
379         gridlines= v3d->gridlines/2;
380         grid= gridlines*v3d->grid;
381         
382         UI_GetThemeColor3ubv(TH_GRID, col);
383         UI_GetThemeColor3ubv(TH_BACK, col2);
384         
385         /* emphasise division lines lighter instead of darker, if background is darker than grid */
386         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
387                 emphasise = 20;
388         else
389                 emphasise = -10;
390         
391         /* draw the Y axis and/or grid lines */
392         for(a= -gridlines;a<=gridlines;a++) {
393                 if(a==0) {
394                         /* check for the 'show Y axis' preference */
395                         if (v3d->gridflag & V3D_SHOW_Y) { 
396                                 UI_make_axis_color(col, col2, 'y');
397                                 glColor3ubv((GLubyte *)col2);
398                                 
399                                 draw_line = 1;
400                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
401                                 UI_ThemeColorShade(TH_GRID, emphasise);
402                         } else {
403                                 draw_line = 0;
404                         }
405                 } else {
406                         /* check for the 'show grid floor' preference */
407                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
408                                 if( (a % 10)==0) {
409                                         UI_ThemeColorShade(TH_GRID, emphasise);
410                                 }
411                                 else UI_ThemeColorShade(TH_GRID, 10);
412                                 
413                                 draw_line = 1;
414                         } else {
415                                 draw_line = 0;
416                         }
417                 }
418                 
419                 if (draw_line) {
420                         glBegin(GL_LINE_STRIP);
421                 vert[0]= a*v3d->grid;
422                 vert[1]= grid;
423                 glVertex3fv(vert);
424                 vert[1]= -grid;
425                 glVertex3fv(vert);
426                         glEnd();
427                 }
428         }
429         
430         /* draw the X axis and/or grid lines */
431         for(a= -gridlines;a<=gridlines;a++) {
432                 if(a==0) {
433                         /* check for the 'show X axis' preference */
434                         if (v3d->gridflag & V3D_SHOW_X) { 
435                                 UI_make_axis_color(col, col2, 'x');
436                                 glColor3ubv((GLubyte *)col2);
437                                 
438                                 draw_line = 1;
439                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
440                                 UI_ThemeColorShade(TH_GRID, emphasise);
441                         } else {
442                                 draw_line = 0;
443                         }
444                 } else {
445                         /* check for the 'show grid floor' preference */
446                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
447                                 if( (a % 10)==0) {
448                                         UI_ThemeColorShade(TH_GRID, emphasise);
449                                 }
450                                 else UI_ThemeColorShade(TH_GRID, 10);
451                                 
452                                 draw_line = 1;
453                         } else {
454                                 draw_line = 0;
455                         }
456                 }
457                 
458                 if (draw_line) {
459                         glBegin(GL_LINE_STRIP);
460                 vert[1]= a*v3d->grid;
461                 vert[0]= grid;
462                 glVertex3fv(vert );
463                 vert[0]= -grid;
464                 glVertex3fv(vert);
465                         glEnd();
466                 }
467         }
468         
469         /* draw the Z axis line */      
470         /* check for the 'show Z axis' preference */
471         if (v3d->gridflag & V3D_SHOW_Z) {
472                 UI_make_axis_color(col, col2, 'z');
473                 glColor3ubv((GLubyte *)col2);
474                 
475                 glBegin(GL_LINE_STRIP);
476                 vert[0]= 0;
477                 vert[1]= 0;
478                 vert[2]= grid;
479                 glVertex3fv(vert );
480                 vert[2]= -grid;
481                 glVertex3fv(vert);
482                 glEnd();
483         }
484         
485         if(v3d->zbuf && scene->obedit) glDepthMask(1);  
486         
487 }
488
489 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
490 {
491         short mx,my,co[2];
492         int flag;
493         
494         /* we dont want the clipping for cursor */
495         flag= v3d->flag;
496         v3d->flag= 0;
497         project_short(ar, give_cursor(scene, v3d), co);
498         v3d->flag= flag;
499         
500         mx = co[0];
501         my = co[1];
502         
503         if(mx!=IS_CLIPPED) {
504                 setlinestyle(0); 
505                 cpack(0xFF);
506                 circ((float)mx, (float)my, 10.0);
507                 setlinestyle(4); 
508                 cpack(0xFFFFFF);
509                 circ((float)mx, (float)my, 10.0);
510                 setlinestyle(0);
511                 cpack(0x0);
512                 
513                 sdrawline(mx-20, my, mx-5, my);
514                 sdrawline(mx+5, my, mx+20, my);
515                 sdrawline(mx, my-20, mx, my-5);
516                 sdrawline(mx, my+5, mx, my+20);
517         }
518 }
519
520 /* Draw a live substitute of the view icon, which is always shown */
521 static void draw_view_axis(RegionView3D *rv3d)
522 {
523         const float k = U.rvisize;   /* axis size */
524         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
525         const float start = k + 1.0; /* axis center in screen coordinates, x=y */
526         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
527         
528         /* rvibright ranges approx. from original axis icon color to gizmo color */
529         float bright = U.rvibright / 15.0f;
530         
531         unsigned char col[3];
532         unsigned char gridcol[3];
533         float colf[3];
534         
535         float vec[4];
536         float dx, dy;
537         float h, s, v;
538         
539         /* thickness of lines is proportional to k */
540         /*      (log(k)-1) gives a more suitable thickness, but fps decreased by about 3 fps */
541         glLineWidth(k / 10);
542         //glLineWidth(log(k)-1); // a bit slow
543         
544         UI_GetThemeColor3ubv(TH_GRID, (char *)gridcol);
545         
546         /* X */
547         vec[0] = vec[3] = 1;
548         vec[1] = vec[2] = 0;
549         QuatMulVecf(rv3d->viewquat, vec);
550         
551         UI_make_axis_color((char *)gridcol, (char *)col, 'x');
552         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
553         s = s<0.5 ? s+0.5 : 1.0;
554         v = 0.3;
555         v = (v<1.0-(bright) ? v+bright : 1.0);
556         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
557         glColor3fv(colf);
558         
559         dx = vec[0] * k;
560         dy = vec[1] * k;
561         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
562         if (fabs(dx) > toll || fabs(dy) > toll) {
563                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "x");
564         }
565         
566         /* Y */
567         vec[1] = vec[3] = 1;
568         vec[0] = vec[2] = 0;
569         QuatMulVecf(rv3d->viewquat, vec);
570         
571         UI_make_axis_color((char *)gridcol, (char *)col, 'y');
572         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
573         s = s<0.5 ? s+0.5 : 1.0;
574         v = 0.3;
575         v = (v<1.0-(bright) ? v+bright : 1.0);
576         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
577         glColor3fv(colf);
578         
579         dx = vec[0] * k;
580         dy = vec[1] * k;
581         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
582         if (fabs(dx) > toll || fabs(dy) > toll) {
583                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "y");
584         }
585         
586         /* Z */
587         vec[2] = vec[3] = 1;
588         vec[1] = vec[0] = 0;
589         QuatMulVecf(rv3d->viewquat, vec);
590         
591         UI_make_axis_color((char *)gridcol, (char *)col, 'z');
592         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
593         s = s<0.5 ? s+0.5 : 1.0;
594         v = 0.5;
595         v = (v<1.0-(bright) ? v+bright : 1.0);
596         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
597         glColor3fv(colf);
598         
599         dx = vec[0] * k;
600         dy = vec[1] * k;
601         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
602         if (fabs(dx) > toll || fabs(dy) > toll) {
603                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "z");
604         }
605         
606         /* restore line-width */
607         glLineWidth(1.0);
608 }
609
610
611 static void draw_view_icon(RegionView3D *rv3d)
612 {
613         BIFIconID icon;
614         
615         if( ELEM(rv3d->view, V3D_VIEW_TOP, V3D_VIEW_BOTTOM)) 
616                 icon= ICON_AXIS_TOP;
617         else if( ELEM(rv3d->view, V3D_VIEW_FRONT, V3D_VIEW_BACK)) 
618                 icon= ICON_AXIS_FRONT;
619         else if( ELEM(rv3d->view, V3D_VIEW_RIGHT, V3D_VIEW_LEFT)) 
620                 icon= ICON_AXIS_SIDE;
621         else return ;
622         
623         glEnable(GL_BLEND);
624         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
625         
626         UI_icon_draw(5.0, 5.0, icon);
627         
628         glDisable(GL_BLEND);
629 }
630
631 static char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
632 {
633         char *name = NULL;
634         
635         switch (rv3d->view) {
636                 case V3D_VIEW_FRONT:
637                         if (rv3d->persp == V3D_ORTHO) name = "Front Ortho";
638                         else name = "Front Persp";
639                         break;
640                 case V3D_VIEW_BACK:
641                         if (rv3d->persp == V3D_ORTHO) name = "Back Ortho";
642                         else name = "Back Persp";
643                         break;
644                 case V3D_VIEW_TOP:
645                         if (rv3d->persp == V3D_ORTHO) name = "Top Ortho";
646                         else name = "Top Persp";
647                         break;
648                 case V3D_VIEW_BOTTOM:
649                         if (rv3d->persp == V3D_ORTHO) name = "Bottom Ortho";
650                         else name = "Bottom Persp";
651                         break;
652                 case V3D_VIEW_RIGHT:
653                         if (rv3d->persp == V3D_ORTHO) name = "Right Ortho";
654                         else name = "Right Persp";
655                         break;
656                 case V3D_VIEW_LEFT:
657                         if (rv3d->persp == V3D_ORTHO) name = "Left Ortho";
658                         else name = "Left Persp";
659                         break;
660                         
661                 default:
662                         if (rv3d->persp==V3D_CAMOB) {
663                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
664                                         Camera *cam;
665                                         cam = v3d->camera->data;
666                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
667                                 } else {
668                                         name = "Object as Camera";
669                                 }
670                         } else { 
671                                 name = (rv3d->persp == V3D_ORTHO) ? "User Ortho" : "User Persp";
672                         }
673                         break;
674         }
675         
676         return name;
677 }
678
679 static void draw_viewport_name(ARegion *ar, View3D *v3d)
680 {
681         RegionView3D *rv3d= ar->regiondata;
682         char *name = view3d_get_name(v3d, rv3d);
683         char *printable = NULL;
684         
685         if (v3d->localview) {
686                 printable = malloc(strlen(name) + strlen(" (Local)_")); /* '_' gives space for '\0' */
687                                                                                                  strcpy(printable, name);
688                                                                                                  strcat(printable, " (Local)");
689         } else {
690                 printable = name;
691         }
692
693         if (printable) {
694                 UI_ThemeColor(TH_TEXT_HI);
695                 BLF_draw_default(10,  ar->winy-20, 0.0f, printable);
696         }
697
698         if (v3d->localview) {
699                 free(printable);
700         }
701 }
702
703
704 static char *get_cfra_marker_name(Scene *scene)
705 {
706         ListBase *markers= &scene->markers;
707         TimeMarker *m1, *m2;
708         
709         /* search through markers for match */
710         for (m1=markers->first, m2=markers->last; m1 && m2; m1=m1->next, m2=m2->prev) {
711                 if (m1->frame==CFRA)
712                         return m1->name;
713                 
714                 if (m1 == m2)
715                         break;          
716                 
717                 if (m2->frame==CFRA)
718                         return m2->name;
719         }
720         
721         return NULL;
722 }
723
724 /* draw info beside axes in bottom left-corner: 
725 *       framenum, object name, bone name (if available), marker name (if available)
726 */
727 static void draw_selected_name(Scene *scene, Object *ob, View3D *v3d)
728 {
729         char info[256], *markern;
730         short offset=30;
731         
732         /* get name of marker on current frame (if available) */
733         markern= get_cfra_marker_name(scene);
734         
735         /* check if there is an object */
736         if(ob) {
737                 /* name(s) to display depends on type of object */
738                 if(ob->type==OB_ARMATURE) {
739                         bArmature *arm= ob->data;
740                         char *name= NULL;
741                         
742                         /* show name of active bone too (if possible) */
743                         if(arm->edbo) {
744                                 EditBone *ebo;
745                                 for (ebo=arm->edbo->first; ebo; ebo=ebo->next){
746                                         if ((ebo->flag & BONE_ACTIVE) && (ebo->layer & arm->layer)) {
747                                                 name= ebo->name;
748                                                 break;
749                                         }
750                                 }
751                         }
752                         else if(ob->pose && (ob->flag & OB_POSEMODE)) {
753                                 bPoseChannel *pchan;
754                                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
755                                         if((pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer)) {
756                                                 name= pchan->name;
757                                                 break;
758                                         }
759                                 }
760                         }
761                         if(name && markern)
762                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, name, markern);
763                         else if(name)
764                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
765                         else
766                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
767                 }
768                 else if(ELEM3(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
769                         Key *key= NULL;
770                         KeyBlock *kb = NULL;
771                         char shapes[75];
772                         
773                         /* try to display active shapekey too */
774                         shapes[0] = 0;
775                         key = ob_get_key(ob);
776                         if(key){
777                                 kb = BLI_findlink(&key->block, ob->shapenr-1);
778                                 if(kb){
779                                         sprintf(shapes, ": %s ", kb->name);             
780                                         if(ob->shapeflag == OB_SHAPE_LOCK){
781                                                 sprintf(shapes, "%s (Pinned)",shapes);
782                                         }
783                                 }
784                         }
785                         
786                         if(markern)
787                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, shapes, markern);
788                         else
789                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
790                 }
791                 else {
792                         /* standard object */
793                         if (markern)
794                                 sprintf(info, "(%d) %s <%s>", CFRA, ob->id.name+2, markern);
795                         else
796                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
797                 }
798                 
799                 /* colour depends on whether there is a keyframe */
800                 if (id_frame_has_keyframe((ID *)ob, /*frame_to_float(scene, CFRA)*/(float)(CFRA), v3d->keyflags))
801                         UI_ThemeColor(TH_VERTEX_SELECT);
802                 else
803                         UI_ThemeColor(TH_TEXT_HI);
804         }
805         else {
806                 /* no object */
807                 if (markern)
808                         sprintf(info, "(%d) <%s>", CFRA, markern);
809                 else
810                         sprintf(info, "(%d)", CFRA);
811                 
812                 /* colour is always white */
813                 UI_ThemeColor(TH_TEXT_HI);
814         }
815         
816         if (U.uiflag & USER_SHOW_ROTVIEWICON)
817                 offset = 14 + (U.rvisize * 2);
818
819         BLF_draw_default(offset,  10, 0.0f, info);
820 }
821
822 static void view3d_get_viewborder_size(Scene *scene, ARegion *ar, float size_r[2])
823 {
824         float winmax= MAX2(ar->winx, ar->winy);
825         float aspect= (float) (scene->r.xsch*scene->r.xasp)/(scene->r.ysch*scene->r.yasp);
826         
827         if(aspect>1.0) {
828                 size_r[0]= winmax;
829                 size_r[1]= winmax/aspect;
830         } else {
831                 size_r[0]= winmax*aspect;
832                 size_r[1]= winmax;
833         }
834 }
835
836 void calc_viewborder(Scene *scene, ARegion *ar, View3D *v3d, rctf *viewborder_r)
837 {
838         RegionView3D *rv3d= ar->regiondata;
839         float zoomfac, size[2];
840         float dx= 0.0f, dy= 0.0f;
841         
842         view3d_get_viewborder_size(scene, ar, size);
843         
844         /* magic zoom calculation, no idea what
845                 * it signifies, if you find out, tell me! -zr
846                 */
847         /* simple, its magic dude!
848                 * well, to be honest, this gives a natural feeling zooming
849                 * with multiple keypad presses (ton)
850                 */
851         
852         zoomfac= (M_SQRT2 + rv3d->camzoom/50.0);
853         zoomfac= (zoomfac*zoomfac)*0.25;
854         
855         size[0]= size[0]*zoomfac;
856         size[1]= size[1]*zoomfac;
857         
858         /* center in window */
859         viewborder_r->xmin= 0.5*ar->winx - 0.5*size[0];
860         viewborder_r->ymin= 0.5*ar->winy - 0.5*size[1];
861         viewborder_r->xmax= viewborder_r->xmin + size[0];
862         viewborder_r->ymax= viewborder_r->ymin + size[1];
863         
864         dx= ar->winx*rv3d->camdx*zoomfac*2.0f;
865         dy= ar->winy*rv3d->camdy*zoomfac*2.0f;
866         
867         /* apply offset */
868         viewborder_r->xmin-= dx;
869         viewborder_r->ymin-= dy;
870         viewborder_r->xmax-= dx;
871         viewborder_r->ymax-= dy;
872         
873         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
874                 Camera *cam= v3d->camera->data;
875                 float w = viewborder_r->xmax - viewborder_r->xmin;
876                 float h = viewborder_r->ymax - viewborder_r->ymin;
877                 float side = MAX2(w, h);
878                 
879                 viewborder_r->xmin+= cam->shiftx*side;
880                 viewborder_r->xmax+= cam->shiftx*side;
881                 viewborder_r->ymin+= cam->shifty*side;
882                 viewborder_r->ymax+= cam->shifty*side;
883         }
884 }
885
886 void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar)
887 {
888         RegionView3D *rv3d= ar->regiondata;
889         float size[2];
890         int im_width= (scene->r.size*scene->r.xsch)/100;
891         
892         view3d_get_viewborder_size(scene, ar, size);
893         
894         rv3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
895         rv3d->camzoom= CLAMPIS(rv3d->camzoom, -30, 300);
896 }
897
898
899 static void drawviewborder_flymode(ARegion *ar) 
900 {
901         /* draws 4 edge brackets that frame the safe area where the
902         mouse can move during fly mode without spinning the view */
903         float x1, x2, y1, y2;
904         
905         x1= 0.45*(float)ar->winx;
906         y1= 0.45*(float)ar->winy;
907         x2= 0.55*(float)ar->winx;
908         y2= 0.55*(float)ar->winy;
909         cpack(0);
910         
911         
912         glBegin(GL_LINES);
913         /* bottom left */
914         glVertex2f(x1,y1); 
915         glVertex2f(x1,y1+5);
916         
917         glVertex2f(x1,y1); 
918         glVertex2f(x1+5,y1);
919         
920         /* top right */
921         glVertex2f(x2,y2); 
922         glVertex2f(x2,y2-5);
923         
924         glVertex2f(x2,y2); 
925         glVertex2f(x2-5,y2);
926         
927         /* top left */
928         glVertex2f(x1,y2); 
929         glVertex2f(x1,y2-5);
930         
931         glVertex2f(x1,y2); 
932         glVertex2f(x1+5,y2);
933         
934         /* bottom right */
935         glVertex2f(x2,y1); 
936         glVertex2f(x2,y1+5);
937         
938         glVertex2f(x2,y1); 
939         glVertex2f(x2-5,y1);
940         glEnd();        
941 }
942
943
944 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
945 {
946         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
947         float fac, a;
948         float x1, x2, y1, y2;
949         float x3, y3, x4, y4;
950         rctf viewborder;
951         Camera *ca= NULL;
952         
953         if(v3d->camera==NULL)
954                 return;
955         if(v3d->camera->type==OB_CAMERA)
956                 ca = v3d->camera->data;
957         
958         calc_viewborder(scene, ar, v3d, &viewborder);
959         x1= viewborder.xmin;
960         y1= viewborder.ymin;
961         x2= viewborder.xmax;
962         y2= viewborder.ymax;
963         
964         /* passepartout, specified in camera edit buttons */
965         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
966                 if (ca->passepartalpha == 1.0) {
967                         glColor3f(0, 0, 0);
968                 } else {
969                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
970                         glEnable(GL_BLEND);
971                         glColor4f(0, 0, 0, ca->passepartalpha);
972                 }
973                 if (x1 > 0.0)
974                         glRectf(0.0, (float)ar->winy, x1, 0.0);
975                 if (x2 < (float)ar->winx)
976                         glRectf(x2, (float)ar->winy, (float)ar->winx, 0.0);
977                 if (y2 < (float)ar->winy)
978                         glRectf(x1, (float)ar->winy, x2, y2);
979                 if (y2 > 0.0) 
980                         glRectf(x1, y1, x2, 0.0);
981                 
982                 glDisable(GL_BLEND);
983         }
984         
985         /* edge */
986         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
987         
988         setlinestyle(0);
989         UI_ThemeColor(TH_BACK);
990         glRectf(x1, y1, x2, y2);
991         
992         setlinestyle(3);
993         UI_ThemeColor(TH_WIRE);
994         glRectf(x1, y1, x2, y2);
995         
996         /* camera name - draw in highlighted text color */
997         if (ca && (ca->flag & CAM_SHOWNAME)) {
998                 UI_ThemeColor(TH_TEXT_HI);
999                 BLF_draw_default(x1, y1-15, 0.0f, v3d->camera->id.name+2);
1000                 UI_ThemeColor(TH_WIRE);
1001         }
1002         
1003         
1004         /* border */
1005         if(scene->r.mode & R_BORDER) {
1006                 
1007                 cpack(0);
1008                 x3= x1+ scene->r.border.xmin*(x2-x1);
1009                 y3= y1+ scene->r.border.ymin*(y2-y1);
1010                 x4= x1+ scene->r.border.xmax*(x2-x1);
1011                 y4= y1+ scene->r.border.ymax*(y2-y1);
1012                 
1013                 cpack(0x4040FF);
1014                 glRectf(x3,  y3,  x4,  y4); 
1015         }
1016         
1017         /* safety border */
1018         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1019                 fac= 0.1;
1020                 
1021                 a= fac*(x2-x1);
1022                 x1+= a; 
1023                 x2-= a;
1024                 
1025                 a= fac*(y2-y1);
1026                 y1+= a;
1027                 y2-= a;
1028                 
1029                 UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1030                 
1031                 uiSetRoundBox(15);
1032                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1033         }
1034         
1035         setlinestyle(0);
1036         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1037         
1038 }
1039
1040 /* *********************** backdraw for selection *************** */
1041
1042 void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1043 {
1044         RegionView3D *rv3d= ar->regiondata;
1045         struct Base *base;
1046
1047 /*for 2.43 release, don't use glext and just define the constant.
1048   this to avoid possibly breaking platforms before release.*/
1049 #ifndef GL_MULTISAMPLE_ARB
1050         #define GL_MULTISAMPLE_ARB      0x809D
1051 #endif
1052
1053 #ifdef GL_MULTISAMPLE_ARB
1054         int m;
1055 #endif
1056
1057         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || (FACESEL_PAINT_TEST));
1058         else if((G.f & G_TEXTUREPAINT) && scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1059         else if((G.f & G_PARTICLEEDIT) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1060         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1061         else {
1062                 v3d->flag &= ~V3D_NEEDBACKBUFDRAW;
1063                 return;
1064         }
1065
1066         if( !(v3d->flag & V3D_NEEDBACKBUFDRAW) ) return;
1067
1068 //      if(test) {
1069 //              if(qtest()) {
1070 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1071 //                      return;
1072 //              }
1073 //      }
1074
1075         /* Disable FSAA for backbuffer selection.  
1076         
1077         Only works if GL_MULTISAMPLE_ARB is defined by the header
1078         file, which is should be for every OS that supports FSAA.*/
1079
1080 #ifdef GL_MULTISAMPLE_ARB
1081         m = glIsEnabled(GL_MULTISAMPLE_ARB);
1082         if (m) glDisable(GL_MULTISAMPLE_ARB);
1083 #endif
1084
1085         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1086         
1087         glDisable(GL_DITHER);
1088
1089         glClearColor(0.0, 0.0, 0.0, 0.0); 
1090         if(v3d->zbuf) {
1091                 glEnable(GL_DEPTH_TEST);
1092                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1093         }
1094         else {
1095                 glClear(GL_COLOR_BUFFER_BIT);
1096                 glDisable(GL_DEPTH_TEST);
1097         }
1098         
1099         if(rv3d->rflag & RV3D_CLIPPING)
1100                 view3d_set_clipping(rv3d);
1101         
1102         G.f |= G_BACKBUFSEL;
1103         
1104         base= (scene->basact);
1105         if(base && (base->lay & v3d->lay)) {
1106                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1107         }
1108
1109         v3d->flag &= ~V3D_NEEDBACKBUFDRAW;
1110
1111         G.f &= ~G_BACKBUFSEL;
1112         v3d->zbuf= FALSE; 
1113         glDisable(GL_DEPTH_TEST);
1114         glEnable(GL_DITHER);
1115
1116         if(rv3d->rflag & RV3D_CLIPPING)
1117                 view3d_clr_clipping();
1118
1119 #ifdef GL_MULTISAMPLE_ARB
1120         if (m) glEnable(GL_MULTISAMPLE_ARB);
1121 #endif
1122
1123         /* it is important to end a view in a transform compatible with buttons */
1124 //      persp(PERSP_WIN);  // set ortho
1125
1126 }
1127
1128 void view3d_validate_backbuf(ViewContext *vc)
1129 {
1130         if(vc->v3d->flag & V3D_NEEDBACKBUFDRAW)
1131                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1132 }
1133
1134 /* samples a single pixel (copied from vpaint) */
1135 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1136 {
1137         unsigned int col;
1138         
1139         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1140         x+= vc->ar->winrct.xmin;
1141         y+= vc->ar->winrct.ymin;
1142         
1143         view3d_validate_backbuf(vc);
1144
1145         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1146         glReadBuffer(GL_BACK);  
1147         
1148         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1149         
1150         return WM_framebuffer_to_index(col);
1151 }
1152
1153 /* reads full rect, converts indices */
1154 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1155 {
1156         unsigned int *dr, *rd;
1157         struct ImBuf *ibuf, *ibuf1;
1158         int a;
1159         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1160         
1161         /* clip */
1162         if(xmin<0) xminc= 0; else xminc= xmin;
1163         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1164         if(xminc > xmaxc) return NULL;
1165
1166         if(ymin<0) yminc= 0; else yminc= ymin;
1167         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1168         if(yminc > ymaxc) return NULL;
1169         
1170         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1171
1172         view3d_validate_backbuf(vc); 
1173         
1174         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1175         glReadBuffer(GL_BACK);  
1176
1177         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1178
1179         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1180         dr= ibuf->rect;
1181         while(a--) {
1182                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1183                 dr++;
1184         }
1185         
1186         /* put clipped result back, if needed */
1187         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1188                 return ibuf;
1189         
1190         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1191         rd= ibuf->rect;
1192         dr= ibuf1->rect;
1193                 
1194         for(ys= ymin; ys<=ymax; ys++) {
1195                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1196                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1197                                 *dr= *rd;
1198                                 rd++;
1199                         }
1200                 }
1201         }
1202         IMB_freeImBuf(ibuf);
1203         return ibuf1;
1204 }
1205
1206 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1207 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, short mval[2], int size, 
1208                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1209                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1210 {
1211         struct ImBuf *buf;
1212         unsigned int *bufmin, *bufmax, *tbuf;
1213         int minx, miny;
1214         int a, b, rc, nr, amount, dirvec[4][2];
1215         int distance=0;
1216         unsigned int index = 0;
1217         short indexok = 0;      
1218
1219         amount= (size-1)/2;
1220
1221         minx = mval[0]-(amount+1);
1222         miny = mval[1]-(amount+1);
1223         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1224         if (!buf) return 0;
1225
1226         rc= 0;
1227         
1228         dirvec[0][0]= 1; dirvec[0][1]= 0;
1229         dirvec[1][0]= 0; dirvec[1][1]= -size;
1230         dirvec[2][0]= -1; dirvec[2][1]= 0;
1231         dirvec[3][0]= 0; dirvec[3][1]= size;
1232         
1233         bufmin = buf->rect;
1234         tbuf = buf->rect;
1235         bufmax = buf->rect + size*size;
1236         tbuf+= amount*size+ amount;
1237         
1238         for(nr=1; nr<=size; nr++) {
1239                 
1240                 for(a=0; a<2; a++) {
1241                         for(b=0; b<nr; b++, distance++) {
1242                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1243                                         if(strict){
1244                                                 indexok =  indextest(handle, *tbuf - min+1);
1245                                                 if(indexok){
1246                                                         *dist= (short) sqrt( (float)distance   );
1247                                                         index = *tbuf - min+1;
1248                                                         goto exit; 
1249                                                 }                                               
1250                                         }
1251                                         else{
1252                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1253                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1254                                                 goto exit;
1255                                         }                       
1256                                 }
1257                                 
1258                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1259                                 
1260                                 if(tbuf<bufmin || tbuf>=bufmax) {
1261                                         goto exit;
1262                                 }
1263                         }
1264                         rc++;
1265                         rc &= 3;
1266                 }
1267         }
1268
1269 exit:
1270         IMB_freeImBuf(buf);
1271         return index;
1272 }
1273
1274
1275 /* ************************************************************* */
1276
1277 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1278 {
1279         RegionView3D *rv3d= ar->regiondata;
1280         BGpic *bgpic;
1281         Image *ima;
1282         ImBuf *ibuf= NULL;
1283         float vec[4], fac, asp, zoomx, zoomy;
1284         float x1, y1, x2, y2, cx, cy;
1285         
1286         bgpic= v3d->bgpic;
1287         if(bgpic==NULL) return;
1288         
1289         ima= bgpic->ima;
1290         
1291         if(ima)
1292                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1293         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) ) 
1294                 return;
1295         if(ibuf->channels!=4)
1296                 return;
1297         if(ibuf->rect==NULL)
1298                 IMB_rect_from_float(ibuf);
1299         
1300         if(rv3d->persp==2) {
1301                 rctf vb;
1302                 
1303                 calc_viewborder(scene, ar, v3d, &vb);
1304                 
1305                 x1= vb.xmin;
1306                 y1= vb.ymin;
1307                 x2= vb.xmax;
1308                 y2= vb.ymax;
1309         }
1310         else {
1311                 float sco[2];
1312                 
1313                 /* calc window coord */
1314                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1315                 window_to_3d_delta(ar, vec, 1, 0);
1316                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1317                 fac= 1.0/fac;
1318                 
1319                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1320                 
1321                 vec[0] = vec[1] = vec[2] = 0.0;
1322                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1323                 cx = sco[0];
1324                 cy = sco[1];
1325                 
1326                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1327                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1328                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1329                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1330         }
1331         
1332         /* complete clip? */
1333         
1334         if(x2 < 0 ) return;
1335         if(y2 < 0 ) return;
1336         if(x1 > ar->winx ) return;
1337         if(y1 > ar->winy ) return;
1338         
1339         zoomx= (x2-x1)/ibuf->x;
1340         zoomy= (y2-y1)/ibuf->y;
1341         
1342         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1343         if(zoomx < 1.0f || zoomy < 1.0f) {
1344                 float tzoom= MIN2(zoomx, zoomy);
1345                 int mip= 0;
1346                 
1347                 if(ibuf->mipmap[0]==NULL)
1348                         IMB_makemipmap(ibuf, 0);
1349                 
1350                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1351                         tzoom*= 2.0f;
1352                         zoomx*= 2.0f;
1353                         zoomy*= 2.0f;
1354                         mip++;
1355                 }
1356                 if(mip>0)
1357                         ibuf= ibuf->mipmap[mip-1];
1358         }
1359         
1360         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1361         
1362         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
1363         
1364         glMatrixMode(GL_PROJECTION);
1365         glPushMatrix();
1366         glMatrixMode(GL_MODELVIEW);
1367         glPushMatrix();
1368         
1369         glaDefine2DArea(&ar->winrct);
1370         
1371         glEnable(GL_BLEND);
1372         
1373         glPixelZoom(zoomx, zoomy);
1374         glColor4f(1.0, 1.0, 1.0, 1.0-bgpic->blend);
1375         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1376         
1377         glPixelZoom(1.0, 1.0);
1378         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1379         
1380         glMatrixMode(GL_PROJECTION);
1381         glPopMatrix();
1382         glMatrixMode(GL_MODELVIEW);
1383         glPopMatrix();
1384         
1385         glDisable(GL_BLEND);
1386         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1387 }
1388
1389 /* ****************** View3d afterdraw *************** */
1390
1391 typedef struct View3DAfter {
1392         struct View3DAfter *next, *prev;
1393         struct Base *base;
1394         int type, flag;
1395 } View3DAfter;
1396
1397 /* temp storage of Objects that need to be drawn as last */
1398 void add_view3d_after(View3D *v3d, Base *base, int type, int flag)
1399 {
1400         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1401         
1402         BLI_addtail(&v3d->afterdraw, v3da);
1403         v3da->base= base;
1404         v3da->type= type;
1405         v3da->flag= flag;
1406 }
1407
1408 /* clears zbuffer and draws it over */
1409 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1410 {
1411         View3DAfter *v3da, *next;
1412         int doit= 0;
1413         
1414         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
1415                 if(v3da->type==V3D_XRAY) doit= 1;
1416         
1417         if(doit) {
1418                 if(clear && v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
1419                 v3d->xray= TRUE;
1420                 
1421                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1422                         next= v3da->next;
1423                         if(v3da->type==V3D_XRAY) {
1424                                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1425                                 BLI_remlink(&v3d->afterdraw, v3da);
1426                                 MEM_freeN(v3da);
1427                         }
1428                 }
1429                 v3d->xray= FALSE;
1430         }
1431 }
1432
1433 /* disables write in zbuffer and draws it over */
1434 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1435 {
1436         View3DAfter *v3da, *next;
1437         
1438         glDepthMask(0);
1439         v3d->transp= TRUE;
1440         
1441         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1442                 next= v3da->next;
1443                 if(v3da->type==V3D_TRANSP) {
1444                         draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1445                         BLI_remlink(&v3d->afterdraw, v3da);
1446                         MEM_freeN(v3da);
1447                 }
1448         }
1449         v3d->transp= FALSE;
1450         
1451         glDepthMask(1);
1452         
1453 }
1454
1455 /* *********************** */
1456
1457 /*
1458         In most cases call draw_dupli_objects,
1459         draw_dupli_objects_color was added because when drawing set dupli's
1460         we need to force the color
1461  */
1462 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1463 {       
1464         RegionView3D *rv3d= ar->regiondata;
1465         ListBase *lb;
1466         DupliObject *dob;
1467         Base tbase;
1468         BoundBox *bb= NULL;
1469         GLuint displist=0;
1470         short transflag, use_displist= -1;      /* -1 is initialize */
1471         char dt, dtx;
1472         
1473         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1474         
1475         tbase.flag= OB_FROMDUPLI|base->flag;
1476         lb= object_duplilist(scene, base->object);
1477         
1478         for(dob= lb->first; dob; dob= dob->next) {
1479                 if(dob->no_draw);
1480                 else {
1481                         tbase.object= dob->ob;
1482                         
1483                         /* extra service: draw the duplicator in drawtype of parent */
1484                         /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1485                         dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1486                         dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1487                         
1488                         /* negative scale flag has to propagate */
1489                         transflag= tbase.object->transflag;
1490                         if(base->object->transflag & OB_NEG_SCALE)
1491                                 tbase.object->transflag ^= OB_NEG_SCALE;
1492                         
1493                         UI_ThemeColorBlend(color, TH_BACK, 0.5);
1494                         
1495                         /* generate displist, test for new object */
1496                         if(use_displist==1 && dob->prev && dob->prev->ob!=dob->ob) {
1497                                 use_displist= -1;
1498                                 glDeleteLists(displist, 1);
1499                         }
1500                         /* generate displist */
1501                         if(use_displist == -1) {
1502                                 
1503                                 /* lamp drawing messes with matrices, could be handled smarter... but this works */
1504                                 if(dob->ob->type==OB_LAMP || dob->type==OB_DUPLIGROUP)
1505                                         use_displist= 0;
1506                                 else {
1507                                         /* disable boundbox check for list creation */
1508                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1509                                         /* need this for next part of code */
1510                                         bb= object_get_boundbox(dob->ob);
1511                                         
1512                                         Mat4One(dob->ob->obmat);        /* obmat gets restored */
1513                                         
1514                                         displist= glGenLists(1);
1515                                         glNewList(displist, GL_COMPILE);
1516                                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1517                                         glEndList();
1518                                         
1519                                         use_displist= 1;
1520                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1521                                 }
1522                         }
1523                         if(use_displist) {
1524                                 wmMultMatrix(dob->mat);
1525                                 if(boundbox_clip(rv3d, dob->mat, bb))
1526                                         glCallList(displist);
1527                                 wmLoadMatrix(rv3d->viewmat);
1528                         }
1529                         else {
1530                                 Mat4CpyMat4(dob->ob->obmat, dob->mat);
1531                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1532                         }
1533                         
1534                         tbase.object->dt= dt;
1535                         tbase.object->dtx= dtx;
1536                         tbase.object->transflag= transflag;
1537                 }
1538         }
1539         
1540         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1541         
1542         free_object_duplilist(lb);      /* does restore */
1543         
1544         if(use_displist)
1545                 glDeleteLists(displist, 1);
1546 }
1547
1548 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1549 {
1550         /* define the color here so draw_dupli_objects_color can be called
1551         * from the set loop */
1552         
1553         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1554         /* debug */
1555         if(base->object->dup_group && base->object->dup_group->id.us<1)
1556                 color= TH_REDALERT;
1557         
1558         draw_dupli_objects_color(scene, ar, v3d, base, color);
1559 }
1560
1561
1562 void view3d_update_depths(ARegion *ar, View3D *v3d)
1563 {
1564         RegionView3D *rv3d= ar->regiondata;
1565         
1566         /* Create storage for, and, if necessary, copy depth buffer */
1567         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1568         if(rv3d->depths) {
1569                 ViewDepths *d= rv3d->depths;
1570                 if(d->w != ar->winx ||
1571                    d->h != ar->winy ||
1572                    !d->depths) {
1573                         d->w= ar->winx;
1574                         d->h= ar->winy;
1575                         if(d->depths)
1576                                 MEM_freeN(d->depths);
1577                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1578                         d->damaged= 1;
1579                 }
1580                 
1581                 if(d->damaged) {
1582                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1583                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1584                         
1585                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1586                         
1587                         d->damaged= 0;
1588                 }
1589         }
1590 }
1591
1592 /* Enable sculpting in wireframe mode by drawing sculpt object only to the depth buffer */
1593 static void draw_sculpt_depths(Scene *scene, ARegion *ar, View3D *v3d)
1594 {
1595         Object *ob = OBACT;
1596         
1597         int dt= MIN2(v3d->drawtype, ob->dt);
1598         if(v3d->zbuf==0 && dt>OB_WIRE)
1599                 dt= OB_WIRE;
1600         if(dt == OB_WIRE) {
1601                 GLboolean depth_on;
1602                 int orig_vdt = v3d->drawtype;
1603                 int orig_zbuf = v3d->zbuf;
1604                 int orig_odt = ob->dt;
1605                 
1606                 glGetBooleanv(GL_DEPTH_TEST, &depth_on);
1607                 v3d->drawtype = ob->dt = OB_SOLID;
1608                 v3d->zbuf = 1;
1609                 
1610                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1611                 glEnable(GL_DEPTH_TEST);
1612                 draw_object(scene, ar, v3d, BASACT, 0);
1613                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1614                 if(!depth_on)
1615                         glDisable(GL_DEPTH_TEST);
1616                 
1617                 v3d->drawtype = orig_vdt;
1618                 v3d->zbuf = orig_zbuf;
1619                 ob->dt = orig_odt;
1620         }
1621 }
1622
1623 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1624 {
1625         RegionView3D *rv3d= ar->regiondata;
1626         Base *base;
1627         Scene *sce;
1628         short zbuf, flag;
1629         float glalphaclip;
1630         /* temp set drawtype to solid */
1631         
1632         /* Setting these temporarily is not nice */
1633         zbuf = v3d->zbuf;
1634         flag = v3d->flag;
1635         glalphaclip = U.glalphaclip;
1636         
1637         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1638         v3d->flag &= ~V3D_SELECT_OUTLINE;
1639         
1640         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1641         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1642         
1643         Mat4MulMat4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1644         Mat4Invert(rv3d->persinv, rv3d->persmat);
1645         Mat4Invert(rv3d->viewinv, rv3d->viewmat);
1646         
1647         glClear(GL_DEPTH_BUFFER_BIT);
1648         
1649         wmLoadMatrix(rv3d->viewmat);
1650 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1651         
1652         if(rv3d->rflag & RV3D_CLIPPING) {
1653                 view3d_set_clipping(rv3d);
1654         }
1655         
1656         v3d->zbuf= TRUE;
1657         glEnable(GL_DEPTH_TEST);
1658         
1659         /* draw set first */
1660         if(scene->set) {
1661                 for(SETLOOPER(scene->set, base)) {
1662                         if(v3d->lay & base->lay) {
1663                                 if (func == NULL || func(base)) {
1664                                         draw_object(scene, ar, v3d, base, 0);
1665                                         if(base->object->transflag & OB_DUPLI) {
1666                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1667                                         }
1668                                 }
1669                         }
1670                 }
1671         }
1672         
1673         for(base= scene->base.first; base; base= base->next) {
1674                 if(v3d->lay & base->lay) {
1675                         if (func == NULL || func(base)) {
1676                                 /* dupli drawing */
1677                                 if(base->object->transflag & OB_DUPLI) {
1678                                         draw_dupli_objects(scene, ar, v3d, base);
1679                                 }
1680                                 draw_object(scene, ar, v3d, base, 0);
1681                         }
1682                 }
1683         }
1684         
1685         /* this isnt that nice, draw xray objects as if they are normal */
1686         if (v3d->afterdraw.first) {
1687                 View3DAfter *v3da, *next;
1688                 int num = 0;
1689                 v3d->xray= TRUE;
1690                 
1691                 glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1692                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1693                         next= v3da->next;
1694                         if(v3da->type==V3D_XRAY) {
1695                                 draw_object(scene, ar, v3d, v3da->base, 0);
1696                                 num++;
1697                         }
1698                         /* dont remove this time */
1699                 }
1700                 v3d->xray= FALSE;
1701                 
1702                 glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1703                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1704                         next= v3da->next;
1705                         if(v3da->type==V3D_XRAY) {
1706                                 v3d->xray= TRUE; v3d->transp= FALSE;  
1707                         } else if (v3da->type==V3D_TRANSP) {
1708                                 v3d->xray= FALSE; v3d->transp= TRUE;
1709                         }
1710                         
1711                         draw_object(scene, ar, v3d, v3da->base, 0); /* Draw Xray or Transp objects normally */
1712                         BLI_remlink(&v3d->afterdraw, v3da);
1713                         MEM_freeN(v3da);
1714                 }
1715                 v3d->xray= FALSE;
1716                 v3d->transp= FALSE;
1717         }
1718         
1719         v3d->zbuf = zbuf;
1720         U.glalphaclip = glalphaclip;
1721         v3d->flag = flag;
1722 }
1723
1724 typedef struct View3DShadow {
1725         struct View3DShadow *next, *prev;
1726         GPULamp *lamp;
1727 } View3DShadow;
1728
1729 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1730 {
1731         GPULamp *lamp;
1732         Lamp *la = (Lamp*)ob->data;
1733         View3DShadow *shadow;
1734         
1735         lamp = GPU_lamp_from_blender(scene, ob, par);
1736         
1737         if(lamp) {
1738                 GPU_lamp_update(lamp, ob->lay, obmat);
1739                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1740                 
1741                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1742                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1743                         shadow->lamp = lamp;
1744                         BLI_addtail(shadows, shadow);
1745                 }
1746         }
1747 }
1748
1749 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1750 {
1751         ListBase shadows;
1752         View3DShadow *shadow;
1753         Scene *sce;
1754         Base *base;
1755         Object *ob;
1756         
1757         shadows.first= shadows.last= NULL;
1758         
1759         /* update lamp transform and gather shadow lamps */
1760         for(SETLOOPER(scene, base)) {
1761                 ob= base->object;
1762                 
1763                 if(ob->type == OB_LAMP)
1764                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
1765                 
1766                 if (ob->transflag & OB_DUPLI) {
1767                         DupliObject *dob;
1768                         ListBase *lb = object_duplilist(scene, ob);
1769                         
1770                         for(dob=lb->first; dob; dob=dob->next)
1771                                 if(dob->ob->type==OB_LAMP)
1772                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
1773                         
1774                         free_object_duplilist(lb);
1775                 }
1776         }
1777         
1778         /* render shadows after updating all lamps, nested object_duplilist
1779                 * don't work correct since it's replacing object matrices */
1780         for(shadow=shadows.first; shadow; shadow=shadow->next) {
1781                 /* this needs to be done better .. */
1782                 float viewmat[4][4], winmat[4][4];
1783                 int drawtype, lay, winsize, flag2;
1784                 
1785                 drawtype= v3d->drawtype;
1786                 lay= v3d->lay;
1787                 flag2= v3d->flag2 & V3D_SOLID_TEX;
1788                 
1789                 v3d->drawtype = OB_SOLID;
1790                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1791                 v3d->flag2 &= ~V3D_SOLID_TEX;
1792                 
1793                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1794 // XXX          drawview3d_render(v3d, viewmat, winsize, winsize, winmat, 1);
1795                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1796                 
1797                 v3d->drawtype= drawtype;
1798                 v3d->lay= lay;
1799                 v3d->flag2 |= flag2;
1800         }
1801         
1802         BLI_freelistN(&shadows);
1803 }
1804
1805 /* *********************** customdata **************** */
1806
1807 /* goes over all modes and view3d settings */
1808 static CustomDataMask get_viewedit_datamask(bScreen *screen)
1809 {
1810         CustomDataMask mask = CD_MASK_BAREMESH;
1811         ScrArea *sa;
1812         
1813         /* check if we need tfaces & mcols due to face select or texture paint */
1814         if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT)
1815                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1816         
1817         /* check if we need tfaces & mcols due to view mode */
1818         for(sa = screen->areabase.first; sa; sa = sa->next) {
1819                 if(sa->spacetype == SPACE_VIEW3D) {
1820                         View3D *view = sa->spacedata.first;
1821                         if(view->drawtype == OB_SHADED) {
1822                                 /* this includes normals for mesh_create_shadedColors */
1823                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
1824                         }
1825                         if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
1826                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1827                                 
1828                                 if((G.fileflags & G_FILE_GAME_MAT) &&
1829                                    (G.fileflags & G_FILE_GAME_MAT_GLSL)) {
1830                                         mask |= CD_MASK_ORCO;
1831                                 }
1832                         }
1833                 }
1834         }
1835         
1836         /* check if we need mcols due to vertex paint or weightpaint */
1837         if(G.f & G_VERTEXPAINT)
1838                 mask |= CD_MASK_MCOL;
1839         if(G.f & G_WEIGHTPAINT)
1840                 mask |= CD_MASK_WEIGHT_MCOL;
1841         
1842         if(G.f & G_SCULPTMODE)
1843                 mask |= CD_MASK_MDISPS;
1844         
1845         return mask;
1846 }
1847
1848 void view3d_main_area_draw(const bContext *C, ARegion *ar)
1849 {
1850         Scene *scene= CTX_data_scene(C);
1851         View3D *v3d = CTX_wm_view3d(C);
1852         RegionView3D *rv3d= CTX_wm_region_view3d(C);
1853         Scene *sce;
1854         Base *base;
1855         Object *ob;
1856         int retopo= 0, sculptparticle= 0;
1857         Object *obact = OBACT;
1858         
1859         /* from now on all object derived meshes check this */
1860         v3d->customdata_mask= get_viewedit_datamask(CTX_wm_screen(C));
1861         
1862         /* shadow buffers, before we setup matrices */
1863         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
1864                 gpu_update_lamps_shadows(scene, v3d);
1865         
1866         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1867         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1868         
1869         Mat4MulMat4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1870         Mat4Invert(rv3d->persinv, rv3d->persmat);
1871         Mat4Invert(rv3d->viewinv, rv3d->viewmat);
1872         
1873         /* calculate pixelsize factor once, is used for lamps and obcenters */
1874         {
1875                 float len1, len2, vec[3];
1876                 
1877                 VECCOPY(vec, rv3d->persinv[0]);
1878                 len1= Normalize(vec);
1879                 VECCOPY(vec, rv3d->persinv[1]);
1880                 len2= Normalize(vec);
1881                 
1882                 rv3d->pixsize= 2.0f*(len1>len2?len1:len2);
1883                 
1884                 /* correct for window size */
1885                 if(ar->winx > ar->winy) rv3d->pixsize/= (float)ar->winx;
1886                 else rv3d->pixsize/= (float)ar->winy;
1887         }
1888         
1889         if(v3d->drawtype > OB_WIRE) {
1890                 float col[3];
1891                 UI_GetThemeColor3fv(TH_BACK, col);
1892                 glClearColor(col[0], col[1], col[2], 0.0); 
1893                 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1894                 
1895                 glLoadIdentity();
1896         }
1897         else {
1898                 float col[3];
1899                 UI_GetThemeColor3fv(TH_BACK, col);
1900                 glClearColor(col[0], col[1], col[2], 0.0);
1901                 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1902         }
1903         
1904         wmLoadMatrix(rv3d->viewmat);
1905         
1906         if(rv3d->rflag & RV3D_CLIPPING)
1907                 view3d_draw_clipping(rv3d);
1908         
1909         /* set zbuffer after we draw clipping region */
1910         if(v3d->drawtype > OB_WIRE) {
1911                 v3d->zbuf= TRUE;
1912                 glEnable(GL_DEPTH_TEST);
1913         }
1914         
1915         // needs to be done always, gridview is adjusted in drawgrid() now
1916         v3d->gridview= v3d->grid;
1917         
1918         if(rv3d->view==0 || rv3d->persp!=0) {
1919                 drawfloor(scene, v3d);
1920                 if(rv3d->persp==2) {
1921                         if(scene->world) {
1922                                 if(scene->world->mode & WO_STARS) {
1923                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
1924                                                                   star_stuff_term_func);
1925                                 }
1926                         }
1927                         if(v3d->flag & V3D_DISPBGPIC) draw_bgpic(scene, ar, v3d);
1928                 }
1929         }
1930         else {
1931                 ED_region_pixelspace(ar);
1932                 drawgrid(ar, v3d);
1933                 /* XXX make function? replaces persp(1) */
1934                 glMatrixMode(GL_PROJECTION);
1935                 wmLoadMatrix(rv3d->winmat);
1936                 glMatrixMode(GL_MODELVIEW);
1937                 wmLoadMatrix(rv3d->viewmat);
1938                 
1939                 if(v3d->flag & V3D_DISPBGPIC) {
1940                         draw_bgpic(scene, ar, v3d);
1941                 }
1942         }
1943         
1944         if(rv3d->rflag & RV3D_CLIPPING)
1945                 view3d_set_clipping(rv3d);
1946         
1947         /* draw set first */
1948         if(scene->set) {
1949                 for(SETLOOPER(scene->set, base)) {
1950                         
1951                         if(v3d->lay & base->lay) {
1952                                 
1953                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1954                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
1955                                 
1956                                 if(base->object->transflag & OB_DUPLI) {
1957                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1958                                 }
1959                         }
1960                 }
1961                 
1962                 /* Transp and X-ray afterdraw stuff for sets is done later */
1963         }
1964         
1965         /* extra service in layerbuttons, showing used layers */
1966         v3d->lay_used = 0;
1967         
1968         /* then draw not selected and the duplis, but skip editmode object */
1969         for(base= scene->base.first; base; base= base->next) {
1970                 v3d->lay_used |= base->lay;
1971                 
1972                 if(v3d->lay & base->lay) {
1973                         
1974                         /* dupli drawing */
1975                         if(base->object->transflag & OB_DUPLI) {
1976                                 draw_dupli_objects(scene, ar, v3d, base);
1977                         }
1978                         if((base->flag & SELECT)==0) {
1979                                 if(base->object!=scene->obedit) 
1980                                         draw_object(scene, ar, v3d, base, 0);
1981                         }
1982                 }
1983         }
1984
1985 //      retopo= retopo_mesh_check() || retopo_curve_check();
1986         sculptparticle= (G.f & (G_SCULPTMODE|G_PARTICLEEDIT)) && !scene->obedit;
1987         if(retopo)
1988                 view3d_update_depths(ar, v3d);
1989         
1990         /* draw selected and editmode */
1991         for(base= scene->base.first; base; base= base->next) {
1992                 if(v3d->lay & base->lay) {
1993                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
1994                                 draw_object(scene, ar, v3d, base, 0);
1995                 }
1996         }
1997         
1998         if(!retopo && sculptparticle && !(obact && (obact->dtx & OB_DRAWXRAY))) {
1999                 if(G.f & G_SCULPTMODE)
2000                         draw_sculpt_depths(scene, ar, v3d);
2001                 view3d_update_depths(ar, v3d);
2002         }
2003         
2004         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST);
2005         
2006 //      REEB_draw();
2007         
2008 //      if(scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
2009         
2010         /* Transp and X-ray afterdraw stuff */
2011         view3d_draw_transp(scene, ar, v3d);
2012         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2013         
2014         if(!retopo && sculptparticle && (obact && (OBACT->dtx & OB_DRAWXRAY))) {
2015                 if(G.f & G_SCULPTMODE)
2016                         draw_sculpt_depths(scene, ar, v3d);
2017                 view3d_update_depths(ar, v3d);
2018         }
2019         
2020         if(rv3d->rflag & RV3D_CLIPPING)
2021                 view3d_clr_clipping();
2022         
2023         BIF_draw_manipulator(C);
2024         
2025         if(v3d->zbuf) {
2026                 v3d->zbuf= FALSE;
2027                 glDisable(GL_DEPTH_TEST);
2028         }
2029         
2030         /* draw grease-pencil stuff */
2031 //      if (v3d->flag2 & V3D_DISPGP)
2032 //              draw_gpencil_3dview(ar, 1);
2033         
2034         BDR_drawSketch(C);
2035         
2036         ED_region_pixelspace(ar);
2037         
2038         /* Draw Sculpt Mode brush XXX (removed) */
2039         
2040 //      retopo_paint_view_update(v3d);
2041 //      retopo_draw_paint_lines();
2042         
2043         /* Draw particle edit brush XXX (removed) */
2044         
2045         if(rv3d->persp>1) drawviewborder(scene, ar, v3d);
2046         if(rv3d->rflag & RV3D_FLYMODE) drawviewborder_flymode(ar);
2047         
2048         /* draw grease-pencil stuff */
2049 //      if (v3d->flag2 & V3D_DISPGP)
2050 //              draw_gpencil_3dview(ar, 0);
2051
2052         drawcursor(scene, ar, v3d);
2053         
2054         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2055                 draw_view_axis(rv3d);
2056         else    
2057                 draw_view_icon(rv3d);
2058         
2059         /* XXX removed viewport fps */
2060         if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2061                 draw_viewport_name(ar, v3d);
2062         }
2063         
2064         ob= OBACT;
2065         if(U.uiflag & USER_DRAWVIEWINFO) 
2066                 draw_selected_name(scene, ob, v3d);
2067         
2068         /* XXX here was the blockhandlers for floating panels */
2069
2070         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT) {
2071                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2072                 // XXX addafterqueue(ar->win, BACKBUFDRAW, 1);
2073         }
2074
2075         if((G.f & G_PARTICLEEDIT) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
2076                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2077                 // XXX addafterqueue(ar->win, BACKBUFDRAW, 1);
2078         }
2079
2080         // test for backbuf select
2081         if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
2082                 
2083                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2084                 // XXX if(afterqtest(ar->win, BACKBUFDRAW)==0) {
2085                 //      addafterqueue(ar->win, BACKBUFDRAW, 1);
2086                 //}
2087         }
2088         
2089 #ifndef DISABLE_PYTHON
2090         /* XXX here was scriptlink */
2091 #endif  
2092 }
2093
2094