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