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