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