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