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