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