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