Fix threading issues of viewport rendering when using movies/generated images
[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;
1931         short dtx;
1932         
1933         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1934         
1935         tbase.flag = OB_FROMDUPLI | base->flag;
1936         lb = object_duplilist(scene, base->object, FALSE);
1937         // BLI_sortlist(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
1938
1939         dob = dupli_step(lb->first);
1940         if (dob) dob_next = dupli_step(dob->next);
1941
1942         for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1943                 tbase.object = dob->ob;
1944
1945                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
1946                  * to allow e.g. boundbox box objects in groups for LOD */
1947                 dt = tbase.object->dt;
1948                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1949
1950                 /* inherit draw extra, but not if a boundbox under the assumption that this
1951                  * is intended to speed up drawing, and drawing extra (especially wire) can
1952                  * slow it down too much */
1953                 dtx = tbase.object->dtx;
1954                 if (tbase.object->dt != OB_BOUNDBOX)
1955                         tbase.object->dtx = base->object->dtx;
1956
1957                 /* negative scale flag has to propagate */
1958                 transflag = tbase.object->transflag;
1959                 if (base->object->transflag & OB_NEG_SCALE)
1960                         tbase.object->transflag ^= OB_NEG_SCALE;
1961
1962                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1963
1964                 /* generate displist, test for new object */
1965                 if (dob_prev && dob_prev->ob != dob->ob) {
1966                         if (use_displist == TRUE)
1967                                 glDeleteLists(displist, 1);
1968
1969                         use_displist = -1;
1970                 }
1971
1972                 /* generate displist */
1973                 if (use_displist == -1) {
1974
1975                         /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
1976                          * however this is very slow, it was probably needed for the NLA
1977                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1978                          * so for now it should be ok to - campbell */
1979
1980                         if ( /* if this is the last no need  to make a displist */
1981                             (dob_next == NULL || dob_next->ob != dob->ob) ||
1982                             /* lamp drawing messes with matrices, could be handled smarter... but this works */
1983                             (dob->ob->type == OB_LAMP) ||
1984                             (dob->type == OB_DUPLIGROUP && dob->animated) ||
1985                             !(bb_tmp = BKE_object_boundbox_get(dob->ob)))
1986                         {
1987                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1988                                 use_displist = FALSE;
1989                         }
1990                         else {
1991                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1992                                 bb = *bb_tmp; /* must make a copy  */
1993
1994                                 /* disable boundbox check for list creation */
1995                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1996                                 /* need this for next part of code */
1997                                 unit_m4(dob->ob->obmat);    /* obmat gets restored */
1998
1999                                 displist = glGenLists(1);
2000                                 glNewList(displist, GL_COMPILE);
2001                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
2002                                 glEndList();
2003
2004                                 use_displist = TRUE;
2005                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
2006                         }
2007                 }
2008                 if (use_displist) {
2009                         glMultMatrixf(dob->mat);
2010                         if (ED_view3d_boundbox_clip(rv3d, dob->mat, &bb))
2011                                 glCallList(displist);
2012                         glLoadMatrixf(rv3d->viewmat);
2013                 }
2014                 else {
2015                         copy_m4_m4(dob->ob->obmat, dob->mat);
2016                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
2017                 }
2018
2019                 tbase.object->dt = dt;
2020                 tbase.object->dtx = dtx;
2021                 tbase.object->transflag = transflag;
2022         }
2023         
2024         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
2025         
2026         free_object_duplilist(lb);  /* does restore */
2027         
2028         if (use_displist)
2029                 glDeleteLists(displist, 1);
2030 }
2031
2032 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
2033 {
2034         /* define the color here so draw_dupli_objects_color can be called
2035          * from the set loop */
2036         
2037         int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
2038         /* debug */
2039         if (base->object->dup_group && base->object->dup_group->id.us < 1)
2040                 color = TH_REDALERT;
2041         
2042         draw_dupli_objects_color(scene, ar, v3d, base, color);
2043 }
2044
2045 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
2046 {
2047         int x, y, w, h;
2048         rcti r;
2049         /* clamp rect by area */
2050
2051         r.xmin = 0;
2052         r.xmax = ar->winx - 1;
2053         r.ymin = 0;
2054         r.ymax = ar->winy - 1;
2055
2056         /* Constrain rect to depth bounds */
2057         BLI_rcti_isect(&r, rect, rect);
2058
2059         /* assign values to compare with the ViewDepths */
2060         x = rect->xmin;
2061         y = rect->ymin;
2062
2063         w = BLI_rcti_size_x(rect);
2064         h = BLI_rcti_size_y(rect);
2065
2066         if (w <= 0 || h <= 0) {
2067                 if (d->depths)
2068                         MEM_freeN(d->depths);
2069                 d->depths = NULL;
2070
2071                 d->damaged = FALSE;
2072         }
2073         else if (d->w != w ||
2074                  d->h != h ||
2075                  d->x != x ||
2076                  d->y != y ||
2077                  d->depths == NULL
2078                  )
2079         {
2080                 d->x = x;
2081                 d->y = y;
2082                 d->w = w;
2083                 d->h = h;
2084
2085                 if (d->depths)
2086                         MEM_freeN(d->depths);
2087
2088                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
2089                 
2090                 d->damaged = TRUE;
2091         }
2092
2093         if (d->damaged) {
2094                 glReadPixels(ar->winrct.xmin + d->x, ar->winrct.ymin + d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2095                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2096                 d->damaged = FALSE;
2097         }
2098 }
2099
2100 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
2101 void ED_view3d_depth_update(ARegion *ar)
2102 {
2103         RegionView3D *rv3d = ar->regiondata;
2104         
2105         /* Create storage for, and, if necessary, copy depth buffer */
2106         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
2107         if (rv3d->depths) {
2108                 ViewDepths *d = rv3d->depths;
2109                 if (d->w != ar->winx ||
2110                     d->h != ar->winy ||
2111                     !d->depths)
2112                 {
2113                         d->w = ar->winx;
2114                         d->h = ar->winy;
2115                         if (d->depths)
2116                                 MEM_freeN(d->depths);
2117                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
2118                         d->damaged = 1;
2119                 }
2120                 
2121                 if (d->damaged) {
2122                         glReadPixels(ar->winrct.xmin, ar->winrct.ymin, d->w, d->h,
2123                                      GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2124                         
2125                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2126                         
2127                         d->damaged = 0;
2128                 }
2129         }
2130 }
2131
2132 /* utility function to find the closest Z value, use for autodepth */
2133 float view3d_depth_near(ViewDepths *d)
2134 {
2135         /* convert to float for comparisons */
2136         const float near = (float)d->depth_range[0];
2137         const float far_real = (float)d->depth_range[1];
2138         float far = far_real;
2139
2140         const float *depths = d->depths;
2141         float depth = FLT_MAX;
2142         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
2143
2144         /* far is both the starting 'far' value
2145          * and the closest value found. */
2146         while (i--) {
2147                 depth = *depths++;
2148                 if ((depth < far) && (depth > near)) {
2149                         far = depth;
2150                 }
2151         }
2152
2153         return far == far_real ? FLT_MAX : far;
2154 }
2155
2156 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
2157 {
2158         short zbuf = v3d->zbuf;
2159         RegionView3D *rv3d = ar->regiondata;
2160
2161         setwinmatrixview3d(ar, v3d, NULL);
2162         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2163
2164         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2165         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2166         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2167
2168         glClear(GL_DEPTH_BUFFER_BIT);
2169
2170         glLoadMatrixf(rv3d->viewmat);
2171
2172         v3d->zbuf = TRUE;
2173         glEnable(GL_DEPTH_TEST);
2174
2175         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2176                 draw_gpencil_view3d(scene, v3d, ar, TRUE);
2177         }
2178         
2179         v3d->zbuf = zbuf;
2180
2181 }
2182
2183 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (*func)(void *))
2184 {
2185         RegionView3D *rv3d = ar->regiondata;
2186         Base *base;
2187         short zbuf = v3d->zbuf;
2188         short flag = v3d->flag;
2189         float glalphaclip = U.glalphaclip;
2190         int obcenter_dia = U.obcenter_dia;
2191         /* temp set drawtype to solid */
2192         
2193         /* Setting these temporarily is not nice */
2194         v3d->flag &= ~V3D_SELECT_OUTLINE;
2195         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
2196         U.obcenter_dia = 0;
2197         
2198         setwinmatrixview3d(ar, v3d, NULL);
2199         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2200         
2201         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2202         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2203         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2204         
2205         glClear(GL_DEPTH_BUFFER_BIT);
2206         
2207         glLoadMatrixf(rv3d->viewmat);
2208 //      persp(PERSP_STORE);  /* store correct view for persp(PERSP_VIEW) calls */
2209         
2210         if (rv3d->rflag & RV3D_CLIPPING) {
2211                 ED_view3d_clipping_set(rv3d);
2212         }
2213         
2214         v3d->zbuf = TRUE;
2215         glEnable(GL_DEPTH_TEST);
2216         
2217         /* draw set first */
2218         if (scene->set) {
2219                 Scene *sce_iter;
2220                 for (SETLOOPER(scene->set, sce_iter, base)) {
2221                         if (v3d->lay & base->lay) {
2222                                 if (func == NULL || func(base)) {
2223                                         draw_object(scene, ar, v3d, base, 0);
2224                                         if (base->object->transflag & OB_DUPLI) {
2225                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2226                                         }
2227                                 }
2228                         }
2229                 }
2230         }
2231         
2232         for (base = scene->base.first; base; base = base->next) {
2233                 if (v3d->lay & base->lay) {
2234                         if (func == NULL || func(base)) {
2235                                 /* dupli drawing */
2236                                 if (base->object->transflag & OB_DUPLI) {
2237                                         draw_dupli_objects(scene, ar, v3d, base);
2238                                 }
2239                                 draw_object(scene, ar, v3d, base, 0);
2240                         }
2241                 }
2242         }
2243         
2244         /* this isn't that nice, draw xray objects as if they are normal */
2245         if (v3d->afterdraw_transp.first ||
2246             v3d->afterdraw_xray.first ||
2247             v3d->afterdraw_xraytransp.first)
2248         {
2249                 View3DAfter *v3da, *next;
2250                 int mask_orig;
2251
2252                 v3d->xray = TRUE;
2253                 
2254                 /* transp materials can change the depth mask, see #21388 */
2255                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2256
2257
2258                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2259                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2260                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2261                                 next = v3da->next;
2262                                 draw_object(scene, ar, v3d, v3da->base, 0);
2263                         }
2264                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2265                 }
2266
2267                 /* draw 3 passes, transp/xray/xraytransp */
2268                 v3d->xray = FALSE;
2269                 v3d->transp = TRUE;
2270                 for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
2271                         next = v3da->next;
2272                         draw_object(scene, ar, v3d, v3da->base, 0);
2273                         BLI_remlink(&v3d->afterdraw_transp, v3da);
2274                         MEM_freeN(v3da);
2275                 }
2276
2277                 v3d->xray = TRUE;
2278                 v3d->transp = FALSE;
2279                 for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2280                         next = v3da->next;
2281                         draw_object(scene, ar, v3d, v3da->base, 0);
2282                         BLI_remlink(&v3d->afterdraw_xray, v3da);
2283                         MEM_freeN(v3da);
2284                 }
2285
2286                 v3d->xray = TRUE;
2287                 v3d->transp = TRUE;
2288                 for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
2289                         next = v3da->next;
2290                         draw_object(scene, ar, v3d, v3da->base, 0);
2291                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
2292                         MEM_freeN(v3da);
2293                 }
2294
2295                 
2296                 v3d->xray = FALSE;
2297                 v3d->transp = FALSE;
2298
2299                 glDepthMask(mask_orig);
2300         }
2301         
2302         if (rv3d->rflag & RV3D_CLIPPING)
2303                 ED_view3d_clipping_disable();
2304         
2305         v3d->zbuf = zbuf;
2306         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2307
2308         U.glalphaclip = glalphaclip;
2309         v3d->flag = flag;
2310         U.obcenter_dia = obcenter_dia;
2311 }
2312
2313 typedef struct View3DShadow {
2314         struct View3DShadow *next, *prev;
2315         GPULamp *lamp;
2316 } View3DShadow;
2317
2318 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par,
2319                                    float obmat[4][4], ListBase *shadows)
2320 {
2321         GPULamp *lamp;
2322         Lamp *la = (Lamp *)ob->data;
2323         View3DShadow *shadow;
2324         
2325         lamp = GPU_lamp_from_blender(scene, ob, par);
2326         
2327         if (lamp) {
2328                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2329                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2330                 
2331                 if ((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
2332                         shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2333                         shadow->lamp = lamp;
2334                         BLI_addtail(shadows, shadow);
2335                 }
2336         }
2337 }
2338
2339 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
2340 {
2341         ListBase shadows;
2342         View3DShadow *shadow;
2343         Scene *sce_iter;
2344         Base *base;
2345         Object *ob;
2346         
2347         shadows.first = shadows.last = NULL;
2348         
2349         /* update lamp transform and gather shadow lamps */
2350         for (SETLOOPER(scene, sce_iter, base)) {
2351                 ob = base->object;
2352                 
2353                 if (ob->type == OB_LAMP)
2354                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2355                 
2356                 if (ob->transflag & OB_DUPLI) {
2357                         DupliObject *dob;
2358                         ListBase *lb = object_duplilist(scene, ob, FALSE);
2359                         
2360                         for (dob = lb->first; dob; dob = dob->next)
2361                                 if (dob->ob->type == OB_LAMP)
2362                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2363                         
2364                         free_object_duplilist(lb);
2365                 }
2366         }
2367         
2368         /* render shadows after updating all lamps, nested object_duplilist
2369          * don't work correct since it's replacing object matrices */
2370         for (shadow = shadows.first; shadow; shadow = shadow->next) {
2371                 /* this needs to be done better .. */
2372                 float viewmat[4][4], winmat[4][4];
2373                 int drawtype, lay, winsize, flag2 = v3d->flag2;
2374                 ARegion ar = {NULL};
2375                 RegionView3D rv3d = {{{0}}};
2376                 
2377                 drawtype = v3d->drawtype;
2378                 lay = v3d->lay;
2379                 
2380                 v3d->drawtype = OB_SOLID;
2381                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2382                 v3d->flag2 &= ~V3D_SOLID_TEX;
2383                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2384                 
2385                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2386
2387                 ar.regiondata = &rv3d;
2388                 ar.regiontype = RGN_TYPE_WINDOW;
2389                 rv3d.persp = RV3D_CAMOB;
2390                 copy_m4_m4(rv3d.winmat, winmat);
2391                 copy_m4_m4(rv3d.viewmat, viewmat);
2392                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2393                 mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2394                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2395
2396                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
2397                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat, FALSE);
2398                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2399                 
2400                 v3d->drawtype = drawtype;
2401                 v3d->lay = lay;
2402                 v3d->flag2 = flag2;
2403         }
2404         
2405         BLI_freelistN(&shadows);
2406 }
2407
2408 /* *********************** customdata **************** */
2409
2410 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2411 {
2412         CustomDataMask mask = 0;
2413
2414         if (ELEM(v3d->drawtype, OB_TEXTURE, OB_MATERIAL) ||
2415             ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
2416         {
2417                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2418
2419                 if (BKE_scene_use_new_shading_nodes(scene)) {
2420                         if (v3d->drawtype == OB_MATERIAL)
2421                                 mask |= CD_MASK_ORCO;
2422                 }
2423                 else {
2424                         if (scene->gm.matmode == GAME_MAT_GLSL)
2425                                 mask |= CD_MASK_ORCO;
2426                 }
2427         }
2428
2429         return mask;
2430 }
2431
2432 CustomDataMask ED_view3d_object_datamask(Scene *scene)
2433 {
2434         Object *ob = scene->basact ? scene->basact->object : NULL;
2435         CustomDataMask mask = 0;
2436
2437         if (ob) {
2438                 /* check if we need tfaces & mcols due to face select or texture paint */
2439                 if (paint_facesel_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2440                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2441                 }
2442
2443                 /* check if we need mcols due to vertex paint or weightpaint */
2444                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2445                         mask |= CD_MASK_MCOL;
2446                 }
2447
2448                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2449                         mask |= CD_MASK_PREVIEW_MCOL;
2450                 }
2451
2452                 if (ob->mode & OB_MODE_EDIT)
2453                         mask |= CD_MASK_MVERT_SKIN;
2454         }
2455
2456         return mask;
2457 }
2458
2459 /* goes over all modes and view3d settings */
2460 CustomDataMask ED_view3d_screen_datamask(bScreen *screen)
2461 {
2462         Scene *scene = screen->scene;
2463         CustomDataMask mask = CD_MASK_BAREMESH;
2464         ScrArea *sa;
2465         
2466         /* check if we need tfaces & mcols due to view mode */
2467         for (sa = screen->areabase.first; sa; sa = sa->next) {
2468                 if (sa->spacetype == SPACE_VIEW3D) {
2469                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2470                 }
2471         }
2472
2473         mask |= ED_view3d_object_datamask(scene);
2474
2475         return mask;
2476 }
2477
2478 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2479 {
2480         RegionView3D *rv3d = ar->regiondata;
2481
2482         /* setup window matrices */
2483         if (winmat)
2484                 copy_m4_m4(rv3d->winmat, winmat);
2485         else
2486                 setwinmatrixview3d(ar, v3d, NULL);
2487
2488         /* setup view matrix */
2489         if (viewmat)
2490                 copy_m4_m4(rv3d->viewmat, viewmat);
2491         else
2492                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2493
2494         /* update utilitity matrices */
2495         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2496         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2497         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2498
2499         /* calculate pixelsize factor once, is used for lamps and obcenters */
2500         {
2501                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2502                  * because of float point precision problems at large values [#23908] */
2503                 float v1[3], v2[3];
2504                 float len_px, len_sc;
2505
2506                 v1[0] = rv3d->persmat[0][0];
2507                 v1[1] = rv3d->persmat[1][0];
2508                 v1[2] = rv3d->persmat[2][0];
2509
2510                 v2[0] = rv3d->persmat[0][1];
2511                 v2[1] = rv3d->persmat[1][1];
2512                 v2[2] = rv3d->persmat[2][1];
2513
2514                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
2515                 len_sc = (float)MAX2(ar->winx, ar->winy);
2516
2517                 rv3d->pixsize = len_px / len_sc;
2518         }
2519 }
2520
2521 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2522 {
2523         RegionView3D *rv3d = ar->regiondata;
2524
2525         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
2526
2527         /* set for opengl */
2528         glMatrixMode(GL_PROJECTION);
2529         glLoadMatrixf(rv3d->winmat);
2530         glMatrixMode(GL_MODELVIEW);
2531         glLoadMatrixf(rv3d->viewmat);
2532 }
2533
2534 void ED_view3d_draw_offscreen_init(Scene *scene, View3D *v3d)
2535 {
2536         /* shadow buffers, before we setup matrices */
2537         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2538                 gpu_update_lamps_shadows(scene, v3d);
2539 }
2540
2541 /* ED_view3d_draw_offscreen_init should be called before this to initialize
2542  * stuff like shadow buffers
2543  */
2544 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
2545                               float viewmat[4][4], float winmat[4][4], int do_bgpic)
2546 {
2547         RegionView3D *rv3d = ar->regiondata;
2548         Base *base;
2549         int bwinx, bwiny;
2550         rcti brect;
2551
2552         glPushMatrix();
2553
2554         /* set temporary new size */
2555         bwinx = ar->winx;
2556         bwiny = ar->winy;
2557         brect = ar->winrct;
2558         
2559         ar->winx = winx;
2560         ar->winy = winy;
2561         ar->winrct.xmin = 0;
2562         ar->winrct.ymin = 0;
2563         ar->winrct.xmax = winx;
2564         ar->winrct.ymax = winy;
2565
2566         /* set theme */
2567         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
2568         
2569         /* set flags */
2570         G.f |= G_RENDER_OGL;
2571
2572         /* free images which can have changed on frame-change
2573          * warning! can be slow so only free animated images - campbell */
2574         GPU_free_images_anim();
2575
2576         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2577
2578         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2579
2580         /* setup view matrices */
2581         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2582
2583         if (rv3d->rflag & RV3D_CLIPPING)
2584                 view3d_draw_clipping(rv3d);
2585
2586         /* set zbuffer */
2587         if (v3d->drawtype > OB_WIRE) {
2588                 v3d->zbuf = TRUE;
2589                 glEnable(GL_DEPTH_TEST);
2590         }
2591         else
2592                 v3d->zbuf = FALSE;
2593
2594         /* important to do before clipping */
2595         if (do_bgpic) {
2596                 view3d_draw_bgpic_test(scene, ar, v3d, FALSE, FALSE);
2597         }
2598
2599         if (rv3d->rflag & RV3D_CLIPPING)
2600                 ED_view3d_clipping_set(rv3d);
2601
2602         /* draw set first */
2603         if (scene->set) {
2604                 Scene *sce_iter;
2605                 for (SETLOOPER(scene->set, sce_iter, base)) {
2606                         if (v3d->lay & base->lay) {
2607                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2608                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
2609                                 
2610                                 if (base->object->transflag & OB_DUPLI)
2611                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2612                         }
2613                 }
2614         }
2615         
2616         /* then draw not selected and the duplis, but skip editmode object */
2617         for (base = scene->base.first; base; base = base->next) {
2618                 if (v3d->lay & base->lay) {
2619                         /* dupli drawing */
2620                         if (base->object->transflag & OB_DUPLI)
2621                                 draw_dupli_objects(scene, ar, v3d, base);
2622
2623                         draw_object(scene, ar, v3d, base, 0);
2624                 }
2625         }
2626
2627         /* must be before xray draw which clears the depth buffer */
2628         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2629                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
2630                 draw_gpencil_view3d(scene, v3d, ar, TRUE);
2631                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
2632         }
2633
2634         /* transp and X-ray afterdraw stuff */
2635         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, ar, v3d);
2636         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, ar, v3d, 1);       /* clears zbuffer if it is used! */
2637         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
2638
2639         if (rv3d->rflag & RV3D_CLIPPING)
2640                 ED_view3d_clipping_disable();
2641
2642         /* important to do after clipping */
2643         if (do_bgpic) {
2644                 view3d_draw_bgpic_test(scene, ar, v3d, TRUE, FALSE);
2645         }
2646
2647         /* cleanup */
2648         if (v3d->zbuf) {
2649                 v3d->zbuf = FALSE;
2650                 glDisable(GL_DEPTH_TEST);
2651         }
2652
2653         /* draw grease-pencil stuff */
2654         ED_region_pixelspace(ar);
2655
2656
2657         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2658                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2659                 draw_gpencil_view3d(scene, v3d, ar, FALSE);
2660         }
2661
2662         /* freeing the images again here could be done after the operator runs, leaving for now */
2663         GPU_free_images_anim();
2664
2665         /* restore size */
2666         ar->winx = bwinx;
2667         ar->winy = bwiny;
2668         ar->winrct = brect;
2669
2670         glPopMatrix();
2671
2672         /* XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell */
2673         glColor4ub(255, 255, 255, 255);
2674
2675         G.f &= ~G_RENDER_OGL;
2676 }
2677
2678 /* get a color used for offscreen sky, returns color in sRGB space */
2679 void ED_view3d_offscreen_sky_color_get(Scene *scene, float sky_color[3])
2680 {
2681         if (scene->world)
2682                 linearrgb_to_srgb_v3_v3(sky_color, &scene->world->horr);
2683         else
2684                 UI_GetThemeColor3fv(TH_BACK, sky_color);
2685 }
2686
2687 static void offscreen_imbuf_add_sky(ImBuf *ibuf, Scene *scene)
2688 {
2689         float sky_color[3];
2690
2691         ED_view3d_offscreen_sky_color_get(scene, sky_color);
2692
2693         if (ibuf->rect_float)
2694                 IMB_alpha_under_color_float(ibuf->rect_float, ibuf->x, ibuf->y, sky_color);
2695         else
2696                 IMB_alpha_under_color_byte((unsigned char *) ibuf->rect, ibuf->x, ibuf->y, sky_color);
2697 }
2698
2699 /* utility func for ED_view3d_draw_offscreen */
2700 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey, unsigned int flag,
2701                                       int draw_background, int alpha_mode, char err_out[256])
2702 {
2703         RegionView3D *rv3d = ar->regiondata;
2704         ImBuf *ibuf;
2705         GPUOffScreen *ofs;
2706         
2707         /* state changes make normal drawing go weird otherwise */
2708         glPushAttrib(GL_LIGHTING_BIT);
2709
2710         /* bind */
2711         ofs = GPU_offscreen_create(sizex, sizey, err_out);
2712         if (ofs == NULL)
2713                 return NULL;
2714
2715         ED_view3d_draw_offscreen_init(scene, v3d);
2716
2717         GPU_offscreen_bind(ofs);
2718
2719         /* render 3d view */
2720         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2721                 CameraParams params;
2722
2723                 BKE_camera_params_init(&params);
2724                 BKE_camera_params_from_object(&params, v3d->camera);
2725                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2726                 BKE_camera_params_compute_matrix(&params);
2727
2728                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, params.winmat, draw_background);
2729         }
2730         else {
2731                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL, draw_background);
2732         }
2733
2734         /* read in pixels & stamp */
2735         ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2736
2737         if (ibuf->rect_float)
2738                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2739         else if (ibuf->rect)
2740                 GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2741
2742         if (alpha_mode == R_ADDSKY)
2743                 offscreen_imbuf_add_sky(ibuf, scene);
2744
2745         /* unbind */
2746         GPU_offscreen_unbind(ofs);
2747         GPU_offscreen_free(ofs);
2748
2749         glPopAttrib();
2750         
2751         if (ibuf->rect_float && ibuf->rect)
2752                 IMB_rect_from_float(ibuf);
2753         
2754         return ibuf;
2755 }
2756
2757 /* creates own 3d views, used by the sequencer */
2758 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height, unsigned int flag, int drawtype,
2759                                              int use_solid_tex, int draw_background, int alpha_mode, char err_out[256])
2760 {
2761         View3D v3d = {NULL};
2762         ARegion ar = {NULL};
2763         RegionView3D rv3d = {{{0}}};
2764
2765         /* connect data */
2766         v3d.regionbase.first = v3d.regionbase.last = &ar;
2767         ar.regiondata = &rv3d;
2768         ar.regiontype = RGN_TYPE_WINDOW;
2769
2770         v3d.camera = camera;
2771         v3d.lay = scene->lay;
2772         v3d.drawtype = drawtype;
2773         v3d.flag2 = V3D_RENDER_OVERRIDE;
2774
2775         if (use_solid_tex)
2776                 v3d.flag2 |= V3D_SOLID_TEX;
2777
2778         rv3d.persp = RV3D_CAMOB;
2779
2780         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2781         normalize_m4(rv3d.viewinv);
2782         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2783
2784         {
2785                 CameraParams params;
2786
2787                 BKE_camera_params_init(&params);
2788                 BKE_camera_params_from_object(&params, v3d.camera);
2789                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2790                 BKE_camera_params_compute_matrix(&params);
2791
2792                 copy_m4_m4(rv3d.winmat, params.winmat);
2793                 v3d.near = params.clipsta;
2794                 v3d.far = params.clipend;
2795                 v3d.lens = params.lens;
2796         }
2797
2798         mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2799         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2800
2801         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag,
2802                                               draw_background, alpha_mode, err_out);
2803
2804         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2805 }
2806
2807
2808 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2809  * which currently gets called during SCREEN_OT_animation_step.
2810  */
2811 static void draw_viewport_fps(Scene *scene, rcti *rect)
2812 {
2813         ScreenFrameRateInfo *fpsi = scene->fps_info;
2814         float fps;
2815         char printable[16];
2816         int i, tot;
2817         
2818         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2819                 return;
2820         
2821         printable[0] = '\0';
2822         
2823 #if 0
2824         /* this is too simple, better do an average */
2825         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
2826 #else
2827         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
2828         
2829         for (i = 0, tot = 0, fps = 0.0f; i < REDRAW_FRAME_AVERAGE; i++) {
2830                 if (fpsi->redrawtimes_fps[i]) {
2831                         fps += fpsi->redrawtimes_fps[i];
2832                         tot++;
2833                 }
2834         }
2835         if (tot) {
2836                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2837                 
2838                 //fpsi->redrawtime_index++;
2839                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2840                 //      fpsi->redrawtime = 0;
2841                 
2842                 fps = fps / tot;
2843         }
2844 #endif
2845
2846         /* is this more then half a frame behind? */
2847         if (fps + 0.5f < (float)(FPS)) {
2848                 UI_ThemeColor(TH_REDALERT);
2849                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2850         }
2851         else {
2852                 UI_ThemeColor(TH_TEXT_HI);
2853                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps + 0.5f));
2854         }
2855         
2856         BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
2857 }
2858
2859 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit);
2860
2861 static int view3d_main_area_do_render_draw(const bContext *C)
2862 {
2863         Scene *scene = CTX_data_scene(C);
2864         RenderEngineType *type = RE_engines_find(scene->r.engine);
2865
2866         return (type && type->view_update && type->view_draw);
2867 }
2868
2869 static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw_border)
2870 {
2871         Scene *scene = CTX_data_scene(C);
2872         View3D *v3d = CTX_wm_view3d(C);
2873         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2874         RenderEngineType *type;
2875         GLint scissor[4];
2876
2877         /* create render engine */
2878         if (!rv3d->render_engine) {
2879                 RenderEngine *engine;
2880
2881                 type = RE_engines_find(scene->r.engine);
2882
2883                 if (!(type->view_update && type->view_draw))
2884                         return 0;
2885
2886                 engine = RE_engine_create_ex(type, TRUE);
2887
2888                 engine->tile_x = scene->r.tilex;
2889                 engine->tile_y = scene->r.tiley;
2890
2891                 type->view_update(engine, C);
2892
2893                 rv3d->render_engine = engine;
2894         }
2895
2896         /* setup view matrices */
2897         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2898
2899         /* background draw */
2900         ED_region_pixelspace(ar);
2901
2902         if (draw_border) {
2903                 /* for border draw, we only need to clear a subset of the 3d view */
2904                 rctf viewborder;
2905                 rcti cliprct;
2906
2907                 if (rv3d->persp == RV3D_CAMOB) {
2908                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, FALSE);
2909
2910                         cliprct.xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
2911                         cliprct.ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
2912                         cliprct.xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
2913                         cliprct.ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
2914                 }
2915                 else {
2916                         cliprct.xmin = v3d->render_border.xmin * ar->winx;
2917                         cliprct.xmax = v3d->render_border.xmax * ar->winx;
2918                         cliprct.ymin = v3d->render_border.ymin * ar->winy;
2919                         cliprct.ymax = v3d->render_border.ymax * ar->winy;
2920                 }
2921
2922                 cliprct.xmin += ar->winrct.xmin;
2923                 cliprct.xmax += ar->winrct.xmin;
2924                 cliprct.ymin += ar->winrct.ymin;
2925                 cliprct.ymax += ar->winrct.ymin;
2926
2927                 cliprct.xmin = CLAMPIS(cliprct.xmin, ar->winrct.xmin, ar->winrct.xmax);
2928                 cliprct.ymin = CLAMPIS(cliprct.ymin, ar->winrct.ymin, ar->winrct.ymax);
2929                 cliprct.xmax = CLAMPIS(cliprct.xmax, ar->winrct.xmin, ar->winrct.xmax);
2930                 cliprct.ymax = CLAMPIS(cliprct.ymax, ar->winrct.ymin, ar->winrct.ymax);
2931
2932                 if (cliprct.xmax > cliprct.xmin && cliprct.ymax > cliprct.ymin) {
2933                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
2934                         glScissor(cliprct.xmin, cliprct.ymin, BLI_rcti_size_x(&cliprct), BLI_rcti_size_y(&cliprct));
2935                 }
2936                 else
2937                         return 0;
2938         }
2939
2940         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2941         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2942
2943         if (v3d->flag & V3D_DISPBGPICS)
2944                 view3d_draw_bgpic(scene, ar, v3d, FALSE, TRUE);
2945         else
2946                 fdrawcheckerboard(0, 0, ar->winx, ar->winy);
2947
2948         /* render result draw */
2949         type = rv3d->render_engine->type;
2950         type->view_draw(rv3d->render_engine, C);
2951
2952         if (v3d->flag & V3D_DISPBGPICS)
2953                 view3d_draw_bgpic(scene, ar, v3d, TRUE, TRUE);
2954
2955         if (draw_border) {
2956                 /* restore scissor as it was before */
2957                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2958         }
2959
2960         return 1;
2961 }
2962
2963 static void view3d_main_area_draw_engine_info(RegionView3D *rv3d, ARegion *ar)
2964 {
2965         if (!rv3d->render_engine || !rv3d->render_engine->text)
2966                 return;
2967
2968         ED_region_info_draw(ar, rv3d->render_engine->text, 1, 0.25);
2969 }
2970
2971 /*
2972  * Function to clear the view
2973  */
2974 static void view3d_main_area_clear(Scene *scene, View3D *v3d, ARegion *ar)
2975 {
2976         /* clear background */
2977         if (scene->world && (v3d->flag2 & V3D_RENDER_OVERRIDE)) {  /* clear with solid color */
2978                 if (scene->world->skytype & WO_SKYBLEND) {  /* blend sky */
2979                         int x, y;
2980                         float col_hor[3];
2981                         float col_zen[3];
2982
2983 #define VIEWGRAD_RES_X 16
2984 #define VIEWGRAD_RES_Y 16
2985
2986                         GLubyte grid_col[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][4];
2987                         static float   grid_pos[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][2];
2988                         static GLushort indices[VIEWGRAD_RES_X - 1][VIEWGRAD_RES_X - 1][4];
2989                         static char buf_calculated = FALSE;
2990
2991                         IMB_colormanagement_pixel_to_display_space_v3(col_hor, &scene->world->horr, &scene->view_settings,
2992                                                                       &scene->display_settings);
2993                         IMB_colormanagement_pixel_to_display_space_v3(col_zen, &scene->world->zenr, &scene->view_settings,
2994                                                                       &scene->display_settings);
2995
2996                         glClear(GL_DEPTH_BUFFER_BIT);
2997
2998                         glMatrixMode(GL_PROJECTION);
2999                         glPushMatrix();
3000                         glLoadIdentity();
3001                         glMatrixMode(GL_MODELVIEW);
3002                         glPushMatrix();
3003                         glLoadIdentity();
3004
3005                         glShadeModel(GL_SMOOTH);
3006
3007                         /* calculate buffers the first time only */
3008                         if (!buf_calculated) {
3009                                 for (x = 0; x < VIEWGRAD_RES_X; x++) {
3010                                         for (y = 0; y < VIEWGRAD_RES_Y; y++) {
3011                                                 const float xf = (float)x / (float)(VIEWGRAD_RES_X - 1);
3012                                                 const float yf = (float)y / (float)(VIEWGRAD_RES_Y - 1);
3013
3014                                                 /* -1..1 range */
3015                                                 grid_pos[x][y][0] = (xf - 0.5f) * 2.0f;
3016                                                 grid_pos[x][y][1] = (yf - 0.5f) * 2.0f;
3017                                         }
3018                                 }
3019
3020                                 for (x = 0; x < VIEWGRAD_RES_X - 1; x++) {
3021                                         for (y = 0; y < VIEWGRAD_RES_Y - 1; y++) {
3022                                                 indices[x][y][0] = x * VIEWGRAD_RES_X + y;
3023                                                 indices[x][y][1] = x * VIEWGRAD_RES_X + y + 1;
3024                                                 indices[x][y][2] = (x + 1) * VIEWGRAD_RES_X + y + 1;
3025                                                 indices[x][y][3] = (x + 1) * VIEWGRAD_RES_X + y;
3026                                         }
3027                                 }
3028
3029                                 buf_calculated = TRUE;
3030                         }
3031
3032                         for (x = 0; x < VIEWGRAD_RES_X; x++) {
3033                                 for (y = 0; y < VIEWGRAD_RES_Y; y++) {
3034                                         const float xf = (float)x / (float)(VIEWGRAD_RES_X - 1);
3035                                         const float yf = (float)y / (float)(VIEWGRAD_RES_Y - 1);
3036                                         const float mval[2] = {xf * (float)ar->winx, yf * ar->winy};
3037                                         const float z_up[3] = {0.0f, 0.0f, 1.0f};
3038                                         float out[3];
3039                                         GLubyte *col_ub = grid_col[x][y];
3040
3041                                         float col_fac;
3042                                         float col_fl[3];
3043
3044                                         ED_view3d_win_to_vector(ar, mval, out);
3045
3046                                         if (scene->world->skytype & WO_SKYPAPER) {
3047                                                 if (scene->world->skytype & WO_SKYREAL) {
3048                                                         col_fac = fabsf(((float)y / (float)VIEWGRAD_RES_Y) - 0.5f) * 2.0f;
3049                                                 }
3050                                                 else {
3051                                                         col_fac = (float)y / (float)VIEWGRAD_RES_Y;
3052                                                 }
3053                                         }
3054                                         else {
3055                                                 if (scene->world->skytype & WO_SKYREAL) {
3056                                                         col_fac = fabsf((angle_normalized_v3v3(z_up, out) / (float)M_PI) - 0.5f) * 2.0f;
3057                                                 }
3058                                                 else {
3059                                                         col_fac = 1.0f - (angle_normalized_v3v3(z_up, out) / (float)M_PI);
3060                                                 }
3061                                         }
3062
3063                                         interp_v3_v3v3(col_fl, col_hor, col_zen, col_fac);
3064
3065                                         rgb_float_to_uchar(col_ub, col_fl);
3066                                         col_ub[3] = 0;
3067                                 }
3068                         }
3069
3070                         glEnableClientState(GL_VERTEX_ARRAY);
3071                         glEnableClientState(GL_COLOR_ARRAY);
3072