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