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