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