Sculpt: svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r24095...
[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                                 EditBone *ebo;
795                                 for (ebo=arm->edbo->first; ebo; ebo=ebo->next){
796                                         if ((ebo->flag & BONE_ACTIVE) && (ebo->layer & arm->layer)) {
797                                                 name= ebo->name;
798                                                 break;
799                                         }
800                                 }
801                         }
802                         else if(ob->pose && (ob->mode & OB_MODE_POSE)) {
803                                 bPoseChannel *pchan;
804                                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
805                                         if((pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer)) {
806                                                 name= pchan->name;
807                                                 break;
808                                         }
809                                 }
810                         }
811                         if(name && markern)
812                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, name, markern);
813                         else if(name)
814                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
815                         else
816                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
817                 }
818                 else if(ELEM3(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
819                         Key *key= NULL;
820                         KeyBlock *kb = NULL;
821                         char shapes[75];
822                         
823                         /* try to display active shapekey too */
824                         shapes[0] = 0;
825                         key = ob_get_key(ob);
826                         if(key){
827                                 kb = BLI_findlink(&key->block, ob->shapenr-1);
828                                 if(kb){
829                                         sprintf(shapes, ": %s ", kb->name);             
830                                         if(ob->shapeflag == OB_SHAPE_LOCK){
831                                                 sprintf(shapes, "%s (Pinned)",shapes);
832                                         }
833                                 }
834                         }
835                         
836                         if(markern)
837                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, shapes, markern);
838                         else
839                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
840                 }
841                 else {
842                         /* standard object */
843                         if (markern)
844                                 sprintf(info, "(%d) %s <%s>", CFRA, ob->id.name+2, markern);
845                         else
846                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
847                 }
848                 
849                 /* colour depends on whether there is a keyframe */
850                 if (id_frame_has_keyframe((ID *)ob, /*frame_to_float(scene, CFRA)*/(float)(CFRA), v3d->keyflags))
851                         UI_ThemeColor(TH_VERTEX_SELECT);
852                 else
853                         UI_ThemeColor(TH_TEXT_HI);
854         }
855         else {
856                 /* no object */
857                 if (markern)
858                         sprintf(info, "(%d) <%s>", CFRA, markern);
859                 else
860                         sprintf(info, "(%d)", CFRA);
861                 
862                 /* colour is always white */
863                 UI_ThemeColor(TH_TEXT_HI);
864         }
865         
866         if (U.uiflag & USER_SHOW_ROTVIEWICON)
867                 offset = 14 + (U.rvisize * 2);
868
869         BLF_draw_default(offset,  10, 0.0f, info);
870 }
871
872 static void view3d_get_viewborder_size(Scene *scene, ARegion *ar, float size_r[2])
873 {
874         float winmax= MAX2(ar->winx, ar->winy);
875         float aspect= (float) (scene->r.xsch*scene->r.xasp)/(scene->r.ysch*scene->r.yasp);
876         
877         if(aspect>1.0) {
878                 size_r[0]= winmax;
879                 size_r[1]= winmax/aspect;
880         } else {
881                 size_r[0]= winmax*aspect;
882                 size_r[1]= winmax;
883         }
884 }
885
886 void calc_viewborder(Scene *scene, ARegion *ar, View3D *v3d, rctf *viewborder_r)
887 {
888         RegionView3D *rv3d= ar->regiondata;
889         float zoomfac, size[2];
890         float dx= 0.0f, dy= 0.0f;
891         
892         view3d_get_viewborder_size(scene, ar, size);
893         
894         /* magic zoom calculation, no idea what
895                 * it signifies, if you find out, tell me! -zr
896                 */
897         /* simple, its magic dude!
898                 * well, to be honest, this gives a natural feeling zooming
899                 * with multiple keypad presses (ton)
900                 */
901         
902         zoomfac= (M_SQRT2 + rv3d->camzoom/50.0);
903         zoomfac= (zoomfac*zoomfac)*0.25;
904         
905         size[0]= size[0]*zoomfac;
906         size[1]= size[1]*zoomfac;
907         
908         /* center in window */
909         viewborder_r->xmin= 0.5*ar->winx - 0.5*size[0];
910         viewborder_r->ymin= 0.5*ar->winy - 0.5*size[1];
911         viewborder_r->xmax= viewborder_r->xmin + size[0];
912         viewborder_r->ymax= viewborder_r->ymin + size[1];
913         
914         dx= ar->winx*rv3d->camdx*zoomfac*2.0f;
915         dy= ar->winy*rv3d->camdy*zoomfac*2.0f;
916         
917         /* apply offset */
918         viewborder_r->xmin-= dx;
919         viewborder_r->ymin-= dy;
920         viewborder_r->xmax-= dx;
921         viewborder_r->ymax-= dy;
922         
923         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
924                 Camera *cam= v3d->camera->data;
925                 float w = viewborder_r->xmax - viewborder_r->xmin;
926                 float h = viewborder_r->ymax - viewborder_r->ymin;
927                 float side = MAX2(w, h);
928                 
929                 viewborder_r->xmin+= cam->shiftx*side;
930                 viewborder_r->xmax+= cam->shiftx*side;
931                 viewborder_r->ymin+= cam->shifty*side;
932                 viewborder_r->ymax+= cam->shifty*side;
933         }
934 }
935
936 void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar)
937 {
938         RegionView3D *rv3d= ar->regiondata;
939         float size[2];
940         int im_width= (scene->r.size*scene->r.xsch)/100;
941         
942         view3d_get_viewborder_size(scene, ar, size);
943         
944         rv3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
945         rv3d->camzoom= CLAMPIS(rv3d->camzoom, -30, 300);
946 }
947
948
949 static void drawviewborder_flymode(ARegion *ar) 
950 {
951         /* draws 4 edge brackets that frame the safe area where the
952         mouse can move during fly mode without spinning the view */
953         float x1, x2, y1, y2;
954         
955         x1= 0.45*(float)ar->winx;
956         y1= 0.45*(float)ar->winy;
957         x2= 0.55*(float)ar->winx;
958         y2= 0.55*(float)ar->winy;
959         cpack(0);
960         
961         
962         glBegin(GL_LINES);
963         /* bottom left */
964         glVertex2f(x1,y1); 
965         glVertex2f(x1,y1+5);
966         
967         glVertex2f(x1,y1); 
968         glVertex2f(x1+5,y1);
969         
970         /* top right */
971         glVertex2f(x2,y2); 
972         glVertex2f(x2,y2-5);
973         
974         glVertex2f(x2,y2); 
975         glVertex2f(x2-5,y2);
976         
977         /* top left */
978         glVertex2f(x1,y2); 
979         glVertex2f(x1,y2-5);
980         
981         glVertex2f(x1,y2); 
982         glVertex2f(x1+5,y2);
983         
984         /* bottom right */
985         glVertex2f(x2,y1); 
986         glVertex2f(x2,y1+5);
987         
988         glVertex2f(x2,y1); 
989         glVertex2f(x2-5,y1);
990         glEnd();        
991 }
992
993
994 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
995 {
996         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
997         float fac, a;
998         float x1, x2, y1, y2;
999         float x3, y3, x4, y4;
1000         rctf viewborder;
1001         Camera *ca= NULL;
1002         
1003         if(v3d->camera==NULL)
1004                 return;
1005         if(v3d->camera->type==OB_CAMERA)
1006                 ca = v3d->camera->data;
1007         
1008         calc_viewborder(scene, ar, v3d, &viewborder);
1009         x1= viewborder.xmin;
1010         y1= viewborder.ymin;
1011         x2= viewborder.xmax;
1012         y2= viewborder.ymax;
1013         
1014         /* passepartout, specified in camera edit buttons */
1015         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
1016                 if (ca->passepartalpha == 1.0) {
1017                         glColor3f(0, 0, 0);
1018                 } else {
1019                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1020                         glEnable(GL_BLEND);
1021                         glColor4f(0, 0, 0, ca->passepartalpha);
1022                 }
1023                 if (x1 > 0.0)
1024                         glRectf(0.0, (float)ar->winy, x1, 0.0);
1025                 if (x2 < (float)ar->winx)
1026                         glRectf(x2, (float)ar->winy, (float)ar->winx, 0.0);
1027                 if (y2 < (float)ar->winy)
1028                         glRectf(x1, (float)ar->winy, x2, y2);
1029                 if (y2 > 0.0) 
1030                         glRectf(x1, y1, x2, 0.0);
1031                 
1032                 glDisable(GL_BLEND);
1033         }
1034         
1035         /* edge */
1036         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
1037         
1038         setlinestyle(0);
1039         UI_ThemeColor(TH_BACK);
1040         glRectf(x1, y1, x2, y2);
1041         
1042         setlinestyle(3);
1043         UI_ThemeColor(TH_WIRE);
1044         glRectf(x1, y1, x2, y2);
1045         
1046         /* camera name - draw in highlighted text color */
1047         if (ca && (ca->flag & CAM_SHOWNAME)) {
1048                 UI_ThemeColor(TH_TEXT_HI);
1049                 BLF_draw_default(x1, y1-15, 0.0f, v3d->camera->id.name+2);
1050                 UI_ThemeColor(TH_WIRE);
1051         }
1052         
1053         
1054         /* border */
1055         if(scene->r.mode & R_BORDER) {
1056                 
1057                 cpack(0);
1058                 x3= x1+ scene->r.border.xmin*(x2-x1);
1059                 y3= y1+ scene->r.border.ymin*(y2-y1);
1060                 x4= x1+ scene->r.border.xmax*(x2-x1);
1061                 y4= y1+ scene->r.border.ymax*(y2-y1);
1062                 
1063                 cpack(0x4040FF);
1064                 glRectf(x3,  y3,  x4,  y4); 
1065         }
1066         
1067         /* safety border */
1068         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1069                 fac= 0.1;
1070                 
1071                 a= fac*(x2-x1);
1072                 x1+= a; 
1073                 x2-= a;
1074                 
1075                 a= fac*(y2-y1);
1076                 y1+= a;
1077                 y2-= a;
1078                 
1079                 UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1080                 
1081                 uiSetRoundBox(15);
1082                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1083         }
1084         
1085         setlinestyle(0);
1086         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1087         
1088 }
1089
1090 /* *********************** backdraw for selection *************** */
1091
1092 void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1093 {
1094         RegionView3D *rv3d= ar->regiondata;
1095         struct Base *base = scene->basact;
1096         rcti winrct;
1097
1098 /*for 2.43 release, don't use glext and just define the constant.
1099   this to avoid possibly breaking platforms before release.*/
1100 #ifndef GL_MULTISAMPLE_ARB
1101         #define GL_MULTISAMPLE_ARB      0x809D
1102 #endif
1103
1104 #ifdef GL_MULTISAMPLE_ARB
1105         int m;
1106 #endif
1107
1108         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1109                      paint_facesel_test(base->object)));
1110         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1111                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1112         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1113         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1114         else {
1115                 v3d->flag &= ~V3D_NEEDBACKBUFDRAW;
1116                 return;
1117         }
1118
1119         if( !(v3d->flag & V3D_NEEDBACKBUFDRAW) ) return;
1120
1121 //      if(test) {
1122 //              if(qtest()) {
1123 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1124 //                      return;
1125 //              }
1126 //      }
1127
1128         /* Disable FSAA for backbuffer selection.  
1129         
1130         Only works if GL_MULTISAMPLE_ARB is defined by the header
1131         file, which is should be for every OS that supports FSAA.*/
1132
1133 #ifdef GL_MULTISAMPLE_ARB
1134         m = glIsEnabled(GL_MULTISAMPLE_ARB);
1135         if (m) glDisable(GL_MULTISAMPLE_ARB);
1136 #endif
1137
1138         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1139         
1140         glDisable(GL_DITHER);
1141
1142         region_scissor_winrct(ar, &winrct);
1143         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1144
1145         glClearColor(0.0, 0.0, 0.0, 0.0); 
1146         if(v3d->zbuf) {
1147                 glEnable(GL_DEPTH_TEST);
1148                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1149         }
1150         else {
1151                 glClear(GL_COLOR_BUFFER_BIT);
1152                 glDisable(GL_DEPTH_TEST);
1153         }
1154         
1155         if(rv3d->rflag & RV3D_CLIPPING)
1156                 view3d_set_clipping(rv3d);
1157         
1158         G.f |= G_BACKBUFSEL;
1159         
1160         if(base && (base->lay & v3d->lay)) {
1161                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1162         }
1163
1164         v3d->flag &= ~V3D_NEEDBACKBUFDRAW;
1165
1166         G.f &= ~G_BACKBUFSEL;
1167         v3d->zbuf= FALSE; 
1168         glDisable(GL_DEPTH_TEST);
1169         glEnable(GL_DITHER);
1170
1171         if(rv3d->rflag & RV3D_CLIPPING)
1172                 view3d_clr_clipping();
1173
1174 #ifdef GL_MULTISAMPLE_ARB
1175         if (m) glEnable(GL_MULTISAMPLE_ARB);
1176 #endif
1177
1178         /* it is important to end a view in a transform compatible with buttons */
1179 //      persp(PERSP_WIN);  // set ortho
1180
1181 }
1182
1183 void view3d_validate_backbuf(ViewContext *vc)
1184 {
1185         if(vc->v3d->flag & V3D_NEEDBACKBUFDRAW)
1186                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1187 }
1188
1189 /* samples a single pixel (copied from vpaint) */
1190 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1191 {
1192         unsigned int col;
1193         
1194         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1195         x+= vc->ar->winrct.xmin;
1196         y+= vc->ar->winrct.ymin;
1197         
1198         view3d_validate_backbuf(vc);
1199
1200         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1201         glReadBuffer(GL_BACK);  
1202         
1203         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1204         
1205         return WM_framebuffer_to_index(col);
1206 }
1207
1208 /* reads full rect, converts indices */
1209 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1210 {
1211         unsigned int *dr, *rd;
1212         struct ImBuf *ibuf, *ibuf1;
1213         int a;
1214         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1215         
1216         /* clip */
1217         if(xmin<0) xminc= 0; else xminc= xmin;
1218         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1219         if(xminc > xmaxc) return NULL;
1220
1221         if(ymin<0) yminc= 0; else yminc= ymin;
1222         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1223         if(yminc > ymaxc) return NULL;
1224         
1225         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1226
1227         view3d_validate_backbuf(vc); 
1228         
1229         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1230         glReadBuffer(GL_BACK);  
1231
1232         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1233
1234         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1235         dr= ibuf->rect;
1236         while(a--) {
1237                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1238                 dr++;
1239         }
1240         
1241         /* put clipped result back, if needed */
1242         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1243                 return ibuf;
1244         
1245         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1246         rd= ibuf->rect;
1247         dr= ibuf1->rect;
1248                 
1249         for(ys= ymin; ys<=ymax; ys++) {
1250                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1251                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1252                                 *dr= *rd;
1253                                 rd++;
1254                         }
1255                 }
1256         }
1257         IMB_freeImBuf(ibuf);
1258         return ibuf1;
1259 }
1260
1261 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1262 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, short mval[2], int size, 
1263                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1264                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1265 {
1266         struct ImBuf *buf;
1267         unsigned int *bufmin, *bufmax, *tbuf;
1268         int minx, miny;
1269         int a, b, rc, nr, amount, dirvec[4][2];
1270         int distance=0;
1271         unsigned int index = 0;
1272         short indexok = 0;      
1273
1274         amount= (size-1)/2;
1275
1276         minx = mval[0]-(amount+1);
1277         miny = mval[1]-(amount+1);
1278         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1279         if (!buf) return 0;
1280
1281         rc= 0;
1282         
1283         dirvec[0][0]= 1; dirvec[0][1]= 0;
1284         dirvec[1][0]= 0; dirvec[1][1]= -size;
1285         dirvec[2][0]= -1; dirvec[2][1]= 0;
1286         dirvec[3][0]= 0; dirvec[3][1]= size;
1287         
1288         bufmin = buf->rect;
1289         tbuf = buf->rect;
1290         bufmax = buf->rect + size*size;
1291         tbuf+= amount*size+ amount;
1292         
1293         for(nr=1; nr<=size; nr++) {
1294                 
1295                 for(a=0; a<2; a++) {
1296                         for(b=0; b<nr; b++, distance++) {
1297                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1298                                         if(strict){
1299                                                 indexok =  indextest(handle, *tbuf - min+1);
1300                                                 if(indexok){
1301                                                         *dist= (short) sqrt( (float)distance   );
1302                                                         index = *tbuf - min+1;
1303                                                         goto exit; 
1304                                                 }                                               
1305                                         }
1306                                         else{
1307                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1308                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1309                                                 goto exit;
1310                                         }                       
1311                                 }
1312                                 
1313                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1314                                 
1315                                 if(tbuf<bufmin || tbuf>=bufmax) {
1316                                         goto exit;
1317                                 }
1318                         }
1319                         rc++;
1320                         rc &= 3;
1321                 }
1322         }
1323
1324 exit:
1325         IMB_freeImBuf(buf);
1326         return index;
1327 }
1328
1329
1330 /* ************************************************************* */
1331
1332 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1333 {
1334         RegionView3D *rv3d= ar->regiondata;
1335         BGpic *bgpic;
1336         Image *ima;
1337         ImBuf *ibuf= NULL;
1338         float vec[4], fac, asp, zoomx, zoomy;
1339         float x1, y1, x2, y2, cx, cy;
1340         
1341         bgpic= v3d->bgpic;
1342         if(bgpic==NULL) return;
1343         
1344         ima= bgpic->ima;
1345         
1346         if(ima)
1347                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1348         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) ) 
1349                 return;
1350         if(ibuf->channels!=4)
1351                 return;
1352         if(ibuf->rect==NULL)
1353                 IMB_rect_from_float(ibuf);
1354         
1355         if(rv3d->persp==2) {
1356                 rctf vb;
1357                 
1358                 calc_viewborder(scene, ar, v3d, &vb);
1359                 
1360                 x1= vb.xmin;
1361                 y1= vb.ymin;
1362                 x2= vb.xmax;
1363                 y2= vb.ymax;
1364         }
1365         else {
1366                 float sco[2];
1367                 
1368                 /* calc window coord */
1369                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1370                 window_to_3d_delta(ar, vec, 1, 0);
1371                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1372                 fac= 1.0/fac;
1373                 
1374                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1375                 
1376                 vec[0] = vec[1] = vec[2] = 0.0;
1377                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1378                 cx = sco[0];
1379                 cy = sco[1];
1380                 
1381                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1382                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1383                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1384                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1385         }
1386         
1387         /* complete clip? */
1388         
1389         if(x2 < 0 ) return;
1390         if(y2 < 0 ) return;
1391         if(x1 > ar->winx ) return;
1392         if(y1 > ar->winy ) return;
1393         
1394         zoomx= (x2-x1)/ibuf->x;
1395         zoomy= (y2-y1)/ibuf->y;
1396         
1397         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1398         if(zoomx < 1.0f || zoomy < 1.0f) {
1399                 float tzoom= MIN2(zoomx, zoomy);
1400                 int mip= 0;
1401                 
1402                 if(ibuf->mipmap[0]==NULL)
1403                         IMB_makemipmap(ibuf, 0, 0);
1404                 
1405                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1406                         tzoom*= 2.0f;
1407                         zoomx*= 2.0f;
1408                         zoomy*= 2.0f;
1409                         mip++;
1410                 }
1411                 if(mip>0)
1412                         ibuf= ibuf->mipmap[mip-1];
1413         }
1414         
1415         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1416         glDepthMask(0);
1417         
1418         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
1419         
1420         /* need to use wm push/pop matrix because ED_region_pixelspace
1421            uses the wm functions too, otherwise gets out of sync */
1422         wmPushMatrix();
1423         ED_region_pixelspace(ar);
1424         
1425         glEnable(GL_BLEND);
1426         
1427         glPixelZoom(zoomx, zoomy);
1428         glColor4f(1.0, 1.0, 1.0, 1.0-bgpic->blend);
1429         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1430         
1431         glPixelZoom(1.0, 1.0);
1432         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1433         
1434         wmPopMatrix();
1435         
1436         glDisable(GL_BLEND);
1437
1438         glDepthMask(1);
1439         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1440 }
1441
1442 /* ****************** View3d afterdraw *************** */
1443
1444 typedef struct View3DAfter {
1445         struct View3DAfter *next, *prev;
1446         struct Base *base;
1447         int type, flag;
1448 } View3DAfter;
1449
1450 /* temp storage of Objects that need to be drawn as last */
1451 void add_view3d_after(View3D *v3d, Base *base, int type, int flag)
1452 {
1453         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1454         
1455         BLI_addtail(&v3d->afterdraw, v3da);
1456         v3da->base= base;
1457         v3da->type= type;
1458         v3da->flag= flag;
1459 }
1460
1461 /* clears zbuffer and draws it over */
1462 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1463 {
1464         View3DAfter *v3da, *next;
1465         int doit= 0;
1466         
1467         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
1468                 if(v3da->type==V3D_XRAY) doit= 1;
1469         
1470         if(doit) {
1471                 if(clear && v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
1472                 v3d->xray= TRUE;
1473                 
1474                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1475                         next= v3da->next;
1476                         if(v3da->type==V3D_XRAY) {
1477                                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1478                                 BLI_remlink(&v3d->afterdraw, v3da);
1479                                 MEM_freeN(v3da);
1480                         }
1481                 }
1482                 v3d->xray= FALSE;
1483         }
1484 }
1485
1486 /* disables write in zbuffer and draws it over */
1487 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1488 {
1489         View3DAfter *v3da, *next;
1490         
1491         glDepthMask(0);
1492         v3d->transp= TRUE;
1493         
1494         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1495                 next= v3da->next;
1496                 if(v3da->type==V3D_TRANSP) {
1497                         draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1498                         BLI_remlink(&v3d->afterdraw, v3da);
1499                         MEM_freeN(v3da);
1500                 }
1501         }
1502         v3d->transp= FALSE;
1503         
1504         glDepthMask(1);
1505         
1506 }
1507
1508 /* *********************** */
1509
1510 /*
1511         In most cases call draw_dupli_objects,
1512         draw_dupli_objects_color was added because when drawing set dupli's
1513         we need to force the color
1514  */
1515 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1516 {       
1517         RegionView3D *rv3d= ar->regiondata;
1518         ListBase *lb;
1519         DupliObject *dob;
1520         Base tbase;
1521         BoundBox *bb= NULL;
1522         GLuint displist=0;
1523         short transflag, use_displist= -1;      /* -1 is initialize */
1524         char dt, dtx;
1525         
1526         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1527         
1528         tbase.flag= OB_FROMDUPLI|base->flag;
1529         lb= object_duplilist(scene, base->object);
1530         
1531         for(dob= lb->first; dob; dob= dob->next) {
1532                 if(dob->no_draw);
1533                 else {
1534                         tbase.object= dob->ob;
1535                         
1536                         /* extra service: draw the duplicator in drawtype of parent */
1537                         /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1538                         dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1539                         dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1540                         
1541                         /* negative scale flag has to propagate */
1542                         transflag= tbase.object->transflag;
1543                         if(base->object->transflag & OB_NEG_SCALE)
1544                                 tbase.object->transflag ^= OB_NEG_SCALE;
1545                         
1546                         UI_ThemeColorBlend(color, TH_BACK, 0.5);
1547                         
1548                         /* generate displist, test for new object */
1549                         if(use_displist==1 && dob->prev && dob->prev->ob!=dob->ob) {
1550                                 use_displist= -1;
1551                                 glDeleteLists(displist, 1);
1552                         }
1553                         /* generate displist */
1554                         if(use_displist == -1) {
1555                                 
1556                                 /* lamp drawing messes with matrices, could be handled smarter... but this works */
1557                                 if(dob->ob->type==OB_LAMP || dob->type==OB_DUPLIGROUP)
1558                                         use_displist= 0;
1559                                 else {
1560                                         /* disable boundbox check for list creation */
1561                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1562                                         /* need this for next part of code */
1563                                         bb= object_get_boundbox(dob->ob);
1564                                         
1565                                         Mat4One(dob->ob->obmat);        /* obmat gets restored */
1566                                         
1567                                         displist= glGenLists(1);
1568                                         glNewList(displist, GL_COMPILE);
1569                                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1570                                         glEndList();
1571                                         
1572                                         use_displist= 1;
1573                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1574                                 }
1575                         }
1576                         if(use_displist) {
1577                                 wmMultMatrix(dob->mat);
1578                                 if(boundbox_clip(rv3d, dob->mat, bb))
1579                                         glCallList(displist);
1580                                 wmLoadMatrix(rv3d->viewmat);
1581                         }
1582                         else {
1583                                 Mat4CpyMat4(dob->ob->obmat, dob->mat);
1584                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1585                         }
1586                         
1587                         tbase.object->dt= dt;
1588                         tbase.object->dtx= dtx;
1589                         tbase.object->transflag= transflag;
1590                 }
1591         }
1592         
1593         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1594         
1595         free_object_duplilist(lb);      /* does restore */
1596         
1597         if(use_displist)
1598                 glDeleteLists(displist, 1);
1599 }
1600
1601 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1602 {
1603         /* define the color here so draw_dupli_objects_color can be called
1604         * from the set loop */
1605         
1606         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1607         /* debug */
1608         if(base->object->dup_group && base->object->dup_group->id.us<1)
1609                 color= TH_REDALERT;
1610         
1611         draw_dupli_objects_color(scene, ar, v3d, base, color);
1612 }
1613
1614
1615 void view3d_update_depths(ARegion *ar, View3D *v3d)
1616 {
1617         RegionView3D *rv3d= ar->regiondata;
1618         
1619         /* Create storage for, and, if necessary, copy depth buffer */
1620         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1621         if(rv3d->depths) {
1622                 ViewDepths *d= rv3d->depths;
1623                 if(d->w != ar->winx ||
1624                    d->h != ar->winy ||
1625                    !d->depths) {
1626                         d->w= ar->winx;
1627                         d->h= ar->winy;
1628                         if(d->depths)
1629                                 MEM_freeN(d->depths);
1630                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1631                         d->damaged= 1;
1632                 }
1633                 
1634                 if(d->damaged) {
1635                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1636                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1637                         
1638                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1639                         
1640                         d->damaged= 0;
1641                 }
1642         }
1643 }
1644
1645 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1646 {
1647         RegionView3D *rv3d= ar->regiondata;
1648         Base *base;
1649         Scene *sce;
1650         short zbuf, flag;
1651         float glalphaclip;
1652         /* temp set drawtype to solid */
1653         
1654         /* Setting these temporarily is not nice */
1655         zbuf = v3d->zbuf;
1656         flag = v3d->flag;
1657         glalphaclip = U.glalphaclip;
1658         
1659         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1660         v3d->flag &= ~V3D_SELECT_OUTLINE;
1661         
1662         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1663         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1664         
1665         Mat4MulMat4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1666         Mat4Invert(rv3d->persinv, rv3d->persmat);
1667         Mat4Invert(rv3d->viewinv, rv3d->viewmat);
1668         
1669         glClear(GL_DEPTH_BUFFER_BIT);
1670         
1671         wmLoadMatrix(rv3d->viewmat);
1672 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1673         
1674         if(rv3d->rflag & RV3D_CLIPPING) {
1675                 view3d_set_clipping(rv3d);
1676         }
1677         
1678         v3d->zbuf= TRUE;
1679         glEnable(GL_DEPTH_TEST);
1680         
1681         /* draw set first */
1682         if(scene->set) {
1683                 for(SETLOOPER(scene->set, base)) {
1684                         if(v3d->lay & base->lay) {
1685                                 if (func == NULL || func(base)) {
1686                                         draw_object(scene, ar, v3d, base, 0);
1687                                         if(base->object->transflag & OB_DUPLI) {
1688                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1689                                         }
1690                                 }
1691                         }
1692                 }
1693         }
1694         
1695         for(base= scene->base.first; base; base= base->next) {
1696                 if(v3d->lay & base->lay) {
1697                         if (func == NULL || func(base)) {
1698                                 /* dupli drawing */
1699                                 if(base->object->transflag & OB_DUPLI) {
1700                                         draw_dupli_objects(scene, ar, v3d, base);
1701                                 }
1702                                 draw_object(scene, ar, v3d, base, 0);
1703                         }
1704                 }
1705         }
1706         
1707         /* this isnt that nice, draw xray objects as if they are normal */
1708         if (v3d->afterdraw.first) {
1709                 View3DAfter *v3da, *next;
1710                 int num = 0;
1711                 v3d->xray= TRUE;
1712                 
1713                 glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1714                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1715                         next= v3da->next;
1716                         if(v3da->type==V3D_XRAY) {
1717                                 draw_object(scene, ar, v3d, v3da->base, 0);
1718                                 num++;
1719                         }
1720                         /* dont remove this time */
1721                 }
1722                 v3d->xray= FALSE;
1723                 
1724                 glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1725                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1726                         next= v3da->next;
1727                         if(v3da->type==V3D_XRAY) {
1728                                 v3d->xray= TRUE; v3d->transp= FALSE;  
1729                         } else if (v3da->type==V3D_TRANSP) {
1730                                 v3d->xray= FALSE; v3d->transp= TRUE;
1731                         }
1732                         
1733                         draw_object(scene, ar, v3d, v3da->base, 0); /* Draw Xray or Transp objects normally */
1734                         BLI_remlink(&v3d->afterdraw, v3da);
1735                         MEM_freeN(v3da);
1736                 }
1737                 v3d->xray= FALSE;
1738                 v3d->transp= FALSE;
1739         }
1740         
1741         v3d->zbuf = zbuf;
1742         U.glalphaclip = glalphaclip;
1743         v3d->flag = flag;
1744 }
1745
1746 typedef struct View3DShadow {
1747         struct View3DShadow *next, *prev;
1748         GPULamp *lamp;
1749 } View3DShadow;
1750
1751 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1752 {
1753         GPULamp *lamp;
1754         Lamp *la = (Lamp*)ob->data;
1755         View3DShadow *shadow;
1756         
1757         lamp = GPU_lamp_from_blender(scene, ob, par);
1758         
1759         if(lamp) {
1760                 GPU_lamp_update(lamp, ob->lay, obmat);
1761                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1762                 
1763                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1764                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1765                         shadow->lamp = lamp;
1766                         BLI_addtail(shadows, shadow);
1767                 }
1768         }
1769 }
1770
1771 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1772 {
1773         ListBase shadows;
1774         View3DShadow *shadow;
1775         Scene *sce;
1776         Base *base;
1777         Object *ob;
1778         
1779         shadows.first= shadows.last= NULL;
1780         
1781         /* update lamp transform and gather shadow lamps */
1782         for(SETLOOPER(scene, base)) {
1783                 ob= base->object;
1784                 
1785                 if(ob->type == OB_LAMP)
1786                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
1787                 
1788                 if (ob->transflag & OB_DUPLI) {
1789                         DupliObject *dob;
1790                         ListBase *lb = object_duplilist(scene, ob);
1791                         
1792                         for(dob=lb->first; dob; dob=dob->next)
1793                                 if(dob->ob->type==OB_LAMP)
1794                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
1795                         
1796                         free_object_duplilist(lb);
1797                 }
1798         }
1799         
1800         /* render shadows after updating all lamps, nested object_duplilist
1801                 * don't work correct since it's replacing object matrices */
1802         for(shadow=shadows.first; shadow; shadow=shadow->next) {
1803                 /* this needs to be done better .. */
1804                 float viewmat[4][4], winmat[4][4];
1805                 int drawtype, lay, winsize, flag2;
1806                 
1807                 drawtype= v3d->drawtype;
1808                 lay= v3d->lay;
1809                 flag2= v3d->flag2 & V3D_SOLID_TEX;
1810                 
1811                 v3d->drawtype = OB_SOLID;
1812                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1813                 v3d->flag2 &= ~V3D_SOLID_TEX;
1814                 
1815                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1816 // XXX          drawview3d_render(v3d, viewmat, winsize, winsize, winmat, 1);
1817                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1818                 
1819                 v3d->drawtype= drawtype;
1820                 v3d->lay= lay;
1821                 v3d->flag2 |= flag2;
1822         }
1823         
1824         BLI_freelistN(&shadows);
1825 }
1826
1827 /* *********************** customdata **************** */
1828
1829 /* goes over all modes and view3d settings */
1830 static CustomDataMask get_viewedit_datamask(bScreen *screen, Scene *scene, Object *ob)
1831 {
1832         CustomDataMask mask = CD_MASK_BAREMESH;
1833         ScrArea *sa;
1834         
1835         /* check if we need tfaces & mcols due to face select or texture paint */
1836         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
1837                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1838         
1839         /* check if we need tfaces & mcols due to view mode */
1840         for(sa = screen->areabase.first; sa; sa = sa->next) {
1841                 if(sa->spacetype == SPACE_VIEW3D) {
1842                         View3D *view = sa->spacedata.first;
1843                         if(view->drawtype == OB_SHADED) {
1844                                 /* this includes normals for mesh_create_shadedColors */
1845                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
1846                         }
1847                         if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
1848                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1849                                 
1850                                 if(scene->gm.matmode == GAME_MAT_GLSL)
1851                                         mask |= CD_MASK_ORCO;
1852                         }
1853                 }
1854         }
1855         
1856         /* check if we need mcols due to vertex paint or weightpaint */
1857         if(ob) {
1858                 if(ob->mode & OB_MODE_VERTEX_PAINT)
1859                         mask |= CD_MASK_MCOL;
1860                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
1861                         mask |= CD_MASK_WEIGHT_MCOL;
1862                 //if(ob->mode & OB_MODE_SCULPT)
1863                 //      mask |= CD_MASK_MDISPS;
1864         }
1865
1866         return mask;
1867 }
1868
1869 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
1870 {
1871         RegionView3D *rv3d= ar->regiondata;
1872
1873         /* setup window matrices */
1874         if(winmat)
1875                 Mat4CpyMat4(rv3d->winmat, winmat);
1876         else
1877                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
1878         
1879         /* setup view matrix */
1880         if(viewmat)
1881                 Mat4CpyMat4(rv3d->viewmat, viewmat);
1882         else
1883                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1884         
1885         /* update utilitity matrices */
1886         Mat4MulMat4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1887         Mat4Invert(rv3d->persinv, rv3d->persmat);
1888         Mat4Invert(rv3d->viewinv, rv3d->viewmat);
1889         
1890         /* calculate pixelsize factor once, is used for lamps and obcenters */
1891         {
1892                 float len1, len2, vec[3];
1893                 
1894                 VECCOPY(vec, rv3d->persinv[0]);
1895                 len1= Normalize(vec);
1896                 VECCOPY(vec, rv3d->persinv[1]);
1897                 len2= Normalize(vec);
1898                 
1899                 rv3d->pixsize= 2.0f*(len1>len2?len1:len2);
1900                 
1901                 /* correct for window size */
1902                 if(ar->winx > ar->winy) rv3d->pixsize/= (float)ar->winx;
1903                 else rv3d->pixsize/= (float)ar->winy;
1904         }
1905         
1906         /* set for opengl */
1907         glMatrixMode(GL_PROJECTION);
1908         wmLoadMatrix(rv3d->winmat);
1909
1910         glMatrixMode(GL_MODELVIEW);
1911         wmLoadMatrix(rv3d->viewmat);
1912 }
1913
1914 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
1915 {
1916         Scene *sce;
1917         Base *base;
1918         int bwinx, bwiny;
1919
1920         wmPushMatrix();
1921
1922         /* set temporary new size */
1923         bwinx= ar->winx;
1924         bwiny= ar->winy;
1925         ar->winx= winx;
1926         ar->winy= winy;
1927
1928         /* set flags */
1929         G.f |= G_RENDER_OGL;
1930         GPU_free_images();
1931
1932         /* set background color */
1933         glClearColor(scene->world->horr, scene->world->horg, scene->world->horb, 0.0);
1934         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1935
1936         /* setup view matrices */
1937         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
1938
1939         /* set zbuffer */
1940         if(v3d->drawtype > OB_WIRE) {
1941                 v3d->zbuf= TRUE;
1942                 glEnable(GL_DEPTH_TEST);
1943         }
1944         else
1945                 v3d->zbuf= FALSE;
1946
1947         /* draw set first */
1948         if(scene->set) {
1949                 for(SETLOOPER(scene->set, base)) {
1950                         if(v3d->lay & base->lay) {
1951                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1952                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
1953                                 
1954                                 if(base->object->transflag & OB_DUPLI)
1955                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1956                         }
1957                 }
1958         }
1959         
1960         /* then draw not selected and the duplis, but skip editmode object */
1961         for(base= scene->base.first; base; base= base->next) {
1962                 if(v3d->lay & base->lay) {
1963                         /* dupli drawing */
1964                         if(base->object->transflag & OB_DUPLI)
1965                                 draw_dupli_objects(scene, ar, v3d, base);
1966
1967                         draw_object(scene, ar, v3d, base, 0);
1968                 }
1969         }
1970
1971         /* transp and X-ray afterdraw stuff */
1972         view3d_draw_transp(scene, ar, v3d);
1973         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
1974
1975         /* cleanup */
1976         if(v3d->zbuf) {
1977                 v3d->zbuf= FALSE;
1978                 glDisable(GL_DEPTH_TEST);
1979         }
1980
1981         GPU_free_images();
1982
1983         /* restore size */
1984         ar->winx= bwinx;
1985         ar->winy= bwiny;
1986
1987         wmPopMatrix();
1988 }
1989
1990 void view3d_main_area_draw(const bContext *C, ARegion *ar)
1991 {
1992         Scene *scene= CTX_data_scene(C);
1993         View3D *v3d = CTX_wm_view3d(C);
1994         RegionView3D *rv3d= CTX_wm_region_view3d(C);
1995         Scene *sce;
1996         Base *base;
1997         Object *ob;
1998         float col[3];
1999         int retopo= 0, sculptparticle= 0;
2000         Object *obact = OBACT;
2001         char *grid_unit= NULL;
2002         
2003         /* from now on all object derived meshes check this */
2004         v3d->customdata_mask= get_viewedit_datamask(CTX_wm_screen(C), scene, obact);
2005         
2006         /* shadow buffers, before we setup matrices */
2007         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2008                 gpu_update_lamps_shadows(scene, v3d);
2009
2010         /* clear background */
2011         UI_GetThemeColor3fv(TH_BACK, col);
2012         glClearColor(col[0], col[1], col[2], 0.0); 
2013         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2014         
2015         /* setup view matrices */
2016         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2017
2018         if(rv3d->rflag & RV3D_CLIPPING)
2019                 view3d_draw_clipping(rv3d);
2020         
2021         /* set zbuffer after we draw clipping region */
2022         if(v3d->drawtype > OB_WIRE) {
2023                 v3d->zbuf= TRUE;
2024                 glEnable(GL_DEPTH_TEST);
2025         }
2026         else
2027                 v3d->zbuf= FALSE;
2028         
2029         // needs to be done always, gridview is adjusted in drawgrid() now
2030         v3d->gridview= v3d->grid;
2031         
2032         if(rv3d->view==0 || rv3d->persp!=0) {
2033                 drawfloor(scene, v3d);
2034                 if(rv3d->persp==2) {
2035                         if(scene->world) {
2036                                 if(scene->world->mode & WO_STARS) {
2037                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2038                                                                   star_stuff_term_func);
2039                                 }
2040                         }
2041                         if(v3d->flag & V3D_DISPBGPIC) draw_bgpic(scene, ar, v3d);
2042                 }
2043         }
2044         else {
2045                 ED_region_pixelspace(ar);
2046                 drawgrid(&scene->unit, ar, v3d, &grid_unit);
2047                 /* XXX make function? replaces persp(1) */
2048                 glMatrixMode(GL_PROJECTION);
2049                 wmLoadMatrix(rv3d->winmat);
2050                 glMatrixMode(GL_MODELVIEW);
2051                 wmLoadMatrix(rv3d->viewmat);
2052                 
2053                 if(v3d->flag & V3D_DISPBGPIC) {
2054                         draw_bgpic(scene, ar, v3d);
2055                 }
2056         }
2057         
2058         if(rv3d->rflag & RV3D_CLIPPING)
2059                 view3d_set_clipping(rv3d);
2060         
2061         /* draw set first */
2062         if(scene->set) {
2063                 for(SETLOOPER(scene->set, base)) {
2064                         
2065                         if(v3d->lay & base->lay) {
2066                                 
2067                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2068                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2069                                 
2070                                 if(base->object->transflag & OB_DUPLI) {
2071                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2072                                 }
2073                         }
2074                 }
2075                 
2076                 /* Transp and X-ray afterdraw stuff for sets is done later */
2077         }
2078         
2079         /* extra service in layerbuttons, showing used layers */
2080         v3d->lay_used = 0;
2081         
2082         /* then draw not selected and the duplis, but skip editmode object */
2083         for(base= scene->base.first; base; base= base->next) {
2084                 v3d->lay_used |= base->lay;
2085                 
2086                 if(v3d->lay & base->lay) {
2087                         
2088                         /* dupli drawing */
2089                         if(base->object->transflag & OB_DUPLI) {
2090                                 draw_dupli_objects(scene, ar, v3d, base);
2091                         }
2092                         if((base->flag & SELECT)==0) {
2093                                 if(base->object!=scene->obedit) 
2094                                         draw_object(scene, ar, v3d, base, 0);
2095                         }
2096                 }
2097         }
2098
2099 //      retopo= retopo_mesh_check() || retopo_curve_check();
2100         sculptparticle= (obact && obact->mode & (OB_MODE_PARTICLE_EDIT)) && !scene->obedit;
2101         if(retopo)
2102                 view3d_update_depths(ar, v3d);
2103         
2104         /* draw selected and editmode */
2105         for(base= scene->base.first; base; base= base->next) {
2106                 if(v3d->lay & base->lay) {
2107                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2108                                 draw_object(scene, ar, v3d, base, 0);
2109                 }
2110         }
2111         
2112         if(!retopo && sculptparticle && !(obact && (obact->dtx & OB_DRAWXRAY))) {
2113                 view3d_update_depths(ar, v3d);
2114         }
2115         
2116         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2117         
2118 //      REEB_draw();
2119         
2120 //      if(scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
2121         
2122         /* Transp and X-ray afterdraw stuff */
2123         view3d_draw_transp(scene, ar, v3d);
2124         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2125         
2126         if(!retopo && sculptparticle && (obact && (OBACT->dtx & OB_DRAWXRAY))) {
2127                 view3d_update_depths(ar, v3d);
2128         }
2129         
2130         if(rv3d->rflag & RV3D_CLIPPING)
2131                 view3d_clr_clipping();
2132         
2133         BIF_draw_manipulator(C);
2134         
2135         if(v3d->zbuf) {
2136                 v3d->zbuf= FALSE;
2137                 glDisable(GL_DEPTH_TEST);
2138         }
2139         
2140         /* draw grease-pencil stuff */
2141         //if (v3d->flag2 & V3D_DISPGP)
2142                 draw_gpencil_3dview((bContext *)C, 1);
2143         
2144         BDR_drawSketch(C);
2145         
2146         ED_region_pixelspace(ar);
2147         
2148 //      retopo_paint_view_update(v3d);
2149 //      retopo_draw_paint_lines();
2150         
2151         /* Draw particle edit brush XXX (removed) */
2152         
2153         if(rv3d->persp>1) drawviewborder(scene, ar, v3d);
2154         if(rv3d->rflag & RV3D_FLYMODE) drawviewborder_flymode(ar);
2155         
2156         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2157 //      if (v3d->flag2 & V3D_DISPGP)
2158                 draw_gpencil_3dview((bContext *)C, 0);
2159
2160         drawcursor(scene, ar, v3d);
2161         
2162         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2163                 draw_view_axis(rv3d);
2164         else    
2165                 draw_view_icon(rv3d);
2166         
2167         /* XXX removed viewport fps */
2168         if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2169                 draw_viewport_name(ar, v3d);
2170         }
2171         if (grid_unit) { /* draw below the viewport name */
2172                 UI_ThemeColor(TH_TEXT_HI);
2173                 BLF_draw_default(10,  ar->winy-(USER_SHOW_VIEWPORTNAME?40:20), 0.0f, grid_unit);
2174         }
2175
2176         ob= OBACT;
2177         if(U.uiflag & USER_DRAWVIEWINFO) 
2178                 draw_selected_name(scene, ob, v3d);
2179
2180         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_PIXEL);
2181         
2182         /* XXX here was the blockhandlers for floating panels */
2183
2184         if(ob && ob->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT|OB_MODE_TEXTURE_PAINT)) {
2185                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2186                 // XXX addafterqueue(ar->win, BACKBUFDRAW, 1);
2187         }
2188
2189         if((ob && ob->mode & OB_MODE_PARTICLE_EDIT) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
2190                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2191                 // XXX addafterqueue(ar->win, BACKBUFDRAW, 1);
2192         }
2193
2194         // test for backbuf select
2195         if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
2196                 
2197                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
2198                 // XXX if(afterqtest(ar->win, BACKBUFDRAW)==0) {
2199                 //      addafterqueue(ar->win, BACKBUFDRAW, 1);
2200                 //}
2201         }
2202 }
2203
2204