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