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