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