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