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