code cleanup: dont use function calls like dot_v3v3, pow and sqrt within macros which...
[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                                 /* TODO: skip drawing when out of frame range (as image sequences do above) */
1578
1579                                 if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
1580                                         if (scene->camera)
1581                                                 clip = BKE_object_movieclip_get(scene, scene->camera, 1);
1582                                 }
1583                                 else clip = bgpic->clip;
1584
1585                                 if (clip == NULL)
1586                                         continue;
1587
1588                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
1589                                 ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
1590
1591                                 image_aspect[0] = clip->aspx;
1592                                 image_aspect[1] = clip->aspx;
1593
1594                                 /* working with ibuf from image and clip has got different workflow now.
1595                                  * ibuf acquired from clip is referenced by cache system and should
1596                                  * be dereferenced after usage. */
1597                                 freeibuf = ibuf;
1598                         }
1599                         else {
1600                                 /* perhaps when loading future files... */
1601                                 BLI_assert(0);
1602                                 copy_v2_fl(image_aspect, 1.0f);
1603                         }
1604
1605                         if (ibuf == NULL)
1606                                 continue;
1607
1608                         if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
1609                                 if (freeibuf)
1610                                         IMB_freeImBuf(freeibuf);
1611
1612                                 continue;
1613                         }
1614
1615                         if (ibuf->rect == NULL)
1616                                 IMB_rect_from_float(ibuf);
1617
1618                         if (rv3d->persp == RV3D_CAMOB) {
1619
1620                                 if (do_camera_frame) {
1621                                         rctf vb;
1622                                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, FALSE);
1623                                         x1 = vb.xmin;
1624                                         y1 = vb.ymin;
1625                                         x2 = vb.xmax;
1626                                         y2 = vb.ymax;
1627                                 }
1628                                 else {
1629                                         x1 = ar->winrct.xmin;
1630                                         y1 = ar->winrct.ymin;
1631                                         x2 = ar->winrct.xmax;
1632                                         y2 = ar->winrct.ymax;
1633                                 }
1634
1635                                 /* apply offset last - camera offset is different to offset in blender units */
1636                                 /* so this has some sane way of working - this matches camera's shift _exactly_ */
1637                                 {
1638                                         const float max_dim = maxf(x2 - x1, y2 - y1);
1639                                         const float xof_scale = bgpic->xof * max_dim;
1640                                         const float yof_scale = bgpic->yof * max_dim;
1641
1642                                         x1 += xof_scale;
1643                                         y1 += yof_scale;
1644                                         x2 += xof_scale;
1645                                         y2 += yof_scale;
1646                                 }
1647
1648                                 /* aspect correction */
1649                                 if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
1650                                         /* apply aspect from clip */
1651                                         const float w_src = ibuf->x * image_aspect[0];
1652                                         const float h_src = ibuf->y * image_aspect[1];
1653
1654                                         /* destination aspect is already applied from the camera frame */
1655                                         const float w_dst = x1 - x2;
1656                                         const float h_dst = y1 - y2;
1657
1658                                         const float asp_src = w_src / h_src;
1659                                         const float asp_dst = w_dst / h_dst;
1660
1661                                         if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
1662                                                 if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
1663                                                         /* fit X */
1664                                                         const float div = asp_src / asp_dst;
1665                                                         const float cent = (x1 + x2) / 2.0f;
1666                                                         x1 = ((x1 - cent) * div) + cent;
1667                                                         x2 = ((x2 - cent) * div) + cent;
1668                                                 }
1669                                                 else {
1670                                                         /* fit Y */
1671                                                         const float div = asp_dst / asp_src;
1672                                                         const float cent = (y1 + y2) / 2.0f;
1673                                                         y1 = ((y1 - cent) * div) + cent;
1674                                                         y2 = ((y2 - cent) * div) + cent;
1675                                                 }
1676                                         }
1677                                 }
1678                         }
1679                         else {
1680                                 float sco[2];
1681                                 const float mval_f[2] = {1.0f, 0.0f};
1682
1683                                 /* calc window coord */
1684                                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1685                                 ED_view3d_win_to_delta(ar, mval_f, vec);
1686                                 fac = maxf(fabsf(vec[0]), maxf(fabsf(vec[1]), fabsf(vec[2]))); /* largest abs axis */
1687                                 fac = 1.0f / fac;
1688
1689                                 asp = ( (float)ibuf->y) / (float)ibuf->x;
1690
1691                                 zero_v3(vec);
1692                                 ED_view3d_project_float_v2(ar, vec, sco, rv3d->persmat);
1693                                 cx = sco[0];
1694                                 cy = sco[1];
1695
1696                                 x1 =  cx + fac * (bgpic->xof - bgpic->size);
1697                                 y1 =  cy + asp * fac * (bgpic->yof - bgpic->size);
1698                                 x2 =  cx + fac * (bgpic->xof + bgpic->size);
1699                                 y2 =  cy + asp * fac * (bgpic->yof + bgpic->size);
1700                         }
1701
1702                         /* complete clip? */
1703
1704                         if (x2 < 0 || y2 < 0 || x1 > ar->winx || y1 > ar->winy) {
1705                                 if (freeibuf)
1706                                         IMB_freeImBuf(freeibuf);
1707
1708                                 continue;
1709                         }
1710
1711                         zoomx = (x2 - x1) / ibuf->x;
1712                         zoomy = (y2 - y1) / ibuf->y;
1713
1714                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1715                         if (zoomx < 1.0f || zoomy < 1.0f) {
1716                                 float tzoom = MIN2(zoomx, zoomy);
1717                                 int mip = 0;
1718
1719                                 if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
1720                                         IMB_remakemipmap(ibuf, 0);
1721                                         ibuf->userflags &= ~IB_MIPMAP_INVALID;
1722                                 }
1723                                 else if (ibuf->mipmap[0] == NULL)
1724                                         IMB_makemipmap(ibuf, 0);
1725
1726                                 while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
1727                                         tzoom *= 2.0f;
1728                                         zoomx *= 2.0f;
1729                                         zoomy *= 2.0f;
1730                                         mip++;
1731                                 }
1732                                 if (mip > 0)
1733                                         ibuf = ibuf->mipmap[mip - 1];
1734                         }
1735
1736                         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1737                         glDepthMask(0);
1738
1739                         glEnable(GL_BLEND);
1740                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1741
1742                         glMatrixMode(GL_PROJECTION);
1743                         glPushMatrix();
1744                         glMatrixMode(GL_MODELVIEW);
1745                         glPushMatrix();
1746                         ED_region_pixelspace(ar);
1747
1748                         glPixelZoom(zoomx, zoomy);
1749                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
1750                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1751
1752                         glPixelZoom(1.0, 1.0);
1753                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1754
1755                         glMatrixMode(GL_PROJECTION);
1756                         glPopMatrix();
1757                         glMatrixMode(GL_MODELVIEW);
1758                         glPopMatrix();
1759
1760                         glDisable(GL_BLEND);
1761
1762                         glDepthMask(1);
1763                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1764
1765                         if (freeibuf)
1766                                 IMB_freeImBuf(freeibuf);
1767                 }
1768         }
1769 }
1770
1771 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
1772                                    const short do_forground, const short do_camera_frame)
1773 {
1774         RegionView3D *rv3d = ar->regiondata;
1775
1776         if ((v3d->flag & V3D_DISPBGPICS) == 0)
1777                 return;
1778
1779         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
1780                 return;
1781
1782         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
1783                 if (rv3d->persp == RV3D_CAMOB) {
1784                         view3d_draw_bgpic(scene, ar, v3d, do_forground, do_camera_frame);
1785                 }
1786         }
1787         else {
1788                 view3d_draw_bgpic(scene, ar, v3d, do_forground, do_camera_frame);
1789         }
1790 }
1791
1792 /* ****************** View3d afterdraw *************** */
1793
1794 typedef struct View3DAfter {
1795         struct View3DAfter *next, *prev;
1796         struct Base *base;
1797         short dflag;
1798 } View3DAfter;
1799
1800 /* temp storage of Objects that need to be drawn as last */
1801 void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
1802 {
1803         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
1804         BLI_assert((base->flag & OB_FROMDUPLI) == 0);
1805         BLI_addtail(lb, v3da);
1806         v3da->base = base;
1807         v3da->dflag = dflag;
1808 }
1809
1810 /* disables write in zbuffer and draws it over */
1811 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1812 {
1813         View3DAfter *v3da, *next;
1814         
1815         glDepthMask(0);
1816         v3d->transp = TRUE;
1817         
1818         for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
1819                 next = v3da->next;
1820                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1821                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1822                 MEM_freeN(v3da);
1823         }
1824         v3d->transp = FALSE;
1825         
1826         glDepthMask(1);
1827         
1828 }
1829
1830 /* clears zbuffer and draws it over */
1831 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1832 {
1833         View3DAfter *v3da, *next;
1834
1835         if (clear && v3d->zbuf)
1836                 glClear(GL_DEPTH_BUFFER_BIT);
1837
1838         v3d->xray = TRUE;
1839         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
1840                 next = v3da->next;
1841                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1842                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1843                 MEM_freeN(v3da);
1844         }
1845         v3d->xray = FALSE;
1846 }
1847
1848
1849 /* clears zbuffer and draws it over */
1850 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1851 {
1852         View3DAfter *v3da, *next;
1853
1854         if (clear && v3d->zbuf)
1855                 glClear(GL_DEPTH_BUFFER_BIT);
1856
1857         v3d->xray = TRUE;
1858         v3d->transp = TRUE;
1859         
1860         for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
1861                 next = v3da->next;
1862                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1863                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1864                 MEM_freeN(v3da);
1865         }
1866
1867         v3d->transp = FALSE;
1868         v3d->xray = FALSE;
1869
1870 }
1871
1872 /* *********************** */
1873
1874 /*
1875  * In most cases call draw_dupli_objects,
1876  * draw_dupli_objects_color was added because when drawing set dupli's
1877  * we need to force the color
1878  */
1879
1880 #if 0
1881 int dupli_ob_sort(void *arg1, void *arg2)
1882 {
1883         void *p1 = ((DupliObject *)arg1)->ob;
1884         void *p2 = ((DupliObject *)arg2)->ob;
1885         int val = 0;
1886         if (p1 < p2) val = -1;
1887         else if (p1 > p2) val = 1;
1888         return val;
1889 }
1890 #endif
1891
1892
1893 static DupliObject *dupli_step(DupliObject *dob)
1894 {
1895         while (dob && dob->no_draw)
1896                 dob = dob->next;
1897         return dob;
1898 }
1899
1900 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1901 {
1902         RegionView3D *rv3d = ar->regiondata;
1903         ListBase *lb;
1904         DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
1905         Base tbase = {NULL};
1906         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1907         GLuint displist = 0;
1908         short transflag, use_displist = -1;  /* -1 is initialize */
1909         char dt, dtx;
1910         
1911         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1912         
1913         tbase.flag = OB_FROMDUPLI | base->flag;
1914         lb = object_duplilist(scene, base->object);
1915         // BLI_sortlist(lb, dupli_ob_sort); // might be nice to have if we have a dupli list with mixed objects.
1916
1917         dob = dupli_step(lb->first);
1918         if (dob) dob_next = dupli_step(dob->next);
1919
1920         for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1921                 tbase.object = dob->ob;
1922
1923                 /* extra service: draw the duplicator in drawtype of parent */
1924                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1925                 dt = tbase.object->dt;   tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1926                 dtx = tbase.object->dtx; tbase.object->dtx = base->object->dtx;
1927
1928                 /* negative scale flag has to propagate */
1929                 transflag = tbase.object->transflag;
1930                 if (base->object->transflag & OB_NEG_SCALE)
1931                         tbase.object->transflag ^= OB_NEG_SCALE;
1932
1933                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1934
1935                 /* generate displist, test for new object */
1936                 if (dob_prev && dob_prev->ob != dob->ob) {
1937                         if (use_displist == TRUE)
1938                                 glDeleteLists(displist, 1);
1939
1940                         use_displist = -1;
1941                 }
1942
1943                 /* generate displist */
1944                 if (use_displist == -1) {
1945
1946                         /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
1947                          * however this is very slow, it was probably needed for the NLA
1948                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1949                          * so for now it should be ok to - campbell */
1950
1951                         if ( /* if this is the last no need  to make a displist */
1952                             (dob_next == NULL || dob_next->ob != dob->ob) ||
1953                             /* lamp drawing messes with matrices, could be handled smarter... but this works */
1954                             (dob->ob->type == OB_LAMP) ||
1955                             (dob->type == OB_DUPLIGROUP && dob->animated) ||
1956                             !(bb_tmp = BKE_object_boundbox_get(dob->ob)))
1957                         {
1958                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1959                                 use_displist = FALSE;
1960                         }
1961                         else {
1962                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1963                                 bb = *bb_tmp; /* must make a copy  */
1964
1965                                 /* disable boundbox check for list creation */
1966                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1967                                 /* need this for next part of code */
1968                                 unit_m4(dob->ob->obmat);    /* obmat gets restored */
1969
1970                                 displist = glGenLists(1);
1971                                 glNewList(displist, GL_COMPILE);
1972                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1973                                 glEndList();
1974
1975                                 use_displist = TRUE;
1976                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1977                         }
1978                 }
1979                 if (use_displist) {
1980                         glMultMatrixf(dob->mat);
1981                         if (ED_view3d_boundbox_clip(rv3d, dob->mat, &bb))
1982                                 glCallList(displist);
1983                         glLoadMatrixf(rv3d->viewmat);
1984                 }
1985                 else {
1986                         copy_m4_m4(dob->ob->obmat, dob->mat);
1987                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1988                 }
1989
1990                 tbase.object->dt = dt;
1991                 tbase.object->dtx = dtx;
1992                 tbase.object->transflag = transflag;
1993         }
1994         
1995         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1996         
1997         free_object_duplilist(lb);  /* does restore */
1998         
1999         if (use_displist)
2000                 glDeleteLists(displist, 1);
2001 }
2002
2003 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
2004 {
2005         /* define the color here so draw_dupli_objects_color can be called
2006          * from the set loop */
2007         
2008         int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
2009         /* debug */
2010         if (base->object->dup_group && base->object->dup_group->id.us < 1)
2011                 color = TH_REDALERT;
2012         
2013         draw_dupli_objects_color(scene, ar, v3d, base, color);
2014 }
2015
2016 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
2017 {
2018         int x, y, w, h; 
2019         rcti r;
2020         /* clamp rect by area */
2021
2022         r.xmin = 0;
2023         r.xmax = ar->winx - 1;
2024         r.ymin = 0;
2025         r.ymax = ar->winy - 1;
2026
2027         /* Constrain rect to depth bounds */
2028         BLI_isect_rcti(&r, rect, rect);
2029
2030         /* assign values to compare with the ViewDepths */
2031         x = rect->xmin;
2032         y = rect->ymin;
2033
2034         w = rect->xmax - rect->xmin;
2035         h = rect->ymax - rect->ymin;
2036
2037         if (w <= 0 || h <= 0) {
2038                 if (d->depths)
2039                         MEM_freeN(d->depths);
2040                 d->depths = NULL;
2041
2042                 d->damaged = FALSE;
2043         }
2044         else if (d->w != w ||
2045                  d->h != h ||
2046                  d->x != x ||
2047                  d->y != y ||
2048                  d->depths == NULL
2049                  )
2050         {
2051                 d->x = x;
2052                 d->y = y;
2053                 d->w = w;
2054                 d->h = h;
2055
2056                 if (d->depths)
2057                         MEM_freeN(d->depths);
2058
2059                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
2060                 
2061                 d->damaged = TRUE;
2062         }
2063
2064         if (d->damaged) {
2065                 glReadPixels(ar->winrct.xmin + d->x, ar->winrct.ymin + d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2066                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2067                 d->damaged = FALSE;
2068         }
2069 }
2070
2071 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
2072 void ED_view3d_depth_update(ARegion *ar)
2073 {
2074         RegionView3D *rv3d = ar->regiondata;
2075         
2076         /* Create storage for, and, if necessary, copy depth buffer */
2077         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
2078         if (rv3d->depths) {
2079                 ViewDepths *d = rv3d->depths;
2080                 if (d->w != ar->winx ||
2081                     d->h != ar->winy ||
2082                     !d->depths)
2083                 {
2084                         d->w = ar->winx;
2085                         d->h = ar->winy;
2086                         if (d->depths)
2087                                 MEM_freeN(d->depths);
2088                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
2089                         d->damaged = 1;
2090                 }
2091                 
2092                 if (d->damaged) {
2093                         glReadPixels(ar->winrct.xmin, ar->winrct.ymin, d->w, d->h,
2094                                      GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2095                         
2096                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2097                         
2098                         d->damaged = 0;
2099                 }
2100         }
2101 }
2102
2103 /* utility function to find the closest Z value, use for autodepth */
2104 float view3d_depth_near(ViewDepths *d)
2105 {
2106         /* convert to float for comparisons */
2107         const float near = (float)d->depth_range[0];
2108         const float far_real = (float)d->depth_range[1];
2109         float far = far_real;
2110
2111         const float *depths = d->depths;
2112         float depth = FLT_MAX;
2113         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
2114
2115         /* far is both the starting 'far' value
2116          * and the closest value found. */      
2117         while (i--) {
2118                 depth = *depths++;
2119                 if ((depth < far) && (depth > near)) {
2120                         far = depth;
2121                 }
2122         }
2123
2124         return far == far_real ? FLT_MAX : far;
2125 }
2126
2127 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
2128 {
2129         short zbuf = v3d->zbuf;
2130         RegionView3D *rv3d = ar->regiondata;
2131
2132         setwinmatrixview3d(ar, v3d, NULL);  /* 0= no pick rect */
2133         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2134
2135         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2136         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2137         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2138
2139         glClear(GL_DEPTH_BUFFER_BIT);
2140
2141         glLoadMatrixf(rv3d->viewmat);
2142
2143         v3d->zbuf = TRUE;
2144         glEnable(GL_DEPTH_TEST);
2145
2146         draw_gpencil_view3d(scene, v3d, ar, 1);
2147         
2148         v3d->zbuf = zbuf;
2149
2150 }
2151
2152 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (*func)(void *))
2153 {
2154         RegionView3D *rv3d = ar->regiondata;
2155         Base *base;
2156         short zbuf = v3d->zbuf;
2157         short flag = v3d->flag;
2158         float glalphaclip = U.glalphaclip;
2159         int obcenter_dia = U.obcenter_dia;
2160         /* temp set drawtype to solid */
2161         
2162         /* Setting these temporarily is not nice */
2163         v3d->flag &= ~V3D_SELECT_OUTLINE;
2164         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
2165         U.obcenter_dia = 0;
2166         
2167         setwinmatrixview3d(ar, v3d, NULL);  /* 0= no pick rect */
2168         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2169         
2170         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2171         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2172         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2173         
2174         glClear(GL_DEPTH_BUFFER_BIT);
2175         
2176         glLoadMatrixf(rv3d->viewmat);
2177 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
2178         
2179         if (rv3d->rflag & RV3D_CLIPPING) {
2180                 ED_view3d_clipping_set(rv3d);
2181         }
2182         
2183         v3d->zbuf = TRUE;
2184         glEnable(GL_DEPTH_TEST);
2185         
2186         /* draw set first */
2187         if (scene->set) {
2188                 Scene *sce_iter;
2189                 for (SETLOOPER(scene->set, sce_iter, base)) {
2190                         if (v3d->lay & base->lay) {
2191                                 if (func == NULL || func(base)) {
2192                                         draw_object(scene, ar, v3d, base, 0);
2193                                         if (base->object->transflag & OB_DUPLI) {
2194                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2195                                         }
2196                                 }
2197                         }
2198                 }
2199         }
2200         
2201         for (base = scene->base.first; base; base = base->next) {
2202                 if (v3d->lay & base->lay) {
2203                         if (func == NULL || func(base)) {
2204                                 /* dupli drawing */
2205                                 if (base->object->transflag & OB_DUPLI) {
2206                                         draw_dupli_objects(scene, ar, v3d, base);
2207                                 }
2208                                 draw_object(scene, ar, v3d, base, 0);
2209                         }
2210                 }
2211         }
2212         
2213         /* this isn't that nice, draw xray objects as if they are normal */
2214         if (v3d->afterdraw_transp.first ||
2215             v3d->afterdraw_xray.first ||
2216             v3d->afterdraw_xraytransp.first)
2217         {
2218                 View3DAfter *v3da, *next;
2219                 int mask_orig;
2220
2221                 v3d->xray = TRUE;
2222                 
2223                 /* transp materials can change the depth mask, see #21388 */
2224                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2225
2226
2227                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2228                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2229                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2230                                 next = v3da->next;
2231                                 draw_object(scene, ar, v3d, v3da->base, 0);
2232                         }
2233                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2234                 }
2235
2236                 /* draw 3 passes, transp/xray/xraytransp */
2237                 v3d->xray = FALSE;
2238                 v3d->transp = TRUE;
2239                 for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
2240                         next = v3da->next;
2241                         draw_object(scene, ar, v3d, v3da->base, 0);
2242                         BLI_remlink(&v3d->afterdraw_transp, v3da);
2243                         MEM_freeN(v3da);
2244                 }
2245
2246                 v3d->xray = TRUE;
2247                 v3d->transp = FALSE;
2248                 for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2249                         next = v3da->next;
2250                         draw_object(scene, ar, v3d, v3da->base, 0);
2251                         BLI_remlink(&v3d->afterdraw_xray, v3da);
2252                         MEM_freeN(v3da);
2253                 }
2254
2255                 v3d->xray = TRUE;
2256                 v3d->transp = TRUE;
2257                 for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
2258                         next = v3da->next;
2259                         draw_object(scene, ar, v3d, v3da->base, 0);
2260                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
2261                         MEM_freeN(v3da);
2262                 }
2263
2264                 
2265                 v3d->xray = FALSE;
2266                 v3d->transp = FALSE;
2267
2268                 glDepthMask(mask_orig);
2269         }
2270         
2271         if (rv3d->rflag & RV3D_CLIPPING)
2272                 ED_view3d_clipping_disable();
2273         
2274         v3d->zbuf = zbuf;
2275         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2276
2277         U.glalphaclip = glalphaclip;
2278         v3d->flag = flag;
2279         U.obcenter_dia = obcenter_dia;
2280 }
2281
2282 typedef struct View3DShadow {
2283         struct View3DShadow *next, *prev;
2284         GPULamp *lamp;
2285 } View3DShadow;
2286
2287 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par,
2288                                    float obmat[][4], ListBase *shadows)
2289 {
2290         GPULamp *lamp;
2291         Lamp *la = (Lamp *)ob->data;
2292         View3DShadow *shadow;
2293         
2294         lamp = GPU_lamp_from_blender(scene, ob, par);
2295         
2296         if (lamp) {
2297                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2298                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2299                 
2300                 if ((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
2301                         shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2302                         shadow->lamp = lamp;
2303                         BLI_addtail(shadows, shadow);
2304                 }
2305         }
2306 }
2307
2308 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
2309 {
2310         ListBase shadows;
2311         View3DShadow *shadow;
2312         Scene *sce_iter;
2313         Base *base;
2314         Object *ob;
2315         
2316         shadows.first = shadows.last = NULL;
2317         
2318         /* update lamp transform and gather shadow lamps */
2319         for (SETLOOPER(scene, sce_iter, base)) {
2320                 ob = base->object;
2321                 
2322                 if (ob->type == OB_LAMP)
2323                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2324                 
2325                 if (ob->transflag & OB_DUPLI) {
2326                         DupliObject *dob;
2327                         ListBase *lb = object_duplilist(scene, ob);
2328                         
2329                         for (dob = lb->first; dob; dob = dob->next)
2330                                 if (dob->ob->type == OB_LAMP)
2331                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2332                         
2333                         free_object_duplilist(lb);
2334                 }
2335         }
2336         
2337         /* render shadows after updating all lamps, nested object_duplilist
2338          * don't work correct since it's replacing object matrices */
2339         for (shadow = shadows.first; shadow; shadow = shadow->next) {
2340                 /* this needs to be done better .. */
2341                 float viewmat[4][4], winmat[4][4];
2342                 int drawtype, lay, winsize, flag2 = v3d->flag2;
2343                 ARegion ar = {NULL};
2344                 RegionView3D rv3d = {{{0}}};
2345                 
2346                 drawtype = v3d->drawtype;
2347                 lay = v3d->lay;
2348                 
2349                 v3d->drawtype = OB_SOLID;
2350                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2351                 v3d->flag2 &= ~V3D_SOLID_TEX;
2352                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2353                 
2354                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2355
2356                 ar.regiondata = &rv3d;
2357                 ar.regiontype = RGN_TYPE_WINDOW;
2358                 rv3d.persp = RV3D_CAMOB;
2359                 copy_m4_m4(rv3d.winmat, winmat);
2360                 copy_m4_m4(rv3d.viewmat, viewmat);
2361                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2362                 mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2363                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2364
2365                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat, FALSE);
2366                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2367                 
2368                 v3d->drawtype = drawtype;
2369                 v3d->lay = lay;
2370                 v3d->flag2 = flag2;
2371         }
2372         
2373         BLI_freelistN(&shadows);
2374 }
2375
2376 /* *********************** customdata **************** */
2377
2378 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2379 {
2380         CustomDataMask mask = 0;
2381
2382         if (ELEM(v3d->drawtype, OB_TEXTURE, OB_MATERIAL) ||
2383             ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
2384         {
2385                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2386
2387                 if (BKE_scene_use_new_shading_nodes(scene)) {
2388                         if (v3d->drawtype == OB_MATERIAL)
2389                                 mask |= CD_MASK_ORCO;
2390                 }
2391                 else {
2392                         if (scene->gm.matmode == GAME_MAT_GLSL)
2393                                 mask |= CD_MASK_ORCO;
2394                 }
2395         }
2396
2397         return mask;
2398 }
2399
2400 CustomDataMask ED_view3d_object_datamask(Scene *scene)
2401 {
2402         Object *ob = scene->basact ? scene->basact->object : NULL;
2403         CustomDataMask mask = 0;
2404
2405         if (ob) {
2406                 /* check if we need tfaces & mcols due to face select or texture paint */
2407                 if (paint_facesel_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2408                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2409                 }
2410
2411                 /* check if we need mcols due to vertex paint or weightpaint */
2412                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2413                         mask |= CD_MASK_MCOL;
2414                 }
2415
2416                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2417                         mask |= CD_MASK_PREVIEW_MCOL;
2418                 }
2419
2420                 if (ob->mode & OB_MODE_EDIT)
2421                         mask |= CD_MASK_MVERT_SKIN;
2422         }
2423
2424         return mask;
2425 }
2426
2427 /* goes over all modes and view3d settings */
2428 CustomDataMask ED_view3d_screen_datamask(bScreen *screen)
2429 {
2430         Scene *scene = screen->scene;
2431         CustomDataMask mask = CD_MASK_BAREMESH;
2432         ScrArea *sa;
2433         
2434         /* check if we need tfaces & mcols due to view mode */
2435         for (sa = screen->areabase.first; sa; sa = sa->next) {
2436                 if (sa->spacetype == SPACE_VIEW3D) {
2437                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2438                 }
2439         }
2440
2441         mask |= ED_view3d_object_datamask(scene);
2442
2443         return mask;
2444 }
2445
2446 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2447 {
2448         RegionView3D *rv3d = ar->regiondata;
2449
2450         /* setup window matrices */
2451         if (winmat)
2452                 copy_m4_m4(rv3d->winmat, winmat);
2453         else
2454                 setwinmatrixview3d(ar, v3d, NULL);  /* NULL= no pickrect */
2455
2456         /* setup view matrix */
2457         if (viewmat)
2458                 copy_m4_m4(rv3d->viewmat, viewmat);
2459         else
2460                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2461
2462         /* update utilitity matrices */
2463         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2464         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2465         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2466
2467         /* calculate pixelsize factor once, is used for lamps and obcenters */
2468         {
2469                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2470                  * because of float point precision problems at large values [#23908] */
2471                 float v1[3], v2[3];
2472                 float len1, len2;
2473
2474                 v1[0] = rv3d->persmat[0][0];
2475                 v1[1] = rv3d->persmat[1][0];
2476                 v1[2] = rv3d->persmat[2][0];
2477
2478                 v2[0] = rv3d->persmat[0][1];
2479                 v2[1] = rv3d->persmat[1][1];
2480                 v2[2] = rv3d->persmat[2][1];
2481
2482                 len1 = 1.0f / len_v3(v1);
2483                 len2 = 1.0f / len_v3(v2);
2484
2485                 rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
2486         }
2487 }
2488
2489 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2490 {
2491         RegionView3D *rv3d = ar->regiondata;
2492
2493         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
2494
2495         /* set for opengl */
2496         glMatrixMode(GL_PROJECTION);
2497         glLoadMatrixf(rv3d->winmat);
2498         glMatrixMode(GL_MODELVIEW);
2499         glLoadMatrixf(rv3d->viewmat);
2500 }
2501
2502 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
2503                               int winx, int winy, float viewmat[][4], float winmat[][4],
2504                               int do_bgpic)
2505 {
2506         RegionView3D *rv3d = ar->regiondata;
2507         Base *base;
2508         float backcol[3];
2509         int bwinx, bwiny;
2510         rcti brect;
2511
2512         glPushMatrix();
2513
2514         /* set temporary new size */
2515         bwinx = ar->winx;
2516         bwiny = ar->winy;
2517         brect = ar->winrct;
2518         
2519         ar->winx = winx;
2520         ar->winy = winy;
2521         ar->winrct.xmin = 0;
2522         ar->winrct.ymin = 0;
2523         ar->winrct.xmax = winx;
2524         ar->winrct.ymax = winy;
2525
2526         /* set theme */
2527         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
2528         
2529         /* set flags */
2530         G.f |= G_RENDER_OGL;
2531
2532         /* free images which can have changed on frame-change
2533          * warning! can be slow so only free animated images - campbell */
2534         GPU_free_images_anim();
2535         
2536         /* shadow buffers, before we setup matrices */
2537         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2538                 gpu_update_lamps_shadows(scene, v3d);
2539
2540         /* set background color, fallback on the view background color
2541          * (if active clip is set but frame is failed to load fallback to horizon color as background) */
2542         if (scene->world) {
2543                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2544                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2545                 else
2546                         copy_v3_v3(backcol, &scene->world->horr);
2547                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2548         }
2549         else {
2550                 UI_ThemeClearColor(TH_BACK);
2551         }
2552
2553
2554         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2555
2556         /* setup view matrices */
2557         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2558
2559         if (rv3d->rflag & RV3D_CLIPPING)
2560                 view3d_draw_clipping(rv3d);
2561
2562         /* set zbuffer */
2563         if (v3d->drawtype > OB_WIRE) {
2564                 v3d->zbuf = TRUE;
2565                 glEnable(GL_DEPTH_TEST);
2566         }
2567         else
2568                 v3d->zbuf = FALSE;
2569
2570         /* important to do before clipping */
2571         if (do_bgpic) {
2572                 view3d_draw_bgpic_test(scene, ar, v3d, FALSE, FALSE);
2573         }
2574
2575         if (rv3d->rflag & RV3D_CLIPPING)
2576                 ED_view3d_clipping_set(rv3d);
2577
2578         /* draw set first */
2579         if (scene->set) {
2580                 Scene *sce_iter;
2581                 for (SETLOOPER(scene->set, sce_iter, base)) {
2582                         if (v3d->lay & base->lay) {
2583                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2584                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
2585                                 
2586                                 if (base->object->transflag & OB_DUPLI)
2587                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2588                         }
2589                 }
2590         }
2591         
2592         /* then draw not selected and the duplis, but skip editmode object */
2593         for (base = scene->base.first; base; base = base->next) {
2594                 if (v3d->lay & base->lay) {
2595                         /* dupli drawing */
2596                         if (base->object->transflag & OB_DUPLI)
2597                                 draw_dupli_objects(scene, ar, v3d, base);
2598
2599                         draw_object(scene, ar, v3d, base, 0);
2600                 }
2601         }
2602
2603         /* must be before xray draw which clears the depth buffer */
2604         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
2605         draw_gpencil_view3d(scene, v3d, ar, 1);
2606         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
2607
2608         /* transp and X-ray afterdraw stuff */
2609         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, ar, v3d);
2610         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, ar, v3d, 1);       /* clears zbuffer if it is used! */
2611         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
2612
2613         if (rv3d->rflag & RV3D_CLIPPING)
2614                 ED_view3d_clipping_disable();
2615
2616         /* important to do after clipping */
2617         if (do_bgpic) {
2618                 view3d_draw_bgpic_test(scene, ar, v3d, TRUE, FALSE);
2619         }
2620
2621         /* cleanup */
2622         if (v3d->zbuf) {
2623                 v3d->zbuf = FALSE;
2624                 glDisable(GL_DEPTH_TEST);
2625         }
2626
2627         /* draw grease-pencil stuff */
2628         ED_region_pixelspace(ar);
2629
2630         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2631         draw_gpencil_view3d(scene, v3d, ar, 0);
2632
2633         /* freeing the images again here could be done after the operator runs, leaving for now */
2634         GPU_free_images_anim();
2635
2636         /* restore size */
2637         ar->winx = bwinx;
2638         ar->winy = bwiny;
2639         ar->winrct = brect;
2640
2641         glPopMatrix();
2642
2643         // XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell
2644         glColor4ub(255, 255, 255, 255);
2645
2646         G.f &= ~G_RENDER_OGL;
2647 }
2648
2649 /* utility func for ED_view3d_draw_offscreen */
2650 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar,
2651                                       int sizex, int sizey, unsigned int flag, int draw_background, char err_out[256])
2652 {
2653         RegionView3D *rv3d = ar->regiondata;
2654         ImBuf *ibuf;
2655         GPUOffScreen *ofs;
2656         
2657         /* state changes make normal drawing go weird otherwise */
2658         glPushAttrib(GL_LIGHTING_BIT);
2659
2660         /* bind */
2661         ofs = GPU_offscreen_create(sizex, sizey, err_out);
2662         if (ofs == NULL)
2663                 return NULL;
2664
2665         GPU_offscreen_bind(ofs);
2666
2667         /* render 3d view */
2668         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2669                 CameraParams params;
2670
2671                 BKE_camera_params_init(&params);
2672                 BKE_camera_params_from_object(&params, v3d->camera);
2673                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2674                 BKE_camera_params_compute_matrix(&params);
2675
2676                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, params.winmat, draw_background);
2677         }
2678         else {
2679                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL, draw_background);
2680         }
2681
2682         /* read in pixels & stamp */
2683         ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2684
2685         if (ibuf->rect_float)
2686                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2687         else if (ibuf->rect)
2688                 GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2689         
2690         //if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
2691         //      BKE_stamp_buf(scene, NULL, rr->rectf, rr->rectx, rr->recty, 4);
2692
2693         /* unbind */
2694         GPU_offscreen_unbind(ofs);
2695         GPU_offscreen_free(ofs);
2696
2697         glPopAttrib();
2698         
2699         if (ibuf->rect_float && ibuf->rect)
2700                 IMB_rect_from_float(ibuf);
2701         
2702         return ibuf;
2703 }
2704
2705 /* creates own 3d views, used by the sequencer */
2706 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height,
2707                                              unsigned int flag, int drawtype, int draw_background, char err_out[256])
2708 {
2709         View3D v3d = {NULL};
2710         ARegion ar = {NULL};
2711         RegionView3D rv3d = {{{0}}};
2712
2713         /* connect data */
2714         v3d.regionbase.first = v3d.regionbase.last = &ar;
2715         ar.regiondata = &rv3d;
2716         ar.regiontype = RGN_TYPE_WINDOW;
2717
2718         v3d.camera = camera;
2719         v3d.lay = scene->lay;
2720         v3d.drawtype = drawtype;
2721         v3d.flag2 = V3D_RENDER_OVERRIDE;
2722
2723         rv3d.persp = RV3D_CAMOB;
2724
2725         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2726         normalize_m4(rv3d.viewinv);
2727         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2728
2729         {
2730                 CameraParams params;
2731
2732                 BKE_camera_params_init(&params);
2733                 BKE_camera_params_from_object(&params, v3d.camera);
2734                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2735                 BKE_camera_params_compute_matrix(&params);
2736
2737                 copy_m4_m4(rv3d.winmat, params.winmat);
2738                 v3d.near = params.clipsta;
2739                 v3d.far = params.clipend;
2740                 v3d.lens = params.lens;
2741         }
2742
2743         mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2744         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2745
2746         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag, draw_background, err_out);
2747
2748         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2749 }
2750
2751
2752 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2753  * which currently gets called during SCREEN_OT_animation_step.
2754  */
2755 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2756 {
2757         ScreenFrameRateInfo *fpsi = scene->fps_info;
2758         float fps;
2759         char printable[16];
2760         int i, tot;
2761         
2762         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2763                 return;
2764         
2765         printable[0] = '\0';
2766         
2767 #if 0
2768         /* this is too simple, better do an average */
2769         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
2770 #else
2771         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
2772         
2773         for (i = 0, tot = 0, fps = 0.0f; i < REDRAW_FRAME_AVERAGE; i++) {
2774                 if (fpsi->redrawtimes_fps[i]) {
2775                         fps += fpsi->redrawtimes_fps[i];
2776                         tot++;
2777                 }
2778         }
2779         if (tot) {
2780                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2781                 
2782                 //fpsi->redrawtime_index++;
2783                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2784                 //      fpsi->redrawtime = 0;
2785                 
2786                 fps = fps / tot;
2787         }
2788 #endif
2789
2790         /* is this more then half a frame behind? */
2791         if (fps + 0.5f < (float)(FPS)) {
2792                 UI_ThemeColor(TH_REDALERT);
2793                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2794         } 
2795         else {
2796                 UI_ThemeColor(TH_TEXT_HI);
2797                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps + 0.5f));
2798         }
2799         
2800         BLF_draw_default_ascii(22,  ar->winy - 17, 0.0f, printable, sizeof(printable));
2801 }
2802
2803 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit);
2804
2805 static int view3d_main_area_do_render_draw(const bContext *C)
2806 {
2807         Scene *scene = CTX_data_scene(C);
2808         RenderEngineType *type = RE_engines_find(scene->r.engine);
2809
2810         return (type && type->view_update && type->view_draw);
2811 }
2812
2813 static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw_border)
2814 {
2815         Scene *scene = CTX_data_scene(C);
2816         View3D *v3d = CTX_wm_view3d(C);
2817         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2818         RenderEngineType *type;
2819         GLint scissor[4];
2820
2821         /* create render engine */
2822         if (!rv3d->render_engine) {
2823                 type = RE_engines_find(scene->r.engine);
2824
2825                 if (!(type->view_update && type->view_draw))
2826                         return 0;
2827
2828                 rv3d->render_engine = RE_engine_create(type);
2829                 type->view_update(rv3d->render_engine, C);
2830         }
2831
2832         /* setup view matrices */
2833         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2834
2835         /* background draw */
2836         ED_region_pixelspace(ar);
2837
2838         if (draw_border) {
2839                 /* for border draw, we only need to clear a subset of the 3d view */
2840                 rctf viewborder;
2841                 rcti cliprct;
2842
2843                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, FALSE);
2844
2845                 cliprct.xmin = viewborder.xmin + scene->r.border.xmin * (viewborder.xmax - viewborder.xmin);
2846                 cliprct.ymin = viewborder.ymin + scene->r.border.ymin * (viewborder.ymax - viewborder.ymin);
2847                 cliprct.xmax = viewborder.xmin + scene->r.border.xmax * (viewborder.xmax - viewborder.xmin);
2848                 cliprct.ymax = viewborder.ymin + scene->r.border.ymax * (viewborder.ymax - viewborder.ymin);
2849
2850                 cliprct.xmin += ar->winrct.xmin;
2851                 cliprct.xmax += ar->winrct.xmin;
2852                 cliprct.ymin += ar->winrct.ymin;
2853                 cliprct.ymax += ar->winrct.ymin;
2854
2855                 cliprct.xmin = CLAMPIS(cliprct.xmin, ar->winrct.xmin, ar->winrct.xmax);
2856                 cliprct.ymin = CLAMPIS(cliprct.ymin, ar->winrct.ymin, ar->winrct.ymax);
2857                 cliprct.xmax = CLAMPIS(cliprct.xmax, ar->winrct.xmin, ar->winrct.xmax);
2858                 cliprct.ymax = CLAMPIS(cliprct.ymax, ar->winrct.ymin, ar->winrct.ymax);
2859
2860                 if (cliprct.xmax > cliprct.xmin && cliprct.ymax > cliprct.ymin) {
2861                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
2862                         glScissor(cliprct.xmin, cliprct.ymin, cliprct.xmax - cliprct.xmin, cliprct.ymax - cliprct.ymin);
2863                 }
2864                 else
2865                         return 0;
2866         }
2867
2868         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2869         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2870
2871         if (v3d->flag & V3D_DISPBGPICS)
2872                 view3d_draw_bgpic(scene, ar, v3d, FALSE, TRUE);
2873         else
2874                 fdrawcheckerboard(0, 0, ar->winx, ar->winy);
2875
2876         /* render result draw */
2877         type = rv3d->render_engine->type;
2878         type->view_draw(rv3d->render_engine, C);
2879
2880         if (v3d->flag & V3D_DISPBGPICS)
2881                 view3d_draw_bgpic(scene, ar, v3d, TRUE, TRUE);
2882
2883         if (draw_border) {
2884                 /* restore scissor as it was before */
2885                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2886         }
2887
2888         return 1;
2889 }
2890
2891 static void view3d_main_area_draw_engine_info(RegionView3D *rv3d, ARegion *ar)
2892 {
2893         if (!rv3d->render_engine || !rv3d->render_engine->text)
2894                 return;
2895
2896         ED_region_info_draw(ar, rv3d->render_engine->text, 1, 0.25);
2897 }
2898
2899 /* warning: this function has duplicate drawing in ED_view3d_draw_offscreen() */
2900 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit)
2901 {
2902         Scene *scene = CTX_data_scene(C);
2903         View3D *v3d = CTX_wm_view3d(C);
2904         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2905         Base *base;
2906         float backcol[3];
2907         unsigned int lay_used;
2908
2909         /* shadow buffers, before we setup matrices */
2910         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2911                 gpu_update_lamps_shadows(scene, v3d);
2912         
2913         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2914         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2915                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2916                 GPU_default_lights();
2917         }
2918
2919         /* clear background */
2920         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) && scene->world) {
2921                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2922                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2923                 else
2924                         copy_v3_v3(backcol, &scene->world->horr);
2925                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2926         }
2927         else
2928                 UI_ThemeClearColor(TH_BACK);
2929
2930         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2931         
2932         /* setup view matrices */
2933         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2934
2935         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2936
2937         if (rv3d->rflag & RV3D_CLIPPING)
2938                 view3d_draw_clipping(rv3d);
2939         
2940         /* set zbuffer after we draw clipping region */
2941         if (v3d->drawtype > OB_WIRE) {
2942                 v3d->zbuf = TRUE;
2943                 glEnable(GL_DEPTH_TEST);
2944         }
2945         else
2946                 v3d->zbuf = FALSE;
2947
2948         /* enables anti-aliasing for 3D view drawing */
2949 #if 0
2950         if (!(U.gameflags & USER_DISABLE_AA))
2951                 glEnable(GL_MULTISAMPLE_ARB);
2952 #endif
2953
2954         // needs to be done always, gridview is adjusted in drawgrid() now
2955         rv3d->gridview = v3d->grid;
2956
2957         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
2958                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2959                         drawfloor(scene, v3d, grid_unit);
2960                 }
2961                 if (rv3d->persp == RV3D_CAMOB) {
2962                         if (scene->world) {
2963                                 if (scene->world->mode & WO_STARS) {
2964                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2965                                                       star_stuff_term_func);
2966                                 }
2967                         }
2968                 }
2969         }
2970         else {
2971                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2972                         ED_region_pixelspace(ar);
2973                         drawgrid(&scene->unit, ar, v3d, grid_unit);
2974                         /* XXX make function? replaces persp(1) */
2975                         glMatrixMode(GL_PROJECTION);
2976                         glLoadMatrixf(rv3d->winmat);
2977                         glMatrixMode(GL_MODELVIEW);
2978                         glLoadMatrixf(rv3d->viewmat);
2979                 }
2980         }
2981
2982         view3d_draw_bgpic_test(scene, ar, v3d, FALSE, TRUE);
2983
2984         if (rv3d->rflag & RV3D_CLIPPING)
2985                 ED_view3d_clipping_set(rv3d);
2986
2987         /* draw set first */
2988         if (scene->set) {
2989                 Scene *sce_iter;
2990                 for (SETLOOPER(scene->set, sce_iter, base)) {
2991                         
2992                         if (v3d->lay & base->lay) {
2993                                 
2994                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2995                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
2996                                 
2997                                 if (base->object->transflag & OB_DUPLI) {
2998                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2999                                 }
3000                         }
3001                 }
3002                 
3003                 /* Transp and X-ray afterdraw stuff for sets is done later */
3004         }
3005
3006         lay_used = 0;
3007
3008         /* then draw not selected and the duplis, but skip editmode object */
3009         for (base = scene->base.first; base; base = base->next) {
3010                 lay_used |= base->lay & ((1 << 20) - 1);
3011
3012                 if (v3d->lay & base->lay) {
3013                         
3014                         /* dupli drawing */
3015                         if (base->object->transflag & OB_DUPLI) {
3016                                 draw_dupli_objects(scene, ar, v3d, base);
3017                         }
3018                         if ((base->flag & SELECT) == 0) {
3019                                 if (base->object != scene->obedit)
3020                                         draw_object(scene, ar, v3d, base, 0);
3021                         }
3022                 }
3023         }
3024
3025         if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
3026                 /* find header and force tag redraw */
3027                 ScrArea *sa = CTX_wm_area(C);
3028                 ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
3029                 ED_region_tag_redraw(ar_header); /* can be NULL */
3030                 v3d->lay_used = lay_used;
3031         }
3032
3033         /* draw selected and editmode */
3034         for (base = scene->base.first; base; base = base->next) {
3035                 if (v3d->lay & base->lay) {
3036                         if (base->object == scene->obedit || (base->flag & SELECT) )
3037                                 draw_object(scene, ar, v3d, base, 0);
3038                 }
3039         }
3040
3041 //      REEB_draw();
3042
3043         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
3044                 /* must be before xray draw which clears the depth buffer */
3045                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
3046                 draw_gpencil_view3d(scene, v3d, ar, 1);
3047                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
3048         }
3049
3050         /* Transp and X-ray afterdraw stuff */
3051         if (v3d->afterdraw_transp.first) view3d_draw_transp(scene, ar, v3d);
3052         if (v3d->afterdraw_xray.first) view3d_draw_xray(scene, ar, v3d, 1);         // clears zbuffer if it is used!
3053         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
3054         
3055         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
3056
3057         if (rv3d->rflag & RV3D_CLIPPING)
3058                 ED_view3d_clipping_disable();
3059         
3060         /* important to do after clipping */
3061         view3d_draw_bgpic_test(scene, ar, v3d, TRUE, TRUE);
3062
3063         BIF_draw_manipulator(C);
3064
3065 #if 0
3066         /* Disable back anti-aliasing */
3067         if (!(U.gameflags & USER_DISABLE_AA))
3068                 glDisable(GL_MULTISAMPLE_ARB);
3069 #endif
3070
3071         if (v3d->zbuf) {
3072                 v3d->zbuf = FALSE;
3073                 glDisable(GL_DEPTH_TEST);
3074         }
3075
3076         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
3077                 BDR_drawSketch(C);
3078         }
3079
3080         if ((U.ndof_flag & NDOF_SHOW_GUIDE) && (rv3d->viewlock != RV3D_LOCKED) && (rv3d->persp != RV3D_CAMOB))
3081                 // TODO: draw something else (but not this) during fly mode
3082                 draw_rotation_guide(rv3d);
3083
3084 }
3085
3086 static void view3d_main_area_draw_info(const bContext *C, ARegion *ar, const char *grid_unit)
3087 {
3088         wmWindowManager *wm = CTX_wm_manager(C);
3089         Scene *scene = CTX_data_scene(C);
3090         View3D *v3d = CTX_wm_view3d(C);
3091         RegionView3D *rv3d = CTX_wm_region_view3d(C);
3092
3093         Object *ob;
3094
3095         if (rv3d->persp == RV3D_CAMOB)
3096                 drawviewborder(scene, ar, v3d);
3097
3098         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
3099