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