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