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