Merged changes in the trunk up to revision 46045.
[blender-staging.git] / source / blender / editors / space_view3d / drawobject.c
index 0dfb2f032f21d7c02d363eae6e78d5e4caec7350..4c714b936183772511bb104399507dc59961c3ec 100644 (file)
@@ -39,6 +39,7 @@
 #include "DNA_lamp_types.h"
 #include "DNA_lattice_types.h"
 #include "DNA_material_types.h"
+#include "DNA_mesh_types.h"
 #include "DNA_meshdata_types.h"
 #include "DNA_meta_types.h"
 #include "DNA_scene_types.h"
 #include "BLI_utildefines.h"
 #include "BLI_blenlib.h"
 #include "BLI_math.h"
-#include "BLI_editVert.h"
 #include "BLI_edgehash.h"
 #include "BLI_rand.h"
 #include "BLI_utildefines.h"
 
-#include "BKE_anim.h"                  //for the where_on_path function
+#include "BKE_anim.h"  //for the where_on_path function
+#include "BKE_armature.h"
 #include "BKE_camera.h"
 #include "BKE_constraint.h" // for the get_constraint_target function
 #include "BKE_curve.h"
 #include "wm_subwindow.h"
 #include "BLF_api.h"
 
-#include "view3d_intern.h"     // own include
-
-
-/* this condition has been made more complex since editmode can draw textures */
-#define CHECK_OB_DRAWTEXTURE(vd, dt)                                          \
-       ((ELEM(vd->drawtype, OB_TEXTURE, OB_MATERIAL) && dt>OB_SOLID) ||          \
-       (vd->drawtype==OB_SOLID && vd->flag2 & V3D_SOLID_TEX))
+#include "view3d_intern.h"  // own include
 
 typedef enum eWireDrawMode {
-       OBDRAW_WIRE_OFF= 0,
-       OBDRAW_WIRE_ON= 1,
-       OBDRAW_WIRE_ON_DEPTH= 2
+       OBDRAW_WIRE_OFF = 0,
+       OBDRAW_WIRE_ON = 1,
+       OBDRAW_WIRE_ON_DEPTH = 2
 } eWireDrawMode;
 
 /* user data structures for derived mesh callbacks */
@@ -132,6 +127,7 @@ typedef struct foreachScreenEdge_userData {
        void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index);
        void *userData;
        ViewContext vc;
+       rcti win_rect; /* copy of: vc.ar->winx/winy, use for faster tests, minx/y will always be 0 */
        eV3DClipTest clipVerts;
 } foreachScreenEdge_userData;
 
@@ -156,7 +152,7 @@ typedef struct drawDMEdgesSel_userData {
 } drawDMEdgesSel_userData;
 
 typedef struct drawDMFacesSel_userData {
-       unsigned char *cols[3];
+       unsigned char *cols[4];
 
        DerivedMesh *dm; /* BMESH BRANCH ONLY */
        BMEditMesh *em;  /* BMESH BRANCH ONLY */
@@ -182,22 +178,36 @@ static void drawcircle_size(float size);
 static void draw_empty_sphere(float size);
 static void draw_empty_cone(float size);
 
+/* this condition has been made more complex since editmode can draw textures */
+static int check_object_draw_texture(Scene *scene, View3D *v3d, int drawtype)
+{
+       /* texture and material draw modes */
+       if (ELEM(v3d->drawtype, OB_TEXTURE, OB_MATERIAL) && drawtype > OB_SOLID)
+               return TRUE;
+
+       /* textured solid */
+       if (v3d->drawtype == OB_SOLID && (v3d->flag2 & V3D_SOLID_TEX) && !scene_use_new_shading_nodes(scene))
+               return TRUE;
+       
+       return FALSE;
+}
+
 static int check_ob_drawface_dot(Scene *sce, View3D *vd, char dt)
 {
-       if((sce->toolsettings->selectmode & SCE_SELECT_FACE) == 0)
+       if ((sce->toolsettings->selectmode & SCE_SELECT_FACE) == 0)
                return 0;
 
-       if(G.f & G_BACKBUFSEL)
+       if (G.f & G_BACKBUFSEL)
                return 0;
 
-       if((vd->flag & V3D_ZBUF_SELECT) == 0)
+       if ((vd->flag & V3D_ZBUF_SELECT) == 0)
                return 1;
 
-       /* if its drawing textures with zbuf sel, then dont draw dots */
-       if(dt==OB_TEXTURE && vd->drawtype==OB_TEXTURE)
+       /* if its drawing textures with zbuf sel, then don't draw dots */
+       if (dt == OB_TEXTURE && vd->drawtype == OB_TEXTURE)
                return 0;
 
-       if(vd->drawtype>=OB_SOLID && vd->flag2 & V3D_SOLID_TEX)
+       if ((vd->drawtype >= OB_SOLID) && (vd->flag2 & V3D_SOLID_TEX))
                return 0;
 
        return 1;
@@ -206,35 +216,35 @@ static int check_ob_drawface_dot(Scene *sce, View3D *vd, char dt)
 /* ************* only use while object drawing **************
  * or after running ED_view3d_init_mats_rv3d
  * */
-static void view3d_project_short_clip(ARegion *ar, const float vec[3], short adr[2], int local)
+static void view3d_project_short_clip(ARegion *ar, const float vec[3], short adr[2], int is_local)
 {
-       RegionView3D *rv3d= ar->regiondata;
+       RegionView3D *rv3d = ar->regiondata;
        float fx, fy, vec4[4];
        
-       adr[0]= IS_CLIPPED;
+       adr[0] = IS_CLIPPED;
        
        /* clipplanes in eye space */
-       if(rv3d->rflag & RV3D_CLIPPING) {
-               if(ED_view3d_test_clipping(rv3d, vec, local))
+       if (rv3d->rflag & RV3D_CLIPPING) {
+               if (ED_view3d_clipping_test(rv3d, vec, is_local))
                        return;
        }
        
        copy_v3_v3(vec4, vec);
-       vec4[3]= 1.0;
+       vec4[3] = 1.0;
        
        mul_m4_v4(rv3d->persmatob, vec4);
        
        /* clipplanes in window space */
-       if( vec4[3] > (float)BL_NEAR_CLIP ) {   /* is the NEAR clipping cutoff for picking */
-               fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
+       if (vec4[3] > (float)BL_NEAR_CLIP) {    /* is the NEAR clipping cutoff for picking */
+               fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
                
-               if( fx>0 && fx<ar->winx) {
+               if (fx > 0 && fx < ar->winx) {
                        
-                       fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
+                       fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
                        
-                       if(fy > 0.0f && fy < (float)ar->winy) {
-                               adr[0]= (short)floorf(fx);
-                               adr[1]= (short)floorf(fy);
+                       if (fy > 0.0f && fy < (float)ar->winy) {
+                               adr[0] = (short)floorf(fx);
+                               adr[1] = (short)floorf(fy);
                        }
                }
        }
@@ -243,63 +253,63 @@ static void view3d_project_short_clip(ARegion *ar, const float vec[3], short adr
 /* BMESH NOTE: this function is unused in bmesh only */
 
 /* only use while object drawing */
-static void UNUSED_FUNCTION(view3d_project_short_noclip)(ARegion *ar, const float vec[3], short adr[2])
+static void UNUSED_FUNCTION(view3d_project_short_noclip) (ARegion * ar, const float vec[3], short adr[2])
 {
-       RegionView3D *rv3d= ar->regiondata;
+       RegionView3D *rv3d = ar->regiondata;
        float fx, fy, vec4[4];
        
-       adr[0]= IS_CLIPPED;
+       adr[0] = IS_CLIPPED;
        
        copy_v3_v3(vec4, vec);
-       vec4[3]= 1.0;
+       vec4[3] = 1.0;
        
        mul_m4_v4(rv3d->persmatob, vec4);
        
-       if( vec4[3] > (float)BL_NEAR_CLIP ) {   /* is the NEAR clipping cutoff for picking */
-               fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
+       if (vec4[3] > (float)BL_NEAR_CLIP) {    /* is the NEAR clipping cutoff for picking */
+               fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
                
-               if( fx>-32700 && fx<32700) {
+               if (fx > -32700 && fx < 32700) {
                        
-                       fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
+                       fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
                        
-                       if(fy > -32700.0f && fy < 32700.0f) {
-                               adr[0]= (short)floorf(fx);
-                               adr[1]= (short)floorf(fy);
+                       if (fy > -32700.0f && fy < 32700.0f) {
+                               adr[0] = (short)floorf(fx);
+                               adr[1] = (short)floorf(fy);
                        }
                }
        }
 }
 
 /* same as view3d_project_short_clip but use persmat instead of persmatob for projection */
-static void view3d_project_short_clip_persmat(ARegion *ar, float *vec, short adr[2], int local)
+static void view3d_project_short_clip_persmat(ARegion *ar, const float vec[3], short adr[2], int is_local)
 {
-       RegionView3D *rv3d= ar->regiondata;
+       RegionView3D *rv3d = ar->regiondata;
        float fx, fy, vec4[4];
 
-       adr[0]= IS_CLIPPED;
+       adr[0] = IS_CLIPPED;
 
        /* clipplanes in eye space */
-       if(rv3d->rflag & RV3D_CLIPPING) {
-               if(ED_view3d_test_clipping(rv3d, vec, local))
+       if (rv3d->rflag & RV3D_CLIPPING) {
+               if (ED_view3d_clipping_test(rv3d, vec, is_local))
                        return;
        }
 
        copy_v3_v3(vec4, vec);
-       vec4[3]= 1.0;
+       vec4[3] = 1.0;
 
        mul_m4_v4(rv3d->persmat, vec4);
 
        /* clipplanes in window space */
-       if( vec4[3] > (float)BL_NEAR_CLIP ) {   /* is the NEAR clipping cutoff for picking */
-               fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
+       if (vec4[3] > (float)BL_NEAR_CLIP) {    /* is the NEAR clipping cutoff for picking */
+               fx = (ar->winx / 2) * (1 + vec4[0] / vec4[3]);
 
-               if( fx>0 && fx<ar->winx) {
+               if (fx > 0 && fx < ar->winx) {
 
-                       fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
+                       fy = (ar->winy / 2) * (1 + vec4[1] / vec4[3]);
 
-                       if(fy > 0.0f && fy < (float)ar->winy) {
-                               adr[0]= (short)floorf(fx);
-                               adr[1]= (short)floorf(fy);
+                       if (fy > 0.0f && fy < (float)ar->winy) {
+                               adr[0] = (short)floorf(fx);
+                               adr[1] = (short)floorf(fy);
                        }
                }
        }
@@ -310,15 +320,15 @@ static void view3d_project_short_clip_persmat(ARegion *ar, float *vec, short adr
 
 int draw_glsl_material(Scene *scene, Object *ob, View3D *v3d, int dt)
 {
-       if(!GPU_glsl_support())
+       if (!GPU_glsl_support())
                return 0;
-       if(G.f & G_PICKSEL)
+       if (G.f & G_PICKSEL)
                return 0;
-       if(!CHECK_OB_DRAWTEXTURE(v3d, dt))
+       if (!check_object_draw_texture(scene, v3d, dt))
                return 0;
-       if(ob==OBACT && (ob && ob->mode & OB_MODE_WEIGHT_PAINT))
+       if (ob == OBACT && (ob && ob->mode & OB_MODE_WEIGHT_PAINT))
                return 0;
-       if(scene_use_new_shading_nodes(scene))
+       if (scene_use_new_shading_nodes(scene))
                return 0;
        
        return (scene->gm.matmode == GAME_MAT_GLSL) && (dt > OB_SOLID);
@@ -326,23 +336,22 @@ int draw_glsl_material(Scene *scene, Object *ob, View3D *v3d, int dt)
 
 static int check_alpha_pass(Base *base)
 {
-       if(base->flag & OB_FROMDUPLI)
+       if (base->flag & OB_FROMDUPLI)
                return 0;
 
-       if(G.f & G_PICKSEL)
+       if (G.f & G_PICKSEL)
                return 0;
        
        return (base->object->dtx & OB_DRAWTRANSP);
 }
 
-       /***/
-static unsigned int colortab[24]=
-       {0x0,           0xFF88FF, 0xFFBBFF, 
-        0x403000,      0xFFFF88, 0xFFFFBB, 
-        0x104040,      0x66CCCC, 0x77CCCC, 
-        0x104010,      0x55BB55, 0x66FF66, 
-        0xFFFFFF
-};
+/***/
+static unsigned int colortab[24] =
+{0x0,       0xFF88FF, 0xFFBBFF,
+ 0x403000,  0xFFFF88, 0xFFFFBB,
+ 0x104040,  0x66CCCC, 0x77CCCC,
+ 0x104010,  0x55BB55, 0x66FF66,
+ 0xFFFFFF};
 
 
 static float cube[8][3] = {
@@ -356,7 +365,7 @@ static float cube[8][3] = {
        { 1.0,  1.0, -1.0},
 };
 
-/* ----------------- OpenGL Circle Drawing - Tables for Optimised Drawing Speed ------------------ */
+/* ----------------- OpenGL Circle Drawing - Tables for Optimized Drawing Speed ------------------ */
 /* 32 values of sin function (still same result!) */
 #define CIRCLE_RESOL 32
 
@@ -433,16 +442,16 @@ static const float cosval[CIRCLE_RESOL] = {
 
 static void draw_xyz_wire(const float c[3], float size, int axis)
 {
-       float v1[3]= {0.f, 0.f, 0.f}, v2[3] = {0.f, 0.f, 0.f};
+       float v1[3] = {0.f, 0.f, 0.f}, v2[3] = {0.f, 0.f, 0.f};
        float dim = size * 0.1f;
        float dx[3], dy[3], dz[3];
 
-       dx[0]=dim; dx[1]=0.f; dx[2]=0.f;
-       dy[0]=0.f; dy[1]=dim; dy[2]=0.f;
-       dz[0]=0.f; dz[1]=0.f; dz[2]=dim;
+       dx[0] = dim; dx[1] = 0.f; dx[2] = 0.f;
+       dy[0] = 0.f; dy[1] = dim; dy[2] = 0.f;
+       dz[0] = 0.f; dz[1] = 0.f; dz[2] = dim;
 
-       switch(axis) {
-               case 0:         /* x axis */
+       switch (axis) {
+               case 0:     /* x axis */
                        glBegin(GL_LINES);
                        
                        /* bottom left to top right */
@@ -464,7 +473,7 @@ static void draw_xyz_wire(const float c[3], float size, int axis)
                        
                        glEnd();
                        break;
-               case 1:         /* y axis */
+               case 1:     /* y axis */
                        glBegin(GL_LINES);
                        
                        /* bottom left to top right */
@@ -487,7 +496,7 @@ static void draw_xyz_wire(const float c[3], float size, int axis)
                        
                        glEnd();
                        break;
-               case 2:         /* z axis */
+               case 2:     /* z axis */
                        glBegin(GL_LINE_STRIP);
                        
                        /* start at top left */
@@ -520,107 +529,110 @@ static void draw_xyz_wire(const float c[3], float size, int axis)
 void drawaxes(float size, char drawtype)
 {
        int axis;
-       float v1[3]= {0.0, 0.0, 0.0};
-       float v2[3]= {0.0, 0.0, 0.0};
-       float v3[3]= {0.0, 0.0, 0.0};
+       float v1[3] = {0.0, 0.0, 0.0};
+       float v2[3] = {0.0, 0.0, 0.0};
+       float v3[3] = {0.0, 0.0, 0.0};
        
-       switch(drawtype) {
-       
-       case OB_PLAINAXES:
-               for (axis=0; axis<3; axis++) {
+       switch (drawtype) {
+
+               case OB_PLAINAXES:
+                       for (axis = 0; axis < 3; axis++) {
+                               glBegin(GL_LINES);
+
+                               v1[axis] = size;
+                               v2[axis] = -size;
+                               glVertex3fv(v1);
+                               glVertex3fv(v2);
+
+                               /* reset v1 & v2 to zero */
+                               v1[axis] = v2[axis] = 0.0f;
+
+                               glEnd();
+                       }
+                       break;
+               case OB_SINGLE_ARROW:
+
                        glBegin(GL_LINES);
-                       
-                       v1[axis]= size;
-                       v2[axis]= -size;
+                       /* in positive z direction only */
+                       v1[2] = size;
                        glVertex3fv(v1);
                        glVertex3fv(v2);
+                       glEnd();
 
-                       /* reset v1 & v2 to zero */
-                       v1[axis]= v2[axis]= 0.0f;
+                       /* square pyramid */
+                       glBegin(GL_TRIANGLES);
+
+                       v2[0] = size * 0.035f; v2[1] = size * 0.035f;
+                       v3[0] = size * -0.035f; v3[1] = size * 0.035f;
+                       v2[2] = v3[2] = size * 0.75f;
+
+                       for (axis = 0; axis < 4; axis++) {
+                               if (axis % 2 == 1) {
+                                       v2[0] = -v2[0];
+                                       v3[1] = -v3[1];
+                               }
+                               else {
+                                       v2[1] = -v2[1];
+                                       v3[0] = -v3[0];
+                               }
+
+                               glVertex3fv(v1);
+                               glVertex3fv(v2);
+                               glVertex3fv(v3);
 
-                       glEnd();
-               }
-               break;
-       case OB_SINGLE_ARROW:
-       
-               glBegin(GL_LINES);
-               /* in positive z direction only */
-               v1[2]= size;
-               glVertex3fv(v1);
-               glVertex3fv(v2);
-               glEnd();
-               
-               /* square pyramid */
-               glBegin(GL_TRIANGLES);
-               
-               v2[0]= size * 0.035f; v2[1] = size * 0.035f;
-               v3[0]= size * -0.035f; v3[1] = size * 0.035f;
-               v2[2]= v3[2]= size * 0.75f;
-               
-               for (axis=0; axis<4; axis++) {
-                       if (axis % 2 == 1) {
-                               v2[0] = -v2[0];
-                               v3[1] = -v3[1];
-                       } else {
-                               v2[1] = -v2[1];
-                               v3[0] = -v3[0];
                        }
-                       
-                       glVertex3fv(v1);
-                       glVertex3fv(v2);
-                       glVertex3fv(v3);
-                       
-               }
-               glEnd();
-               
-               break;
-       case OB_CUBE:
-               drawcube_size(size);
-               break;
-               
-       case OB_CIRCLE:
-               drawcircle_size(size);
-               break;
-       
-       case OB_EMPTY_SPHERE:
-               draw_empty_sphere(size);
-               break;
+                       glEnd();
+
+                       break;
+               case OB_CUBE:
+                       drawcube_size(size);
+                       break;
 
-       case OB_EMPTY_CONE:
-               draw_empty_cone(size);
-               break;
+               case OB_CIRCLE:
+                       drawcircle_size(size);
+                       break;
 
-       case OB_ARROWS:
-       default:
-               for (axis=0; axis<3; axis++) {
-                       const int arrow_axis= (axis==0) ? 1:0;
+               case OB_EMPTY_SPHERE:
+                       draw_empty_sphere(size);
+                       break;
 
-                       glBegin(GL_LINES);
-                       
-                       v2[axis]= size;
-                       glVertex3fv(v1);
-                       glVertex3fv(v2);
+               case OB_EMPTY_CONE:
+                       draw_empty_cone(size);
+                       break;
+
+               case OB_ARROWS:
+               default:
+               {
+                       for (axis = 0; axis < 3; axis++) {
+                               const int arrow_axis = (axis == 0) ? 1 : 0;
+
+                               glBegin(GL_LINES);
+
+                               v2[axis] = size;
+                               glVertex3fv(v1);
+                               glVertex3fv(v2);
                                
-                       v1[axis]= size*0.85f;
-                       v1[arrow_axis]= -size*0.08f;
-                       glVertex3fv(v1);
-                       glVertex3fv(v2);
+                               v1[axis] = size * 0.85f;
+                               v1[arrow_axis] = -size * 0.08f;
+                               glVertex3fv(v1);
+                               glVertex3fv(v2);
                                
-                       v1[arrow_axis]= size*0.08f;
-                       glVertex3fv(v1);
-                       glVertex3fv(v2);
-                       
-                       glEnd();
+                               v1[arrow_axis] = size * 0.08f;
+                               glVertex3fv(v1);
+                               glVertex3fv(v2);
+
+                               glEnd();
                                
-                       v2[axis]+= size*0.125f;
-                       
-                       draw_xyz_wire(v2, size, axis);
-                       
-                       
-                       /* reset v1 & v2 to zero */
-                       v1[arrow_axis]= v1[axis]= v2[axis]= 0.0f;
+                               v2[axis] += size * 0.125f;
+
+                               draw_xyz_wire(v2, size, axis);
+
+
+                               /* reset v1 & v2 to zero */
+                               v1[arrow_axis] = v1[axis] = v2[axis] = 0.0f;
+                       }
+                       break;
                }
-               break;
        }
 }
 
@@ -628,49 +640,49 @@ void drawaxes(float size, char drawtype)
 /* Function to draw an Image on a empty Object */
 static void draw_empty_image(Object *ob)
 {
-       Image *ima = (Image*)ob->data;
+       Image *ima = (Image *)ob->data;
        ImBuf *ibuf = ima ? BKE_image_get_ibuf(ima, NULL) : NULL;
 
        float scale, ofs_x, ofs_y, sca_x, sca_y;
        int ima_x, ima_y;
 
-       if(ibuf && (ibuf->rect == NULL) && (ibuf->rect_float != NULL)) {
+       if (ibuf && (ibuf->rect == NULL) && (ibuf->rect_float != NULL)) {
                IMB_rect_from_float(ibuf);
        }
 
        /* Get the buffer dimensions so we can fallback to fake ones */
-       if(ibuf && ibuf->rect) {
-               ima_x= ibuf->x;
-               ima_y= ibuf->y;
+       if (ibuf && ibuf->rect) {
+               ima_x = ibuf->x;
+               ima_y = ibuf->y;
        }
        else {
-               ima_x= 1;
-               ima_y= 1;
+               ima_x = 1;
+               ima_y = 1;
        }
 
        /* Get the image aspect even if the buffer is invalid */
-       if(ima) {
-               if(ima->aspx > ima->aspy) {
-                       sca_x= 1.0f;
-                       sca_y= ima->aspy / ima->aspx;
+       if (ima) {
+               if (ima->aspx > ima->aspy) {
+                       sca_x = 1.0f;
+                       sca_y = ima->aspy / ima->aspx;
                }
-               else if(ima->aspx < ima->aspy) {
-                       sca_x= ima->aspx / ima->aspy;
-                       sca_y= 1.0f;
+               else if (ima->aspx < ima->aspy) {
+                       sca_x = ima->aspx / ima->aspy;
+                       sca_y = 1.0f;
                }
                else {
-                       sca_x= 1.0f;
-                       sca_y= 1.0f;
+                       sca_x = 1.0f;
+                       sca_y = 1.0f;
                }
        }
        else {
-               sca_x= 1.0f;
-               sca_y= 1.0f;
+               sca_x = 1.0f;
+               sca_y = 1.0f;
        }
 
        /* Calculate the scale center based on objects origin */
-       ofs_x= ob->ima_ofs[0] * ima_x;
-       ofs_y= ob->ima_ofs[1] * ima_y;
+       ofs_x = ob->ima_ofs[0] * ima_x;
+       ofs_y = ob->ima_ofs[1] * ima_y;
 
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
@@ -679,12 +691,12 @@ static void draw_empty_image(Object *ob)
        glTranslatef(0.0f,  0.0f,  0.0f);
 
        /* Calculate Image scale */
-       scale= (ob->empty_drawsize / (float)MAX2(ima_x * sca_x, ima_y * sca_y));
+       scale = (ob->empty_drawsize / (float)MAX2(ima_x * sca_x, ima_y * sca_y));
 
        /* Set the object scale */
        glScalef(scale * sca_x, scale * sca_y, 1.0f);
 
-       if(ibuf && ibuf->rect) {
+       if (ibuf && ibuf->rect) {
                /* Setup GL params */
                glEnable(GL_BLEND);
                glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
@@ -717,16 +729,16 @@ static void draw_empty_image(Object *ob)
 static void circball_array_fill(float verts[CIRCLE_RESOL][3], const float cent[3], float rad, float tmat[][4])
 {
        float vx[3], vy[3];
-       float *viter= (float *)verts;
+       float *viter = (float *)verts;
        unsigned int a;
 
        mul_v3_v3fl(vx, tmat[0], rad);
        mul_v3_v3fl(vy, tmat[1], rad);
 
-       for (a=0; a < CIRCLE_RESOL; a++, viter += 3) {
-               viter[0]= cent[0] + sinval[a] * vx[0] + cosval[a] * vy[0];
-               viter[1]= cent[1] + sinval[a] * vx[1] + cosval[a] * vy[1];
-               viter[2]= cent[2] + sinval[a] * vx[2] + cosval[a] * vy[2];
+       for (a = 0; a < CIRCLE_RESOL; a++, viter += 3) {
+               viter[0] = cent[0] + sinval[a] * vx[0] + cosval[a] * vy[0];
+               viter[1] = cent[1] + sinval[a] * vx[1] + cosval[a] * vy[1];
+               viter[2] = cent[2] + sinval[a] * vx[2] + cosval[a] * vy[2];
        }
 }
 
@@ -745,16 +757,16 @@ void drawcircball(int mode, const float cent[3], float rad, float tmat[][4])
 /* circle for object centers, special_color is for library or ob users */
 static void drawcentercircle(View3D *v3d, RegionView3D *rv3d, const float co[3], int selstate, int special_color)
 {
-       const float size= ED_view3d_pixel_size(rv3d, co) * (float)U.obcenter_dia * 0.5f;
+       const float size = ED_view3d_pixel_size(rv3d, co) * (float)U.obcenter_dia * 0.5f;
        float verts[CIRCLE_RESOL][3];
 
        /* using gldepthfunc guarantees that it does write z values,
-        * but not checks for it, so centers remain visible independt order of drawing */
-       if(v3d->zbuf)  glDepthFunc(GL_ALWAYS);
+        * but not checks for it, so centers remain visible independent order of drawing */
+       if (v3d->zbuf) glDepthFunc(GL_ALWAYS);
        glEnable(GL_BLEND);
        
-       if(special_color) {
-               if (selstate==ACTIVE || selstate==SELECT) glColor4ub(0x88, 0xFF, 0xFF, 155);
+       if (special_color) {
+               if (selstate == ACTIVE || selstate == SELECT) glColor4ub(0x88, 0xFF, 0xFF, 155);
 
                else glColor4ub(0x55, 0xCC, 0xCC, 155);
        }
@@ -777,17 +789,17 @@ static void drawcentercircle(View3D *v3d, RegionView3D *rv3d, const float co[3],
        UI_ThemeColorShadeAlpha(TH_WIRE, 0, -30);
        glDrawArrays(GL_LINE_LOOP, 0, CIRCLE_RESOL);
 
-       /* finishe up */
+       /* finish up */
        glDisableClientState(GL_VERTEX_ARRAY);
 
        glDisable(GL_BLEND);
 
-       if(v3d->zbuf)  glDepthFunc(GL_LEQUAL);
+       if (v3d->zbuf) glDepthFunc(GL_LEQUAL);
 }
 
 /* *********** text drawing for object/particles/armature ************* */
 static ListBase CachedText[3];
-static int CachedTextLevel= 0;
+static int CachedTextLevel = 0;
 
 typedef struct ViewCachedString {
        struct ViewCachedString *next, *prev;
@@ -805,8 +817,8 @@ typedef struct ViewCachedString {
 
 void view3d_cached_text_draw_begin(void)
 {
-       ListBase *strings= &CachedText[CachedTextLevel];
-       strings->first= strings->last= NULL;
+       ListBase *strings = &CachedText[CachedTextLevel];
+       strings->first = strings->last = NULL;
        CachedTextLevel++;
 }
 
@@ -815,17 +827,17 @@ void view3d_cached_text_draw_add(const float co[3],
                                  short xoffs, short flag,
                                  const unsigned char col[4])
 {
-       int alloc_len= strlen(str) + 1;
-       ListBase *strings= &CachedText[CachedTextLevel-1];
+       int alloc_len = strlen(str) + 1;
+       ListBase *strings = &CachedText[CachedTextLevel - 1];
        /* TODO, replace with more efficient malloc, perhaps memarena per draw? */
-       ViewCachedString *vos= MEM_callocN(sizeof(ViewCachedString) + alloc_len, "ViewCachedString");
+       ViewCachedString *vos = MEM_callocN(sizeof(ViewCachedString) + alloc_len, "ViewCachedString");
 
        BLI_addtail(strings, vos);
        copy_v3_v3(vos->vec, co);
-       vos->col.pack= *((int *)col);
-       vos->xoffs= xoffs;
-       vos->flag= flag;
-       vos->str_len= alloc_len-1;
+       vos->col.pack = *((int *)col);
+       vos->xoffs = xoffs;
+       vos->flag = flag;
+       vos->str_len = alloc_len - 1;
 
        /* allocate past the end */
        memcpy(++vos, str, alloc_len);
@@ -833,83 +845,86 @@ void view3d_cached_text_draw_add(const float co[3],
 
 void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, int depth_write, float mat[][4])
 {
-       RegionView3D *rv3d= ar->regiondata;
-       ListBase *strings= &CachedText[CachedTextLevel-1];
+       RegionView3D *rv3d = ar->regiondata;
+       ListBase *strings = &CachedText[CachedTextLevel - 1];
        ViewCachedString *vos;
-       int a, tot= 0;
+       int tot = 0;
        
        /* project first and test */
-       for(vos= strings->first; vos; vos= vos->next) {
-               if(mat && !(vos->flag & V3D_CACHE_TEXT_WORLDSPACE))
+       for (vos = strings->first; vos; vos = vos->next) {
+               if (mat && !(vos->flag & V3D_CACHE_TEXT_WORLDSPACE))
                        mul_m4_v3(mat, vos->vec);
 
-               if(vos->flag&V3D_CACHE_TEXT_GLOBALSPACE)
-                       view3d_project_short_clip_persmat(ar, vos->vec, vos->sco, 0);
+               if (vos->flag & V3D_CACHE_TEXT_GLOBALSPACE)
+                       view3d_project_short_clip_persmat(ar, vos->vec, vos->sco, (vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0);
                else
-                       view3d_project_short_clip(ar, vos->vec, vos->sco, 0);
+                       view3d_project_short_clip(ar, vos->vec, vos->sco, (vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0);
 
-               if(vos->sco[0]!=IS_CLIPPED)
+               if (vos->sco[0] != IS_CLIPPED)
                        tot++;
        }
 
-       if(tot) {
-               int col_pack_prev= 0;
+       if (tot) {
+               int col_pack_prev = 0;
 
 #if 0
                bglMats mats; /* ZBuffer depth vars */
                double ux, uy, uz;
                float depth;
 
-               if(v3d->zbuf)
+               if (v3d->zbuf)
                        bgl_get_mats(&mats);
 #endif
-               if(rv3d->rflag & RV3D_CLIPPING)
-                       for(a=0; a<6; a++)
-                               glDisable(GL_CLIP_PLANE0+a);
-               
+               if (rv3d->rflag & RV3D_CLIPPING) {
+                       ED_view3d_clipping_disable();
+               }
+
                glMatrixMode(GL_PROJECTION);
                glPushMatrix();
                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();
                ED_region_pixelspace(ar);
                
-               if(depth_write) {
-                       if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
+               if (depth_write) {
+                       if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
+               }
+               else {
+                       glDepthMask(0);
                }
-               else glDepthMask(0);
                
-               for(vos= strings->first; vos; vos= vos->next) {
+               for (vos = strings->first; vos; vos = vos->next) {
                        /* too slow, reading opengl info while drawing is very bad,
                         * better to see if we can use the zbuffer while in pixel space - campbell */
 #if 0
-                       if(v3d->zbuf && (vos->flag & V3D_CACHE_TEXT_ZBUF)) {
+                       if (v3d->zbuf && (vos->flag & V3D_CACHE_TEXT_ZBUF)) {
                                gluProject(vos->vec[0], vos->vec[1], vos->vec[2], mats.modelview, mats.projection, (GLint *)mats.viewport, &ux, &uy, &uz);
-                               glReadPixels(ar->winrct.xmin+vos->mval[0]+vos->xoffs, ar->winrct.ymin+vos->mval[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
+                               glReadPixels(ar->winrct.xmin + vos->mval[0] + vos->xoffs, ar->winrct.ymin + vos->mval[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
 
-                               if(uz > depth)
+                               if (uz > depth)
                                        continue;
                        }
 #endif
-                       if(vos->sco[0]!=IS_CLIPPED) {
-                               const char *str= (char *)(vos+1);
+                       if (vos->sco[0] != IS_CLIPPED) {
+                               const char *str = (char *)(vos + 1);
 
-                               if(col_pack_prev != vos->col.pack) {
+                               if (col_pack_prev != vos->col.pack) {
                                        glColor3ubv(vos->col.ub);
-                                       col_pack_prev= vos->col.pack;
+                                       col_pack_prev = vos->col.pack;
                                }
+
                                ((vos->flag & V3D_CACHE_TEXT_ASCII) ?
-                                           BLF_draw_default_ascii :
-                                           BLF_draw_default
-                                           ) ( (float)vos->sco[0] + vos->xoffs,
-                                               (float)vos->sco[1],
-                                               (depth_write) ? 0.0f: 2.0f,
-                                               str,
-                                               vos->str_len);
+                                BLF_draw_default_ascii :
+                                BLF_draw_default
+                               )( (float)vos->sco[0] + vos->xoffs,
+                                  (float)vos->sco[1],
+                                  (depth_write) ? 0.0f : 2.0f,
+                                  str,
+                                  vos->str_len);
                        }
                }
                
-               if(depth_write) {
-                       if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
+               if (depth_write) {
+                       if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
                }
                else glDepthMask(1);
                
@@ -918,12 +933,12 @@ void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, int depth_write, floa
                glMatrixMode(GL_MODELVIEW);
                glPopMatrix();
 
-               if(rv3d->rflag & RV3D_CLIPPING)
-                       for(a=0; a<6; a++)
-                               glEnable(GL_CLIP_PLANE0+a);
+               if (rv3d->rflag & RV3D_CLIPPING) {
+                       ED_view3d_clipping_enable();
+               }
        }
        
-       if(strings->first) 
+       if (strings->first)
                BLI_freelistN(strings);
        
        CachedTextLevel--;
@@ -935,21 +950,21 @@ static void drawcube(void)
 {
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[0]); glVertex3fv(cube[1]);glVertex3fv(cube[2]); glVertex3fv(cube[3]);
-               glVertex3fv(cube[0]); glVertex3fv(cube[4]);glVertex3fv(cube[5]); glVertex3fv(cube[6]);
-               glVertex3fv(cube[7]); glVertex3fv(cube[4]);
+       glVertex3fv(cube[0]); glVertex3fv(cube[1]); glVertex3fv(cube[2]); glVertex3fv(cube[3]);
+       glVertex3fv(cube[0]); glVertex3fv(cube[4]); glVertex3fv(cube[5]); glVertex3fv(cube[6]);
+       glVertex3fv(cube[7]); glVertex3fv(cube[4]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[1]); glVertex3fv(cube[5]);
+       glVertex3fv(cube[1]); glVertex3fv(cube[5]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[2]); glVertex3fv(cube[6]);
+       glVertex3fv(cube[2]); glVertex3fv(cube[6]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[3]); glVertex3fv(cube[7]);
+       glVertex3fv(cube[3]); glVertex3fv(cube[7]);
        glEnd();
 }
 
@@ -959,25 +974,25 @@ static void drawcube(void)
 static void drawcube_size(float size)
 {
        glBegin(GL_LINE_STRIP);
-               glVertex3f(-size,-size,-size); glVertex3f(-size,-size,size);
-               glVertex3f(-size,size,size); glVertex3f(-size,size,-size);
+       glVertex3f(-size, -size, -size); glVertex3f(-size, -size, size);
+       glVertex3f(-size, size, size); glVertex3f(-size, size, -size);
 
-               glVertex3f(-size,-size,-size); glVertex3f(size,-size,-size);
-               glVertex3f(size,-size,size); glVertex3f(size,size,size);
+       glVertex3f(-size, -size, -size); glVertex3f(size, -size, -size);
+       glVertex3f(size, -size, size); glVertex3f(size, size, size);
 
-               glVertex3f(size,size,-size); glVertex3f(size,-size,-size);
+       glVertex3f(size, size, -size); glVertex3f(size, -size, -size);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3f(-size,-size,size); glVertex3f(size,-size,size);
+       glVertex3f(-size, -size, size); glVertex3f(size, -size, size);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3f(-size,size,size); glVertex3f(size,size,size);
+       glVertex3f(-size, size, size); glVertex3f(size, size, size);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3f(-size,size,-size); glVertex3f(size,size,-size);
+       glVertex3f(-size, size, -size); glVertex3f(size, size, -size);
        glEnd();
 }
 
@@ -991,21 +1006,21 @@ static void drawcube_size(const float size[3])
        
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[0]); glVertex3fv(cube[1]);glVertex3fv(cube[2]); glVertex3fv(cube[3]);
-               glVertex3fv(cube[0]); glVertex3fv(cube[4]);glVertex3fv(cube[5]); glVertex3fv(cube[6]);
-               glVertex3fv(cube[7]); glVertex3fv(cube[4]);
+       glVertex3fv(cube[0]); glVertex3fv(cube[1]); glVertex3fv(cube[2]); glVertex3fv(cube[3]);
+       glVertex3fv(cube[0]); glVertex3fv(cube[4]); glVertex3fv(cube[5]); glVertex3fv(cube[6]);
+       glVertex3fv(cube[7]); glVertex3fv(cube[4]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[1]); glVertex3fv(cube[5]);
+       glVertex3fv(cube[1]); glVertex3fv(cube[5]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[2]); glVertex3fv(cube[6]);
+       glVertex3fv(cube[2]); glVertex3fv(cube[6]);
        glEnd();
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(cube[3]); glVertex3fv(cube[7]);
+       glVertex3fv(cube[3]); glVertex3fv(cube[7]);
        glEnd();
        
        glPopMatrix();
@@ -1023,8 +1038,8 @@ static void drawshadbuflimits(Lamp *la, float mat[][4])
        madd_v3_v3v3fl(end, mat[3], lavec, la->clipend);
 
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(sta);
-               glVertex3fv(end);
+       glVertex3fv(sta);
+       glVertex3fv(end);
        glEnd();
 
        glPointSize(3.0);
@@ -1040,76 +1055,76 @@ static void drawshadbuflimits(Lamp *la, float mat[][4])
 static void spotvolume(float lvec[3], float vvec[3], const float inp)
 {
        /* camera is at 0,0,0 */
-       float temp[3],plane[3],mat1[3][3],mat2[3][3],mat3[3][3],mat4[3][3],q[4],co,si,angle;
+       float temp[3], plane[3], mat1[3][3], mat2[3][3], mat3[3][3], mat4[3][3], q[4], co, si, angle;
 
        normalize_v3(lvec);
-       normalize_v3(vvec);                             /* is this the correct vector ? */
+       normalize_v3(vvec);             /* is this the correct vector ? */
 
-       cross_v3_v3v3(temp,vvec,lvec);          /* equation for a plane through vvec en lvec */
-       cross_v3_v3v3(plane,lvec,temp);         /* a plane perpendicular to this, parrallel with lvec */
+       cross_v3_v3v3(temp, vvec, lvec);      /* equation for a plane through vvec en lvec */
+       cross_v3_v3v3(plane, lvec, temp);     /* a plane perpendicular to this, parrallel with lvec */
 
        /* vectors are exactly aligned, use the X axis, this is arbitrary */
-       if(normalize_v3(plane) == 0.0f)
-               plane[1]= 1.0f;
+       if (normalize_v3(plane) == 0.0f)
+               plane[1] = 1.0f;
 
        /* now we've got two equations: one of a cone and one of a plane, but we have
-       three unknowns. We remove one unkown by rotating the plane to z=0 (the plane normal) */
+        * three unknowns. We remove one unknown by rotating the plane to z=0 (the plane normal) */
 
        /* rotate around cross product vector of (0,0,1) and plane normal, dot product degrees */
        /* according definition, we derive cross product is (plane[1],-plane[0],0), en cos = plane[2]);*/
 
        /* translating this comment to english didnt really help me understanding the math! :-) (ton) */
        
-       q[1] = plane[1] ; 
-       q[2] = -plane[0] ; 
-       q[3] = ;
+       q[1] =  plane[1];
+       q[2] = -plane[0];
+       q[3] =  0;
        normalize_v3(&q[1]);
 
-       angle = saacos(plane[2])/2.0f;
+       angle = saacos(plane[2]) / 2.0f;
        co = cosf(angle);
-       si = sqrtf(1-co*co);
+       si = sqrtf(1 - co * co);
 
        q[0] =  co;
        q[1] *= si;
        q[2] *= si;
        q[3] =  0;
 
-       quat_to_mat3(mat1,q);
+       quat_to_mat3(mat1, q);
 
        /* rotate lamp vector now over acos(inp) degrees */
        copy_v3_v3(vvec, lvec);
 
        unit_m3(mat2);
        co = inp;
-       si = sqrtf(1.0f-inp*inp);
+       si = sqrtf(1.0f - inp * inp);
 
        mat2[0][0] =  co;
        mat2[1][0] = -si;
        mat2[0][1] =  si;
        mat2[1][1] =  co;
-       mul_m3_m3m3(mat3,mat2,mat1);
+       mul_m3_m3m3(mat3, mat2, mat1);
 
        mat2[1][0] =  si;
        mat2[0][1] = -si;
-       mul_m3_m3m3(mat4,mat2,mat1);
+       mul_m3_m3m3(mat4, mat2, mat1);
        transpose_m3(mat1);
 
-       mul_m3_m3m3(mat2,mat1,mat3);
-       mul_m3_v3(mat2,lvec);
-       mul_m3_m3m3(mat2,mat1,mat4);
-       mul_m3_v3(mat2,vvec);
+       mul_m3_m3m3(mat2, mat1, mat3);
+       mul_m3_v3(mat2, lvec);
+       mul_m3_m3m3(mat2, mat1, mat4);
+       mul_m3_v3(mat2, vvec);
 
        return;
 }
 
 static void draw_spot_cone(Lamp *la, float x, float z)
 {
-       z= fabs(z);
+       z = fabs(z);
 
        glBegin(GL_TRIANGLE_FAN);
        glVertex3f(0.0f, 0.0f, -x);
 
-       if(la->mode & LA_SQUARE) {
+       if (la->mode & LA_SQUARE) {
                glVertex3f(z, z, 0);
                glVertex3f(-z, z, 0);
                glVertex3f(-z, -z, 0);
@@ -1120,9 +1135,9 @@ static void draw_spot_cone(Lamp *la, float x, float z)
                float angle;
                int a;
 
-               for(a=0; a<33; a++) {
-                       angle= a*M_PI*2/(33-1);
-                       glVertex3f(z*cosf(angle), z*sinf(angle), 0);
+               for (a = 0; a < 33; a++) {
+                       angle = a * M_PI * 2 / (33 - 1);
+                       glVertex3f(z * cosf(angle), z * sinf(angle), 0);
                }
        }
 
@@ -1146,7 +1161,7 @@ static void draw_transp_spot_volume(Lamp *la, float x, float z)
        /* draw front side lighting */
        glCullFace(GL_BACK);
 
-       glBlendFunc(GL_ONE,  GL_ONE); 
+       glBlendFunc(GL_ONE, GL_ONE);
        glColor4f(0.2f, 0.2f, 0.2f, 1.0f);
 
        draw_spot_cone(la, x, z);
@@ -1161,24 +1176,24 @@ static void draw_transp_spot_volume(Lamp *la, float x, float z)
 
 static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base, int dt, int flag)
 {
-       Object *ob= base->object;
-       const float pixsize= ED_view3d_pixel_size(rv3d, ob->obmat[3]);
-       Lamp *la= ob->data;
-       float vec[3], lvec[3], vvec[3], circrad, x,y,z;
+       Object *ob = base->object;
+       const float pixsize = ED_view3d_pixel_size(rv3d, ob->obmat[3]);
+       Lamp *la = ob->data;
+       float vec[3], lvec[3], vvec[3], circrad, x, y, z;
        float lampsize;
        float imat[4][4], curcol[4];
        unsigned char col[4];
        /* cone can't be drawn for duplicated lamps, because duplilist would be freed to */
        /* the moment of view3d_draw_transp() call */
-       const short is_view= (rv3d->persp==RV3D_CAMOB && v3d->camera == base->object);
-       const short drawcone= ((dt > OB_WIRE) &&
-                              !(G.f & G_PICKSEL) &&
-                              (la->type == LA_SPOT) &&
-                              (la->mode & LA_SHOW_CONE) &&
-                              !(base->flag & OB_FROMDUPLI) &&
-                              !is_view);
-
-       if(drawcone && !v3d->transp) {
+       const short is_view = (rv3d->persp == RV3D_CAMOB && v3d->camera == base->object);
+       const short drawcone = ((dt > OB_WIRE) &&
+                               !(G.f & G_PICKSEL) &&
+                               (la->type == LA_SPOT) &&
+                               (la->mode & LA_SHOW_CONE) &&
+                               !(base->flag & OB_FROMDUPLI) &&
+                               !is_view);
+
+       if (drawcone && !v3d->transp) {
                /* in this case we need to draw delayed */
                add_view3d_after(&v3d->afterdraw_transp, base, flag);
                return;
@@ -1189,7 +1204,7 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
        glLoadMatrixf(rv3d->viewmat);
 
        /* lets calculate the scale: */
-       lampsize= pixsize*((float)U.obcenter_dia*0.5f);
+       lampsize = pixsize * ((float)U.obcenter_dia * 0.5f);
 
        /* and view aligned matrix: */
        copy_m4_m4(imat, rv3d->viewinv);
@@ -1201,13 +1216,13 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
        
        /* for AA effects */
        glGetFloatv(GL_CURRENT_COLOR, curcol);
-       curcol[3]= 0.6;
+       curcol[3] = 0.6;
        glColor4fv(curcol);
        
-       if(lampsize > 0.0f) {
+       if (lampsize > 0.0f) {
 
-               if(ob->id.us>1) {
-                       if (ob==OBACT || (ob->flag & SELECT)) glColor4ub(0x88, 0xFF, 0xFF, 155);
+               if (ob->id.us > 1) {
+                       if (ob == OBACT || (ob->flag & SELECT)) glColor4ub(0x88, 0xFF, 0xFF, 155);
                        else glColor4ub(0x77, 0xCC, 0xCC, 155);
                }
                
@@ -1218,21 +1233,19 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
                drawcircball(GL_POLYGON, vec, lampsize, imat);
                
                /* restore */
-               if(ob->id.us>1)
+               if (ob->id.us > 1)
                        glColor4fv(curcol);
-                       
+
                /* Outer circle */
-               circrad = 3.0f*lampsize;
+               circrad = 3.0f * lampsize;
                setlinestyle(3);
 
                drawcircball(GL_LINE_LOOP, vec, circrad, imat);
 
                /* draw dashed outer circle if shadow is on. remember some lamps can't have certain shadows! */
-               if(la->type!=LA_HEMI) {
-                       if(     (la->mode & LA_SHAD_RAY) ||
-                               ((la->mode & LA_SHAD_BUF) && (la->type==LA_SPOT))
-                       ) {
-                               drawcircball(GL_LINE_LOOP, vec, circrad + 3.0f*pixsize, imat);
+               if (la->type != LA_HEMI) {
+                       if ((la->mode & LA_SHAD_RAY) || ((la->mode & LA_SHAD_BUF) && (la->type == LA_SPOT))) {
+                               drawcircball(GL_LINE_LOOP, vec, circrad + 3.0f * pixsize, imat);
                        }
                }
        }
@@ -1242,12 +1255,12 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
        }
        
        /* draw the pretty sun rays */
-       if(la->type==LA_SUN) {
+       if (la->type == LA_SUN) {
                float v1[3], v2[3], mat[3][3];
                short axis;
                
                /* setup a 45 degree rotation matrix */
-               vec_rot_to_mat3(mat, imat[2], (float)M_PI/4.0f);
+               vec_rot_to_mat3(mat, imat[2], (float)M_PI / 4.0f);
                
                /* vectors */
                mul_v3_v3fl(v1, imat[0], circrad * 1.2f);
@@ -1259,7 +1272,7 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
                setlinestyle(3);
                
                glBegin(GL_LINES);
-               for (axis=0; axis<8; axis++) {
+               for (axis = 0; axis < 8; axis++) {
                        glVertex3fv(v1);
                        glVertex3fv(v2);
                        mul_m3_v3(mat, v1);
@@ -1269,32 +1282,31 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
                
                glTranslatef(-vec[0], -vec[1], -vec[2]);
 
-       }               
+       }
        
-       if (la->type==LA_LOCAL) {
-               if(la->mode & LA_SPHERE) {
+       if (la->type == LA_LOCAL) {
+               if (la->mode & LA_SPHERE) {
                        drawcircball(GL_LINE_LOOP, vec, la->dist, imat);
                }
-               /* yafray: for photonlight also draw lightcone as for spot */
        }
        
-       glPopMatrix();  /* back in object space */
+       glPopMatrix();  /* back in object space */
        zero_v3(vec);
        
-       if(is_view) {
+       if (is_view) {
                /* skip drawing extra info */
        }
-       else if ((la->type==LA_SPOT) || (la->type==LA_YF_PHOTON)) {
-               lvec[0]=lvec[1]= 0.0; 
+       else if ((la->type == LA_SPOT) || (la->type == LA_YF_PHOTON)) {
+               lvec[0] = lvec[1] = 0.0;
                lvec[2] = 1.0;
                x = rv3d->persmat[0][2];
                y = rv3d->persmat[1][2];
                z = rv3d->persmat[2][2];
-               vvec[0]= x*ob->obmat[0][0] + y*ob->obmat[0][1] + z*ob->obmat[0][2];
-               vvec[1]= x*ob->obmat[1][0] + y*ob->obmat[1][1] + z*ob->obmat[1][2];
-               vvec[2]= x*ob->obmat[2][0] + y*ob->obmat[2][1] + z*ob->obmat[2][2];
+               vvec[0] = x * ob->obmat[0][0] + y * ob->obmat[0][1] + z * ob->obmat[0][2];
+               vvec[1] = x * ob->obmat[1][0] + y * ob->obmat[1][1] + z * ob->obmat[1][2];
+               vvec[2] = x * ob->obmat[2][0] + y * ob->obmat[2][1] + z * ob->obmat[2][2];
 
-               y = cosf(la->spotsize*(float)(M_PI/360.0));
+               y = cosf(la->spotsize * (float)(M_PI / 360.0));
                spotvolume(lvec, vvec, y);
                x = -la->dist;
                mul_v3_fl(lvec, x);
@@ -1302,75 +1314,75 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
 
                /* draw the angled sides of the cone */
                glBegin(GL_LINE_STRIP);
-                       glVertex3fv(vvec);
-                       glVertex3fv(vec);
-                       glVertex3fv(lvec);
+               glVertex3fv(vvec);
+               glVertex3fv(vec);
+               glVertex3fv(lvec);
                glEnd();
                
-               z = x*sqrtf(1.0f - y*y);
+               z = x * sqrtf(1.0f - y * y);
                x *= y;
 
                /* draw the circle/square at the end of the cone */
-               glTranslatef(0.0, 0.0 ,  x);
-               if(la->mode & LA_SQUARE) {
+               glTranslatef(0.0, 0.0,  x);
+               if (la->mode & LA_SQUARE) {
                        float tvec[3];
-                       float z_abs= fabs(z);
+                       float z_abs = fabs(z);
 
-                       tvec[0]= tvec[1]= z_abs;
-                       tvec[2]= 0.0;
+                       tvec[0] = tvec[1] = z_abs;
+                       tvec[2] = 0.0;
 
                        glBegin(GL_LINE_LOOP);
-                               glVertex3fv(tvec);
-                               tvec[1]= -z_abs; /* neg */
-                               glVertex3fv(tvec);
-                               tvec[0]= -z_abs; /* neg */
-                               glVertex3fv(tvec);
-                               tvec[1]= z_abs; /* pos */
-                               glVertex3fv(tvec);
+                       glVertex3fv(tvec);
+                       tvec[1] = -z_abs; /* neg */
+                       glVertex3fv(tvec);
+                       tvec[0] = -z_abs; /* neg */
+                       glVertex3fv(tvec);
+                       tvec[1] = z_abs; /* pos */
+                       glVertex3fv(tvec);
                        glEnd();
                }
                else circ(0.0, 0.0, fabsf(z));
                
                /* draw the circle/square representing spotbl */
-               if(la->type==LA_SPOT) {
-                       float spotblcirc = fabs(z)*(1 - pow(la->spotblend, 2));
+               if (la->type == LA_SPOT) {
+                       float spotblcirc = fabs(z) * (1 - pow(la->spotblend, 2));
                        /* hide line if it is zero size or overlaps with outer border,
-                          previously it adjusted to always to show it but that seems
-                          confusing because it doesn't show the actual blend size */
+                        * previously it adjusted to always to show it but that seems
+                        * confusing because it doesn't show the actual blend size */
                        if (spotblcirc != 0 && spotblcirc != fabsf(z))
                                circ(0.0, 0.0, spotblcirc);
                }
 
-               if(drawcone)
+               if (drawcone)
                        draw_transp_spot_volume(la, x, z);
 
                /* draw clip start, useful for wide cones where its not obvious where the start is */
-               glTranslatef(0.0, 0.0 , -x); /* reverse translation above */
-               if(la->type==LA_SPOT && (la->mode & LA_SHAD_BUF) ) {
+               glTranslatef(0.0, 0.0, -x);  /* reverse translation above */
+               if (la->type == LA_SPOT && (la->mode & LA_SHAD_BUF) ) {
                        float lvec_clip[3];
                        float vvec_clip[3];
-                       float clipsta_fac= la->clipsta / -x;
+                       float clipsta_fac = la->clipsta / -x;
 
                        interp_v3_v3v3(lvec_clip, vec, lvec, clipsta_fac);
                        interp_v3_v3v3(vvec_clip, vec, vvec, clipsta_fac);
 
                        glBegin(GL_LINE_STRIP);
-                               glVertex3fv(lvec_clip);
-                               glVertex3fv(vvec_clip);
+                       glVertex3fv(lvec_clip);
+                       glVertex3fv(vvec_clip);
                        glEnd();
                }
        }
-       else if ELEM(la->type, LA_HEMI, LA_SUN) {
+       else if (ELEM(la->type, LA_HEMI, LA_SUN)) {
                
                /* draw the line from the circle along the dist */
                glBegin(GL_LINE_STRIP);
-                       vec[2] = -circrad;
-                       glVertex3fv(vec); 
-                       vec[2]= -la->dist; 
-                       glVertex3fv(vec);
+               vec[2] = -circrad;
+               glVertex3fv(vec);
+               vec[2] = -la->dist;
+               glVertex3fv(vec);
                glEnd();
                
-               if(la->type==LA_HEMI) {
+               if (la->type == LA_HEMI) {
                        /* draw the hemisphere curves */
                        short axis, steps, dir;
                        float outdist, zdist, mul;
@@ -1379,24 +1391,24 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
                        
                        setlinestyle(4);
                        /* loop over the 4 compass points, and draw each arc as a LINE_STRIP */
-                       for (axis=0; axis<4; axis++) {
-                               float v[3]= {0.0, 0.0, 0.0};
+                       for (axis = 0; axis < 4; axis++) {
+                               float v[3] = {0.0, 0.0, 0.0};
                                zdist = 0.02;
                                
                                glBegin(GL_LINE_STRIP);
                                
-                               for (steps=0; steps<6; steps++) {
-                                       if (axis == 0 || axis == 1) {           /* x axis up, x axis down */    
+                               for (steps = 0; steps < 6; steps++) {
+                                       if (axis == 0 || axis == 1) {       /* x axis up, x axis down */
                                                /* make the arcs start at the edge of the energy circle */
-                                               if (steps == 0) v[0] = dir*circrad;
-                                               else v[0] = v[0] + dir*(steps*outdist);
-                                       } else if (axis == 2 || axis == 3) {            /* y axis up, y axis down */
+                                               if (steps == 0) v[0] = dir * circrad;
+                                               else v[0] = v[0] + dir * (steps * outdist);
+                                       }
+                                       else if (axis == 2 || axis == 3) {      /* y axis up, y axis down */
                                                /* make the arcs start at the edge of the energy circle */
-                                               if (steps == 0) v[1] = dir*circrad;
-                                               else v[1] = v[1] + dir*(steps*outdist); 
+                                               v[1] = (steps == 0) ? (dir * circrad) : (v[1] + dir * (steps * outdist));
                                        }
-               
-                                       v[2] = v[2] - steps*zdist;
+
+                                       v[2] = v[2] - steps * zdist;
                                        
                                        glVertex3fv(v);
                                        
@@ -1408,16 +1420,17 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
                                dir = -dir;
                        }
                }
-       } else if(la->type==LA_AREA) {
+       }
+       else if (la->type == LA_AREA) {
                setlinestyle(3);
-               if(la->area_shape==LA_AREA_SQUARE) 
-                       fdrawbox(-la->area_size*0.5f, -la->area_size*0.5f, la->area_size*0.5f, la->area_size*0.5f);
-               else if(la->area_shape==LA_AREA_RECT) 
-                       fdrawbox(-la->area_size*0.5f, -la->area_sizey*0.5f, la->area_size*0.5f, la->area_sizey*0.5f);
-
-               glBegin(GL_LINE_STRIP); 
-               glVertex3f(0.0,0.0,-circrad);
-               glVertex3f(0.0,0.0,-la->dist);
+               if (la->area_shape == LA_AREA_SQUARE)
+                       fdrawbox(-la->area_size * 0.5f, -la->area_size * 0.5f, la->area_size * 0.5f, la->area_size * 0.5f);
+               else if (la->area_shape == LA_AREA_RECT)
+                       fdrawbox(-la->area_size * 0.5f, -la->area_sizey * 0.5f, la->area_size * 0.5f, la->area_sizey * 0.5f);
+
+               glBegin(GL_LINE_STRIP);
+               glVertex3f(0.0, 0.0, -circrad);
+               glVertex3f(0.0, 0.0, -la->dist);
                glEnd();
        }
        
@@ -1427,27 +1440,27 @@ static void drawlamp(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base,
 
        setlinestyle(0);
        
-       if((la->type == LA_SPOT) && (la->mode & LA_SHAD_BUF) && (is_view == FALSE)) {
+       if ((la->type == LA_SPOT) && (la->mode & LA_SHAD_BUF) && (is_view == FALSE)) {
                drawshadbuflimits(la, ob->obmat);
        }
        
        UI_GetThemeColor4ubv(TH_LAMP, col);
        glColor4ubv(col);
-        
+
        glEnable(GL_BLEND);
        
-       if (vec[2]>0) vec[2] -= circrad;
+       if (vec[2] > 0) vec[2] -= circrad;
        else vec[2] += circrad;
        
        glBegin(GL_LINE_STRIP);
-               glVertex3fv(vec); 
-               vec[2]= 0; 
-               glVertex3fv(vec);
+       glVertex3fv(vec);
+       vec[2] = 0;
+       glVertex3fv(vec);
        glEnd();
        
        glPointSize(2.0);
        glBegin(GL_POINTS);
-               glVertex3fv(vec);
+       glVertex3fv(vec);
        glEnd();
        glPointSize(1.0);
        
@@ -1476,7 +1489,7 @@ static void draw_limit_line(float sta, float end, unsigned int col)
 
 
 /* yafray: draw camera focus point (cross, similar to aqsis code in tuhopuu) */
-/* qdn: now also enabled for Blender to set focus point for defocus composit node */
+/* qdn: now also enabled for Blender to set focus point for defocus composite node */
 static void draw_focus_cross(float dist, float size)
 {
        glBegin(GL_LINES);
@@ -1489,22 +1502,22 @@ static void draw_focus_cross(float dist, float size)
 
 #ifdef VIEW3D_CAMERA_BORDER_HACK
 float view3d_camera_border_hack_col[4];
-short view3d_camera_border_hack_test= FALSE;
+short view3d_camera_border_hack_test = FALSE;
 #endif
 
 /* ****************** draw clip data *************** */
 
 static void draw_bundle_sphere(void)
 {
-       static GLuint displist= 0;
+       static GLuint displist = 0;
 
        if (displist == 0) {
                GLUquadricObj *qobj;
 
-               displist= glGenLists(1);
+               displist = glGenLists(1);
                glNewList(displist, GL_COMPILE);
 
-               qobj= gluNewQuadric();
+               qobj = gluNewQuadric();
                gluQuadricDrawStyle(qobj, GLU_FILL);
                glShadeModel(GL_SMOOTH);
                gluSphere(qobj, 0.05, 8, 8);
@@ -1518,14 +1531,15 @@ static void draw_bundle_sphere(void)
 }
 
 static void draw_viewport_object_reconstruction(Scene *scene, Base *base, View3D *v3d,
-                       MovieClip *clip, MovieTrackingObject *tracking_object, int flag, int *global_track_index)
+                                                MovieClip *clip, MovieTrackingObject *tracking_object, int flag,
+                                                int *global_track_index, int draw_selected)
 {
-       MovieTracking *tracking= &clip->tracking;
+       MovieTracking *tracking = &clip->tracking;
        MovieTrackingTrack *track;
        float mat[4][4], imat[4][4];
        unsigned char col[4], scol[4];
-       int tracknr= *global_track_index;
-       ListBase *tracksbase= BKE_tracking_object_tracks(tracking, tracking_object);
+       int tracknr = *global_track_index;
+       ListBase *tracksbase = BKE_tracking_object_tracks(tracking, tracking_object);
 
        UI_GetThemeColor4ubv(TH_TEXT, col);
        UI_GetThemeColor4ubv(TH_SELECT, scol);
@@ -1534,10 +1548,10 @@ static void draw_viewport_object_reconstruction(Scene *scene, Base *base, View3D
 
        glPushMatrix();
 
-       if(tracking_object->flag & TRACKING_OBJECT_CAMERA) {
+       if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
                /* current ogl matrix is translated in camera space, bundles should
-                  be rendered in world space, so camera matrix should be "removed"
-                  from current ogl matrix */
+                * be rendered in world space, so camera matrix should be "removed"
+                * from current ogl matrix */
                invert_m4_m4(imat, base->object->obmat);
 
                glMultMatrixf(imat);
@@ -1552,79 +1566,86 @@ static void draw_viewport_object_reconstruction(Scene *scene, Base *base, View3D
                glMultMatrixf(imat);
        }
 
-       for (track= tracksbase->first; track; track= track->next) {
-               int selected= TRACK_SELECTED(track);
+       for (track = tracksbase->first; track; track = track->next) {
+               int selected = TRACK_SELECTED(track);
+
+               if (draw_selected && !selected)
+                       continue;
 
-               if((track->flag&TRACK_HAS_BUNDLE)==0)
+               if ((track->flag & TRACK_HAS_BUNDLE) == 0)
                        continue;
 
-               if(flag&DRAW_PICKING)
-                       glLoadName(base->selcol + (tracknr<<16));
+               if (flag & DRAW_PICKING)
+                       glLoadName(base->selcol + (tracknr << 16));
 
                glPushMatrix();
-                       glTranslatef(track->bundle_pos[0], track->bundle_pos[1], track->bundle_pos[2]);
-                       glScalef(v3d->bundle_size/0.05f, v3d->bundle_size/0.05f, v3d->bundle_size/0.05f);
+               glTranslatef(track->bundle_pos[0], track->bundle_pos[1], track->bundle_pos[2]);
+               glScalef(v3d->bundle_size / 0.05f, v3d->bundle_size / 0.05f, v3d->bundle_size / 0.05f);
 
-                       if(v3d->drawtype==OB_WIRE) {
-                               glDisable(GL_LIGHTING);
+               if (v3d->drawtype == OB_WIRE) {
+                       glDisable(GL_LIGHTING);
 
-                               if(selected) {
-                                       if(base==BASACT) UI_ThemeColor(TH_ACTIVE);
-                                       else UI_ThemeColor(TH_SELECT);
-                               } else {
-                                       if(track->flag&TRACK_CUSTOMCOLOR) glColor3fv(track->color);
-                                       else UI_ThemeColor(TH_WIRE);
-                               }
+                       if (selected) {
+                               if (base == BASACT) UI_ThemeColor(TH_ACTIVE);
+                               else UI_ThemeColor(TH_SELECT);
+                       }
+                       else {
+                               if (track->flag & TRACK_CUSTOMCOLOR) glColor3fv(track->color);
+                               else UI_ThemeColor(TH_WIRE);
+                       }
 
-                               drawaxes(0.05f, v3d->bundle_drawtype);
+                       drawaxes(0.05f, v3d->bundle_drawtype);
 
-                               glEnable(GL_LIGHTING);
-                       } else if(v3d->drawtype>OB_WIRE) {
-                               if(v3d->bundle_drawtype==OB_EMPTY_SPHERE) {
-                                       /* selection outline */
-                                       if(selected) {
-                                               if(base==BASACT) UI_ThemeColor(TH_ACTIVE);
-                                               else UI_ThemeColor(TH_SELECT);
-
-                                               glLineWidth(2.f);
-                                               glDisable(GL_LIGHTING);
-                                               glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-
-                                               draw_bundle_sphere();
-
-                                               glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-                                               glEnable(GL_LIGHTING);
-                                               glLineWidth(1.f);
-                                       }
+                       glEnable(GL_LIGHTING);
+               }
+               else if (v3d->drawtype > OB_WIRE) {
+                       if (v3d->bundle_drawtype == OB_EMPTY_SPHERE) {
+                               /* selection outline */
+                               if (selected) {
+                                       if (base == BASACT) UI_ThemeColor(TH_ACTIVE);
+                                       else UI_ThemeColor(TH_SELECT);
 
-                                       if(track->flag&TRACK_CUSTOMCOLOR) glColor3fv(track->color);
-                                       else UI_ThemeColor(TH_BUNDLE_SOLID);
+                                       glLineWidth(2.f);
+                                       glDisable(GL_LIGHTING);
+                                       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
 
                                        draw_bundle_sphere();
-                               } else {
-                                       glDisable(GL_LIGHTING);
 
-                                       if(selected) {
-                                               if(base==BASACT) UI_ThemeColor(TH_ACTIVE);
-                                               else UI_ThemeColor(TH_SELECT);
-                                       } else {
-                                               if(track->flag&TRACK_CUSTOMCOLOR) glColor3fv(track->color);
-                                               else UI_ThemeColor(TH_WIRE);
-                                       }
+                                       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+                                       glEnable(GL_LIGHTING);
+                                       glLineWidth(1.f);
+                               }
 
-                                       drawaxes(0.05f, v3d->bundle_drawtype);
+                               if (track->flag & TRACK_CUSTOMCOLOR) glColor3fv(track->color);
+                               else UI_ThemeColor(TH_BUNDLE_SOLID);
 
-                                       glEnable(GL_LIGHTING);
+                               draw_bundle_sphere();
+                       }
+                       else {
+                               glDisable(GL_LIGHTING);
+
+                               if (selected) {
+                                       if (base == BASACT) UI_ThemeColor(TH_ACTIVE);
+                                       else UI_ThemeColor(TH_SELECT);
+                               }
+                               else {
+                                       if (track->flag & TRACK_CUSTOMCOLOR) glColor3fv(track->color);
+                                       else UI_ThemeColor(TH_WIRE);
                                }
+
+                               drawaxes(0.05f, v3d->bundle_drawtype);
+
+                               glEnable(GL_LIGHTING);
                        }
+               }
 
                glPopMatrix();
 
-               if((flag & DRAW_PICKING)==0 && (v3d->flag2&V3D_SHOW_BUNDLENAME)) {
+               if ((flag & DRAW_PICKING) == 0 && (v3d->flag2 & V3D_SHOW_BUNDLENAME)) {
                        float pos[3];
                        unsigned char tcol[4];
 
-                       if(selected) memcpy(tcol, scol, sizeof(tcol));
+                       if (selected) memcpy(tcol, scol, sizeof(tcol));
                        else memcpy(tcol, col, sizeof(tcol));
 
                        mul_v3_m4v3(pos, mat, track->bundle_pos);
@@ -1634,47 +1655,48 @@ static void draw_viewport_object_reconstruction(Scene *scene, Base *base, View3D
                tracknr++;
        }
 
-       if((flag & DRAW_PICKING)==0) {
-               if((v3d->flag2&V3D_SHOW_CAMERAPATH) && (tracking_object->flag&TRACKING_OBJECT_CAMERA)) {
+       if ((flag & DRAW_PICKING) == 0) {
+               if ((v3d->flag2 & V3D_SHOW_CAMERAPATH) && (tracking_object->flag & TRACKING_OBJECT_CAMERA)) {
                        MovieTrackingReconstruction *reconstruction;
-                       reconstruction= BKE_tracking_object_reconstruction(tracking, tracking_object);
+                       reconstruction = BKE_tracking_object_reconstruction(tracking, tracking_object);
 
-                       if(reconstruction->camnr) {
-                               MovieReconstructedCamera *camera= reconstruction->cameras;
-                               int a= 0;
+                       if (reconstruction->camnr) {
+                               MovieReconstructedCamera *camera = reconstruction->cameras;
+                               int a = 0;
 
                                glDisable(GL_LIGHTING);
                                UI_ThemeColor(TH_CAMERA_PATH);
                                glLineWidth(2.0f);
 
                                glBegin(GL_LINE_STRIP);
-                                       for(a= 0; a<reconstruction->camnr; a++, camera++) {
-                                               glVertex3fv(camera->mat[3]);
-                                       }
-                                       glEnd();
+                               for (a = 0; a < reconstruction->camnr; a++, camera++) {
+                                       glVertex3fv(camera->mat[3]);
+                               }
+                               glEnd();
 
-                                       glLineWidth(1.0f);
-                                       glEnable(GL_LIGHTING);
+                               glLineWidth(1.0f);
+                               glEnable(GL_LIGHTING);
                        }
                }
        }
 
        glPopMatrix();
 
-       *global_track_index= tracknr;
+       *global_track_index = tracknr;
 }
 
-static void draw_viewport_reconstruction(Scene *scene, Base *base, View3D *v3d, MovieClip *clip, int flag)
+static void draw_viewport_reconstruction(Scene *scene, Base *base, View3D *v3d, MovieClip *clip,
+                                         int flag, int draw_selected)
 {
-       MovieTracking *tracking= &clip->tracking;
+       MovieTracking *tracking = &clip->tracking;
        MovieTrackingObject *tracking_object;
        float curcol[4];
-       int global_track_index= 1;
+       int global_track_index = 1;
 
-       if((v3d->flag2&V3D_SHOW_RECONSTRUCTION)==0)
+       if ((v3d->flag2 & V3D_SHOW_RECONSTRUCTION) == 0)
                return;
 
-       if(v3d->flag2&V3D_RENDER_OVERRIDE)
+       if (v3d->flag2 & V3D_RENDER_OVERRIDE)
                return;
 
        glGetFloatv(GL_CURRENT_COLOR, curcol);
@@ -1684,12 +1706,12 @@ static void draw_viewport_reconstruction(Scene *scene, Base *base, View3D *v3d,
        glEnable(GL_COLOR_MATERIAL);
        glShadeModel(GL_SMOOTH);
 
-       tracking_object= tracking->objects.first;
-       while(tracking_object) {
+       tracking_object = tracking->objects.first;
+       while (tracking_object) {
                draw_viewport_object_reconstruction(scene, base, v3d, clip, tracking_object,
-                                       flag, &global_track_index);
+                                                   flag, &global_track_index, draw_selected);
 
-               tracking_object= tracking_object->next;
+               tracking_object = tracking_object->next;
        }
 
        /* restore */
@@ -1699,7 +1721,7 @@ static void draw_viewport_reconstruction(Scene *scene, Base *base, View3D *v3d,
 
        glColor4fv(curcol);
 
-       if(flag&DRAW_PICKING)
+       if (flag & DRAW_PICKING)
                glLoadName(base->selcol);
 }
 
@@ -1708,31 +1730,33 @@ static void drawcamera(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base
 {
        /* a standing up pyramid with (0,0,0) as top */
        Camera *cam;
-       Object *ob= base->object;
+       Object *ob = base->object;
        float tvec[3];
        float vec[4][3], asp[2], shift[2], scale[3];
        int i;
        float drawsize;
-       const short is_view= (rv3d->persp==RV3D_CAMOB && ob==v3d->camera);
-       MovieClip *clip= object_get_movieclip(scene, base->object, 0);
+       const short is_view = (rv3d->persp == RV3D_CAMOB && ob == v3d->camera);
+       MovieClip *clip = object_get_movieclip(scene, base->object, 0);
 
        /* draw data for movie clip set as active for scene */
-       if(clip)
-               draw_viewport_reconstruction(scene, base, v3d, clip, flag);
+       if (clip) {
+               draw_viewport_reconstruction(scene, base, v3d, clip, flag, FALSE);
+               draw_viewport_reconstruction(scene, base, v3d, clip, flag, TRUE);
+       }
 
 #ifdef VIEW3D_CAMERA_BORDER_HACK
-       if(is_view && !(G.f & G_PICKSEL)) {
+       if (is_view && !(G.f & G_PICKSEL)) {
                glGetFloatv(GL_CURRENT_COLOR, view3d_camera_border_hack_col);
-               view3d_camera_border_hack_test= TRUE;
+               view3d_camera_border_hack_test = TRUE;
                return;
        }
 #endif
 
-       cam= ob->data;
+       cam = ob->data;
 
-       scale[0]= 1.0f / len_v3(ob->obmat[0]);
-       scale[1]= 1.0f / len_v3(ob->obmat[1]);
-       scale[2]= 1.0f / len_v3(ob->obmat[2]);
+       scale[0] = 1.0f / len_v3(ob->obmat[0]);
+       scale[1] = 1.0f / len_v3(ob->obmat[1]);
+       scale[2] = 1.0f / len_v3(ob->obmat[2]);
 
        camera_view_frame_ex(scene, cam, cam->drawsize, is_view, scale,
                             asp, shift, &drawsize, vec);
@@ -1748,7 +1772,7 @@ static void drawcamera(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base
        glVertex3fv(vec[3]);
        glEnd();
 
-       if(is_view)
+       if (is_view)
                return;
 
        zero_v3(tvec);
@@ -1765,36 +1789,36 @@ static void drawcamera(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base
 
 
        /* arrow on top */
-       tvec[2]= vec[1][2]; /* copy the depth */
+       tvec[2] = vec[1][2]; /* copy the depth */
 
 
        /* draw an outline arrow for inactive cameras and filled
         * for active cameras. We actually draw both outline+filled
-        * for active cameras so the wire can be seen side-on */        
-       for (i=0;i<2;i++) {
-               if (i==0) glBegin(GL_LINE_LOOP);
-               else if (i==1 && (ob == v3d->camera)) glBegin(GL_TRIANGLES);
+        * for active cameras so the wire can be seen side-on */
+       for (i = 0; i < 2; i++) {
+               if (i == 0) glBegin(GL_LINE_LOOP);
+               else if (i == 1 && (ob == v3d->camera)) glBegin(GL_TRIANGLES);
                else break;
 
-               tvec[0]= shift[0] + ((-0.7f * drawsize) * scale[0]);
-               tvec[1]= shift[1] + ((drawsize * (asp[1] + 0.1f)) * scale[1]);
+               tvec[0] = shift[0] + ((-0.7f * drawsize) * scale[0]);
+               tvec[1] = shift[1] + ((drawsize * (asp[1] + 0.1f)) * scale[1]);
                glVertex3fv(tvec); /* left */
                
-               tvec[0]= shift[0] + ((0.7f * drawsize) * scale[0]);
+               tvec[0] = shift[0] + ((0.7f * drawsize) * scale[0]);
                glVertex3fv(tvec); /* right */
                
-               tvec[0]= shift[0];
-               tvec[1]= shift[1] + ((1.1f * drawsize * (asp[1] + 0.7f)) * scale[1]);
+               tvec[0] = shift[0];
+               tvec[1] = shift[1] + ((1.1f * drawsize * (asp[1] + 0.7f)) * scale[1]);
                glVertex3fv(tvec); /* top */
-       
+
                glEnd();
        }
 
-       if(flag==0) {
-               if(cam->flag & (CAM_SHOWLIMITS+CAM_SHOWMIST)) {
+       if (flag == 0) {
+               if (cam->flag & (CAM_SHOWLIMITS + CAM_SHOWMIST)) {
                        float nobmat[4][4];
                        World *wrld;
-       
+
                        /* draw in normalized object matrix space */
                        copy_m4_m4(nobmat, ob->obmat);
                        normalize_m4(nobmat);
@@ -1803,16 +1827,16 @@ static void drawcamera(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base
                        glLoadMatrixf(rv3d->viewmat);
                        glMultMatrixf(nobmat);
 
-                       if(cam->flag & CAM_SHOWLIMITS) {
+                       if (cam->flag & CAM_SHOWLIMITS) {
                                draw_limit_line(cam->clipsta, cam->clipend, 0x77FFFF);
-                               /* qdn: was yafray only, now also enabled for Blender to be used with defocus composit node */
+                               /* qdn: was yafray only, now also enabled for Blender to be used with defocus composite node */
                                draw_focus_cross(object_camera_dof_distance(ob), cam->drawsize);
                        }
 
-                       wrld= scene->world;
-                       if(cam->flag & CAM_SHOWMIST) 
-                               if(wrld) draw_limit_line(wrld->miststa, wrld->miststa+wrld->mistdist, 0xFFFFFF);
-                               
+                       wrld = scene->world;
+                       if (cam->flag & CAM_SHOWMIST)
+                               if (wrld) draw_limit_line(wrld->miststa, wrld->miststa + wrld->mistdist, 0xFFFFFF);
+
                        glPopMatrix();
                }
        }
@@ -1829,11 +1853,11 @@ static void drawspeaker(Scene *UNUSED(scene), View3D *UNUSED(v3d), RegionView3D
 
        glEnable(GL_BLEND);
 
-       for(j = 0; j < 3; j++) {
-               vec[2] = 0.25f * j -0.125f;
+       for (j = 0; j < 3; j++) {
+               vec[2] = 0.25f * j - 0.125f;
 
                glBegin(GL_LINE_LOOP);
-               for(i = 0; i < 16; i++) {
+               for (i = 0; i < 16; i++) {
                        vec[0] = cosf((float)M_PI * i / 8.0f) * (j == 0 ? 0.5f : 0.25f);
                        vec[1] = sinf((float)M_PI * i / 8.0f) * (j == 0 ? 0.5f : 0.25f);
                        glVertex3fv(vec);
@@ -1841,17 +1865,17 @@ static void drawspeaker(Scene *UNUSED(scene), View3D *UNUSED(v3d), RegionView3D
                glEnd();
        }
 
-       for(j = 0; j < 4; j++) {
+       for (j = 0; j < 4; j++) {
                vec[0] = (((j + 1) % 2) * (j - 1)) * 0.5f;
                vec[1] = ((j % 2) * (j - 2)) * 0.5f;
                glBegin(GL_LINE_STRIP);
-               for(i = 0; i < 3; i++) {
-                       if(i == 1) {
+               for (i = 0; i < 3; i++) {
+                       if (i == 1) {
                                vec[0] *= 0.5f;
                                vec[1] *= 0.5f;
                        }
 
-                       vec[2] = 0.25f * i -0.125f;
+                       vec[2] = 0.25f * i - 0.125f;
                        glVertex3fv(vec);
                }
                glEnd();
@@ -1863,23 +1887,23 @@ static void drawspeaker(Scene *UNUSED(scene), View3D *UNUSED(v3d), RegionView3D
 static void lattice_draw_verts(Lattice *lt, DispList *dl, short sel)
 {
        BPoint *bp = lt->def;
-       float *co = dl?dl->verts:NULL;
+       float *co = dl ? dl->verts : NULL;
        int u, v, w;
 
-       UI_ThemeColor(sel?TH_VERTEX_SELECT:TH_VERTEX);
+       UI_ThemeColor(sel ? TH_VERTEX_SELECT : TH_VERTEX);
        glPointSize(UI_GetThemeValuef(TH_VERTEX_SIZE));
        bglBegin(GL_POINTS);
 
-       for(w=0; w<lt->pntsw; w++) {
-               int wxt = (w==0 || w==lt->pntsw-1);
-               for(v=0; v<lt->pntsv; v++) {
-                       int vxt = (v==0 || v==lt->pntsv-1);
-                       for(u=0; u<lt->pntsu; u++, bp++, co+=3) {
-                               int uxt = (u==0 || u==lt->pntsu-1);
-                               if(!(lt->flag & LT_OUTSIDE) || uxt || vxt || wxt) {
-                                       if(bp->hide==0) {
-                                               if((bp->f1 & SELECT)==sel) {
-                                                       bglVertex3fv(dl?co:bp->vec);
+       for (w = 0; w < lt->pntsw; w++) {
+               int wxt = (w == 0 || w == lt->pntsw - 1);
+               for (v = 0; v < lt->pntsv; v++) {
+                       int vxt = (v == 0 || v == lt->pntsv - 1);
+                       for (u = 0; u < lt->pntsu; u++, bp++, co += 3) {
+                               int uxt = (u == 0 || u == lt->pntsu - 1);
+                               if (!(lt->flag & LT_OUTSIDE) || uxt || vxt || wxt) {
+                                       if (bp->hide == 0) {
+                                               if ((bp->f1 & SELECT) == sel) {
+                                                       bglVertex3fv(dl ? co : bp->vec);
                                                }
                                        }
                                }
@@ -1888,24 +1912,24 @@ static void lattice_draw_verts(Lattice *lt, DispList *dl, short sel)
        }
        
        glPointSize(1.0);
-       bglEnd();       
+       bglEnd();
 }
 
 void lattice_foreachScreenVert(ViewContext *vc, void (*func)(void *userData, BPoint *bp, int x, int y), void *userData)
 {
-       Object *obedit= vc->obedit;
-       Lattice *lt= obedit->data;
+       Object *obedit = vc->obedit;
+       Lattice *lt = obedit->data;
        BPoint *bp = lt->editlatt->latt->def;
        DispList *dl = find_displist(&obedit->disp, DL_VERTS);
-       float *co = dl?dl->verts:NULL;
-       int i, N = lt->editlatt->latt->pntsu*lt->editlatt->latt->pntsv*lt->editlatt->latt->pntsw;
+       float *co = dl ? dl->verts : NULL;
+       int i, N = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
        short s[2] = {IS_CLIPPED, 0};
 
-       ED_view3d_local_clipping(vc->rv3d, obedit->obmat); /* for local clipping lookups */
+       ED_view3d_clipping_local(vc->rv3d, obedit->obmat); /* for local clipping lookups */
 
-       for (i=0; i<N; i++, bp++, co+=3) {
-               if (bp->hide==0) {
-                       view3d_project_short_clip(vc->ar, dl?co:bp->vec, s, 1);
+       for (i = 0; i < N; i++, bp++, co += 3) {
+               if (bp->hide == 0) {
+                       view3d_project_short_clip(vc->ar, dl ? co : bp->vec, s, TRUE);
                        if (s[0] != IS_CLIPPED)
                                func(userData, bp, s[0], s[1]);
                }
@@ -1914,20 +1938,21 @@ void lattice_foreachScreenVert(ViewContext *vc, void (*func)(void *userData, BPo
 
 static void drawlattice__point(Lattice *lt, DispList *dl, int u, int v, int w, int use_wcol)
 {
-       int index = ((w*lt->pntsv + v)*lt->pntsu) + u;
+       int index = ((w * lt->pntsv + v) * lt->pntsu) + u;
 
-       if(use_wcol) {
+       if (use_wcol) {
                float col[3];
-               MDeformWeight *mdw= defvert_find_index (lt->dvert+index, use_wcol-1);
+               MDeformWeight *mdw = defvert_find_index(lt->dvert + index, use_wcol - 1);
                
-               weight_to_rgb(col, mdw?mdw->weight:0.0f);
+               weight_to_rgb(col, mdw ? mdw->weight : 0.0f);
                glColor3fv(col);
 
        }
        
        if (dl) {
-               glVertex3fv(&dl->verts[index*3]);
-       } else {
+               glVertex3fv(&dl->verts[index * 3]);
+       }
+       else {
                glVertex3fv(lt->def[index].vec);
        }
 }
@@ -1935,63 +1960,63 @@ static void drawlattice__point(Lattice *lt, DispList *dl, int u, int v, int w, i
 /* lattice color is hardcoded, now also shows weightgroup values in edit mode */
 static void drawlattice(Scene *scene, View3D *v3d, Object *ob)
 {
-       Lattice *lt= ob->data;
+       Lattice *lt = ob->data;
        DispList *dl;
        int u, v, w;
-       int use_wcol= 0, is_edit= (lt->editlatt != NULL);
+       int use_wcol = 0, is_edit = (lt->editlatt != NULL);
 
        /* now we default make displist, this will modifiers work for non animated case */
-       if(ob->disp.first==NULL)
+       if (ob->disp.first == NULL)
                lattice_calc_modifiers(scene, ob);
-       dl= find_displist(&ob->disp, DL_VERTS);
+       dl = find_displist(&ob->disp, DL_VERTS);
        
-       if(is_edit) {
-               lt= lt->editlatt->latt;
+       if (is_edit) {
+               lt = lt->editlatt->latt;
 
                cpack(0x004000);
                
-               if(ob->defbase.first && lt->dvert) {
-                       use_wcol= ob->actdef;
+               if (ob->defbase.first && lt->dvert) {
+                       use_wcol = ob->actdef;
                        glShadeModel(GL_SMOOTH);
                }
        }
        
        glBegin(GL_LINES);
-       for(w=0; w<lt->pntsw; w++) {
-               int wxt = (w==0 || w==lt->pntsw-1);
-               for(v=0; v<lt->pntsv; v++) {
-                       int vxt = (v==0 || v==lt->pntsv-1);
-                       for(u=0; u<lt->pntsu; u++) {
-                               int uxt = (u==0 || u==lt->pntsu-1);
-
-                               if(w && ((uxt || vxt) || !(lt->flag & LT_OUTSIDE))) {
-                                       drawlattice__point(lt, dl, u, v, w-1, use_wcol);
+       for (w = 0; w < lt->pntsw; w++) {
+               int wxt = (w == 0 || w == lt->pntsw - 1);
+               for (v = 0; v < lt->pntsv; v++) {
+                       int vxt = (v == 0 || v == lt->pntsv - 1);
+                       for (u = 0; u < lt->pntsu; u++) {
+                               int uxt = (u == 0 || u == lt->pntsu - 1);
+
+                               if (w && ((uxt || vxt) || !(lt->flag & LT_OUTSIDE))) {
+                                       drawlattice__point(lt, dl, u, v, w - 1, use_wcol);
                                        drawlattice__point(lt, dl, u, v, w, use_wcol);
                                }
-                               if(v && ((uxt || wxt) || !(lt->flag & LT_OUTSIDE))) {
-                                       drawlattice__point(lt, dl, u, v-1, w, use_wcol);
+                               if (v && ((uxt || wxt) || !(lt->flag & LT_OUTSIDE))) {
+                                       drawlattice__point(lt, dl, u, v - 1, w, use_wcol);
                                        drawlattice__point(lt, dl, u, v, w, use_wcol);
                                }
-                               if(u && ((vxt || wxt) || !(lt->flag & LT_OUTSIDE))) {
-                                       drawlattice__point(lt, dl, u-1, v, w, use_wcol);
+                               if (u && ((vxt || wxt) || !(lt->flag & LT_OUTSIDE))) {
+                                       drawlattice__point(lt, dl, u - 1, v, w, use_wcol);
                                        drawlattice__point(lt, dl, u, v, w, use_wcol);
                                }
                        }
                }
-       }               
+       }
        glEnd();
        
        /* restoration for weight colors */
-       if(use_wcol)
+       if (use_wcol)
                glShadeModel(GL_FLAT);
 
-       if(is_edit) {
-               if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
+       if (is_edit) {
+               if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
                
                lattice_draw_verts(lt, dl, 0);
                lattice_draw_verts(lt, dl, 1);
                
-               if(v3d->zbuf) glEnable(GL_DEPTH_TEST); 
+               if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
        }
 }
 
@@ -1999,62 +2024,65 @@ static void drawlattice(Scene *scene, View3D *v3d, Object *ob)
 
 /* Note! - foreach funcs should be called while drawing or directly after
  * if not, ED_view3d_init_mats_rv3d() can be used for selection tools
- * but would not give correct results with dupli's for eg. which dont
- * use the object matrix in the useual way */
-static void mesh_foreachScreenVert__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+ * but would not give correct results with dupli's for eg. which don't
+ * use the object matrix in the usual way */
+static void mesh_foreachScreenVert__mapFunc(void *userData, int index, const float co[3],
+                                            const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
 {
        foreachScreenVert_userData *data = userData;
-       BMVert *eve = EDBM_get_vert_for_index(data->vc.em, index);
+       BMVert *eve = EDBM_vert_at_index(data->vc.em, index);
 
        if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
-               short s[2]= {IS_CLIPPED, 0};
+               short s[2] = {IS_CLIPPED, 0};
 
                if (data->clipVerts != V3D_CLIP_TEST_OFF) {
-                       view3d_project_short_clip(data->vc.ar, co, s, 1);
-               } else {
+                       view3d_project_short_clip(data->vc.ar, co, s, TRUE);
+               }
+               else {
                        float co2[2];
                        mul_v3_m4v3(co2, data->vc.obedit->obmat, co);
                        project_short_noclip(data->vc.ar, co2, s);
                }
 
-               if (s[0]!=IS_CLIPPED)
+               if (s[0] != IS_CLIPPED)
                        data->func(data->userData, eve, s[0], s[1], index);
        }
 }
 
 void mesh_foreachScreenVert(
-        ViewContext *vc,
-        void (*func)(void *userData, BMVert *eve, int x, int y, int index),
-        void *userData, eV3DClipTest clipVerts)
+    ViewContext *vc,
+    void (*func)(void *userData, BMVert *eve, int x, int y, int index),
+    void *userData, eV3DClipTest clipVerts)
 {
        foreachScreenVert_userData data;
        DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
        
-       data.vc= *vc;
+       data.vc = *vc;
        data.func = func;
        data.userData = userData;
        data.clipVerts = clipVerts;
 
-       if(clipVerts != V3D_CLIP_TEST_OFF)
-               ED_view3d_local_clipping(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+       if (clipVerts != V3D_CLIP_TEST_OFF)
+               ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat);  /* for local clipping lookups */
 
-       EDBM_init_index_arrays(vc->em, 1, 0, 0);
+       EDBM_index_arrays_init(vc->em, 1, 0, 0);
        dm->foreachMappedVert(dm, mesh_foreachScreenVert__mapFunc, &data);
-       EDBM_free_index_arrays(vc->em);
+       EDBM_index_arrays_free(vc->em);
 
        dm->release(dm);
 }
 
 /*  draw callback */
-static void drawSelectedVertices__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+static void drawSelectedVertices__mapFunc(void *userData, int index, const float co[3],
+                                          const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
 {
        MVert *mv = &((MVert *)userData)[index];
 
-       if(!(mv->flag & ME_HIDE)) {
-               const char sel= mv->flag & SELECT;
+       if (!(mv->flag & ME_HIDE)) {
+               const char sel = mv->flag & SELECT;
 
                // TODO define selected color
-               if(sel) {
+               if (sel) {
                        glColor3f(1.0f, 1.0f, 0.0f);
                }
                else {
@@ -2071,25 +2099,18 @@ static void drawSelectedVertices(DerivedMesh *dm, Mesh *me)
        dm->foreachMappedVert(dm, drawSelectedVertices__mapFunc, me->mvert);
        glEnd();
 }
-static int is_co_in_region(ARegion *ar, const short co[2])
-{
-       return ( (co[0] != IS_CLIPPED) && /* may be the only initialized value, check first */
-                (co[0] >= 0)          &&
-                (co[0] <  ar->winx)   &&
-                (co[1] >= 0)          &&
-                (co[1] <  ar->winy));
-}
-static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, float *v0co, float *v1co)
+
+static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, const float v0co[3], const float v1co[3])
 {
        foreachScreenEdge_userData *data = userData;
-       BMEdge *eed = EDBM_get_edge_for_index(data->vc.em, index);
+       BMEdge *eed = EDBM_edge_at_index(data->vc.em, index);
 
        if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
                short s[2][2];
 
                if (data->clipVerts == V3D_CLIP_TEST_RV3D_CLIPPING) {
-                       view3d_project_short_clip(data->vc.ar, v0co, s[0], 1);
-                       view3d_project_short_clip(data->vc.ar, v1co, s[1], 1);
+                       view3d_project_short_clip(data->vc.ar, v0co, s[0], TRUE);
+                       view3d_project_short_clip(data->vc.ar, v1co, s[1], TRUE);
                }
                else {
                        float v1_co[3], v2_co[3];
@@ -2101,9 +2122,10 @@ static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, float *v0
                        project_short_noclip(data->vc.ar, v2_co, s[1]);
 
                        if (data->clipVerts == V3D_CLIP_TEST_REGION) {
-                               if ( !is_co_in_region(data->vc.ar, s[0]) &&
-                                    !is_co_in_region(data->vc.ar, s[1]))
-                               {
+                               /* make an int copy */
+                               int s_int[2][2] = {{s[0][0], s[0][1]},
+                                                  {s[1][0], s[1][1]}};
+                               if (!BLI_segment_in_rcti(&data->win_rect, s_int[0], s_int[1])) {
                                        return;
                                }
                        }
@@ -2114,32 +2136,38 @@ static void mesh_foreachScreenEdge__mapFunc(void *userData, int index, float *v0
 }
 
 void mesh_foreachScreenEdge(
-        ViewContext *vc,
-        void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index),
-        void *userData, eV3DClipTest clipVerts)
+    ViewContext *vc,
+    void (*func)(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int index),
+    void *userData, eV3DClipTest clipVerts)
 {
        foreachScreenEdge_userData data;
        DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
 
-       data.vc= *vc;
+       data.vc = *vc;
+
+       data.win_rect.xmin = 0;
+       data.win_rect.ymin = 0;
+       data.win_rect.xmax = vc->ar->winx;
+       data.win_rect.ymax = vc->ar->winy;
+
        data.func = func;
        data.userData = userData;
        data.clipVerts = clipVerts;
 
-       if(clipVerts != V3D_CLIP_TEST_OFF)
-               ED_view3d_local_clipping(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+       if (clipVerts != V3D_CLIP_TEST_OFF)
+               ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat);  /* for local clipping lookups */
 
-       EDBM_init_index_arrays(vc->em, 0, 1, 0);
+       EDBM_index_arrays_init(vc->em, 0, 1, 0);
        dm->foreachMappedEdge(dm, mesh_foreachScreenEdge__mapFunc, &data);
-       EDBM_free_index_arrays(vc->em);
+       EDBM_index_arrays_free(vc->em);
 
        dm->release(dm);
 }
 
-static void mesh_foreachScreenFace__mapFunc(void *userData, int index, float *cent, float *UNUSED(no))
+static void mesh_foreachScreenFace__mapFunc(void *userData, int index, const float cent[3], const float UNUSED(no[3]))
 {
        foreachScreenFace_userData *data = userData;
-       BMFace *efa = EDBM_get_face_for_index(data->vc.em, index);
+       BMFace *efa = EDBM_face_at_index(data->vc.em, index);
 
        if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
                float cent2[3];
@@ -2155,59 +2183,60 @@ static void mesh_foreachScreenFace__mapFunc(void *userData, int index, float *ce
 }
 
 void mesh_foreachScreenFace(
-        ViewContext *vc,
-        void (*func)(void *userData, BMFace *efa, int x, int y, int index),
-        void *userData)
+    ViewContext *vc,
+    void (*func)(void *userData, BMFace *efa, int x, int y, int index),
+    void *userData)
 {
        foreachScreenFace_userData data;
        DerivedMesh *dm = editbmesh_get_derived_cage(vc->scene, vc->obedit, vc->em, CD_MASK_BAREMESH);
 
-       data.vc= *vc;
+       data.vc = *vc;
        data.func = func;
        data.userData = userData;
 
-       //if(clipVerts)
-       ED_view3d_local_clipping(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+       //if (clipVerts)
+       ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
 
-       EDBM_init_index_arrays(vc->em, 0, 0, 1);
+       EDBM_index_arrays_init(vc->em, 0, 0, 1);
        dm->foreachMappedFaceCenter(dm, mesh_foreachScreenFace__mapFunc, &data);
-       EDBM_free_index_arrays(vc->em);
+       EDBM_index_arrays_free(vc->em);
 
        dm->release(dm);
 }
 
 void nurbs_foreachScreenVert(
-        ViewContext *vc,
-        void (*func)(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, int x, int y),
-        void *userData)
+    ViewContext *vc,
+    void (*func)(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, int x, int y),
+    void *userData)
 {
-       Curve *cu= vc->obedit->data;
+       Curve *cu = vc->obedit->data;
        short s[2] = {IS_CLIPPED, 0};
        Nurb *nu;
        int i;
-       ListBase *nurbs= curve_editnurbs(cu);
+       ListBase *nurbs = BKE_curve_editNurbs_get(cu);
 
-       ED_view3d_local_clipping(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+       ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
 
-       for (nu= nurbs->first; nu; nu=nu->next) {
-               if(nu->type == CU_BEZIER) {
-                       for (i=0; i<nu->pntsu; i++) {
+       for (nu = nurbs->first; nu; nu = nu->next) {
+               if (nu->type == CU_BEZIER) {
+                       for (i = 0; i < nu->pntsu; i++) {
                                BezTriple *bezt = &nu->bezt[i];
 
-                               if(bezt->hide==0) {
+                               if (bezt->hide == 0) {
                                        
-                                       if(cu->drawflag & CU_HIDE_HANDLES) {
-                                               view3d_project_short_clip(vc->ar, bezt->vec[1], s, 1);
+                                       if (cu->drawflag & CU_HIDE_HANDLES) {
+                                               view3d_project_short_clip(vc->ar, bezt->vec[1], s, TRUE);
                                                if (s[0] != IS_CLIPPED)
                                                        func(userData, nu, NULL, bezt, 1, s[0], s[1]);
-                                       } else {
-                                               view3d_project_short_clip(vc->ar, bezt->vec[0], s, 1);
+                                       }
+                                       else {
+                                               view3d_project_short_clip(vc->ar, bezt->vec[0], s, TRUE);
                                                if (s[0] != IS_CLIPPED)
                                                        func(userData, nu, NULL, bezt, 0, s[0], s[1]);
-                                               view3d_project_short_clip(vc->ar, bezt->vec[1], s, 1);
+                                               view3d_project_short_clip(vc->ar, bezt->vec[1], s, TRUE);
                                                if (s[0] != IS_CLIPPED)
                                                        func(userData, nu, NULL, bezt, 1, s[0], s[1]);
-                                               view3d_project_short_clip(vc->ar, bezt->vec[2], s, 1);
+                                               view3d_project_short_clip(vc->ar, bezt->vec[2], s, TRUE);
                                                if (s[0] != IS_CLIPPED)
                                                        func(userData, nu, NULL, bezt, 2, s[0], s[1]);
                                        }
@@ -2215,11 +2244,11 @@ void nurbs_foreachScreenVert(
                        }
                }
                else {
-                       for (i=0; i<nu->pntsu*nu->pntsv; i++) {
+                       for (i = 0; i < nu->pntsu * nu->pntsv; i++) {
                                BPoint *bp = &nu->bp[i];
 
-                               if(bp->hide==0) {
-                                       view3d_project_short_clip(vc->ar, bp->vec, s, 1);
+                               if (bp->hide == 0) {
+                                       view3d_project_short_clip(vc->ar, bp->vec, s, TRUE);
                                        if (s[0] != IS_CLIPPED)
                                                func(userData, nu, bp, NULL, -1, s[0], s[1]);
                                }
@@ -2239,10 +2268,10 @@ void nurbs_foreachScreenVert(
  * logic!!!
  */
 
-static void draw_dm_face_normals__mapFunc(void *userData, int index, float *cent, float *no)
+static void draw_dm_face_normals__mapFunc(void *userData, int index, const float cent[3], const float no[3])
 {
        drawDMNormal_userData *data = userData;
-       BMFace *efa = EDBM_get_face_for_index(data->em, index);
+       BMFace *efa = EDBM_face_at_index(data->em, index);
 
        if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
                glVertex3fv(cent);
@@ -2263,12 +2292,12 @@ static void draw_dm_face_normals(BMEditMesh *em, Scene *scene, DerivedMesh *dm)
        glEnd();
 }
 
-static void draw_dm_face_centers__mapFunc(void *userData, int index, float *cent, float *UNUSED(no))
+static void draw_dm_face_centers__mapFunc(void *userData, int index, const float cent[3], const float UNUSED(no[3]))
 {
-       BMFace *efa = EDBM_get_face_for_index(((void **)userData)[0], index);
+       BMFace *efa = EDBM_face_at_index(((void **)userData)[0], index);
        int sel = *(((int **)userData)[1]);
        
-       if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BM_elem_flag_test(efa, BM_ELEM_SELECT)==sel) {
+       if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BM_elem_flag_test(efa, BM_ELEM_SELECT) == sel) {
                bglVertex3fv(cent);
        }
 }
@@ -2281,10 +2310,10 @@ static void draw_dm_face_centers(BMEditMesh *em, DerivedMesh *dm, int sel)
        bglEnd();
 }
 
-static void draw_dm_vert_normals__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
+static void draw_dm_vert_normals__mapFunc(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3])
 {
        drawDMNormal_userData *data = userData;
-       BMVert *eve = EDBM_get_vert_for_index(data->em, index);
+       BMVert *eve = EDBM_vert_at_index(data->em, index);
 
        if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
                glVertex3fv(co);
@@ -2314,14 +2343,15 @@ static void draw_dm_vert_normals(BMEditMesh *em, Scene *scene, DerivedMesh *dm)
 }
 
 /* Draw verts with color set based on selection */
-static void draw_dm_verts__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+static void draw_dm_verts__mapFunc(void *userData, int index, const float co[3],
+                                   const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
 {
-       drawDMVerts_userData * data = userData;
-       BMVert *eve = EDBM_get_vert_for_index(data->em, index);
+       drawDMVerts_userData *data = userData;
+       BMVert *eve = EDBM_vert_at_index(data->em, index);
 
-       if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BM_elem_flag_test(eve, BM_ELEM_SELECT)==data->sel) {
+       if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BM_elem_flag_test(eve, BM_ELEM_SELECT) == data->sel) {
                /* draw active larger - need to stop/start point drawing for this :/ */
-               if (eve==data->eve_act) {
+               if (eve == data->eve_act) {
                        float size = UI_GetThemeValuef(TH_VERTEX_SIZE);
                        UI_ThemeColor4(TH_EDITMESH_ACTIVE);
                        
@@ -2332,10 +2362,11 @@ static void draw_dm_verts__mapFunc(void *userData, int index, float *co, float *
                        bglVertex3fv(co);
                        bglEnd();
                        
-                       UI_ThemeColor4(data->sel?TH_VERTEX_SELECT:TH_VERTEX);
+                       UI_ThemeColor4(data->sel ? TH_VERTEX_SELECT : TH_VERTEX);
                        glPointSize(size);
                        bglBegin(GL_POINTS);
-               } else {
+               }
+               else {
                        bglVertex3fv(co);
                }
        }
@@ -2353,37 +2384,41 @@ static void draw_dm_verts(BMEditMesh *em, DerivedMesh *dm, int sel, BMVert *eve_
        bglEnd();
 }
 
-       /* Draw edges with color set based on selection */
-static int draw_dm_edges_sel__setDrawOptions(void *userData, int index)
+/* Draw edges with color set based on selection */
+static DMDrawOption draw_dm_edges_sel__setDrawOptions(void *userData, int index)
 {
        BMEdge *eed;
        //unsigned char **cols = userData, *col;
-       drawDMEdgesSel_userData * data = userData;
+       drawDMEdgesSel_userData *data = userData;
        unsigned char *col;
 
-       eed = EDBM_get_edge_for_index(data->em, index);
+       eed = EDBM_edge_at_index(data->em, index);
 
        if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
-               if (eed==data->eed_act) {
+               if (eed == data->eed_act) {
                        glColor4ubv(data->actCol);
-               } else {
+               }
+               else {
                        if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
                                col = data->selCol;
-                       } else {
+                       }
+                       else {
                                col = data->baseCol;
                        }
                        /* no alpha, this is used so a transparent color can disable drawing unselected edges in editmode  */
-                       if (col[3]==0) return 0;
+                       if (col[3] == 0)
+                               return DM_DRAW_OPTION_SKIP;
                        
                        glColor4ubv(col);
                }
-               return 1;
-       } else {
-               return 0;
+               return DM_DRAW_OPTION_NORMAL;
+       }
+       else {
+               return DM_DRAW_OPTION_SKIP;
        }
 }
 static void draw_dm_edges_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol, 
-                             unsigned char *selCol, unsigned char *actCol, BMEdge *eed_act) 
+                              unsigned char *selCol, unsigned char *actCol, BMEdge *eed_act)
 {
        drawDMEdgesSel_userData data;
        
@@ -2395,32 +2430,39 @@ static void draw_dm_edges_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *ba
        dm->drawMappedEdges(dm, draw_dm_edges_sel__setDrawOptions, &data);
 }
 
-       /* Draw edges */
-static int draw_dm_edges__setDrawOptions(void *userData, int index)
+/* Draw edges */
+static DMDrawOption draw_dm_edges__setDrawOptions(void *userData, int index)
 {
-       return !BM_elem_flag_test(EDBM_get_edge_for_index(userData, index), BM_ELEM_HIDDEN);
+       if (BM_elem_flag_test(EDBM_edge_at_index(userData, index), BM_ELEM_HIDDEN))
+               return DM_DRAW_OPTION_SKIP;
+       else
+               return DM_DRAW_OPTION_NORMAL;
 }
+
 static void draw_dm_edges(BMEditMesh *em, DerivedMesh *dm) 
 {
        dm->drawMappedEdges(dm, draw_dm_edges__setDrawOptions, em);
 }
 
-       /* Draw edges with color interpolated based on selection */
-static int draw_dm_edges_sel_interp__setDrawOptions(void *userData, int index)
+/* Draw edges with color interpolated based on selection */
+static DMDrawOption draw_dm_edges_sel_interp__setDrawOptions(void *userData, int index)
 {
-       return !BM_elem_flag_test(EDBM_get_edge_for_index(((void**)userData)[0], index), BM_ELEM_HIDDEN);
+       if (BM_elem_flag_test(EDBM_edge_at_index(((void **)userData)[0], index), BM_ELEM_HIDDEN))
+               return DM_DRAW_OPTION_SKIP;
+       else
+               return DM_DRAW_OPTION_NORMAL;
 }
 static void draw_dm_edges_sel_interp__setDrawInterpOptions(void *userData, int index, float t)
 {
-       BMEdge *eed = EDBM_get_edge_for_index(((void**)userData)[0], index);
+       BMEdge *eed = EDBM_edge_at_index(((void **)userData)[0], index);
        unsigned char **cols = userData;
-       unsigned char *col0 = cols[(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT))?2:1];
-       unsigned char *col1 = cols[(BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))?2:1];
+       unsigned char *col0 = cols[(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT)) ? 2 : 1];
+       unsigned char *col1 = cols[(BM_elem_flag_test(eed->v2, BM_ELEM_SELECT)) ? 2 : 1];
 
-       glColor4ub(     col0[0] + (col1[0]-col0[0])*t,
-                               col0[1] + (col1[1]-col0[1])*t,
-                               col0[2] + (col1[2]-col0[2])*t,
-                               col0[3] + (col1[3]-col0[3])*t);
+       glColor4ub(col0[0] + (col1[0] - col0[0]) * t,
+                  col0[1] + (col1[1] - col0[1]) * t,
+                  col0[2] + (col1[2] - col0[2]) * t,
+                  col0[3] + (col1[3] - col0[3]) * t);
 }
 
 static void draw_dm_edges_sel_interp(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol, unsigned char *selCol)
@@ -2430,12 +2472,15 @@ static void draw_dm_edges_sel_interp(BMEditMesh *em, DerivedMesh *dm, unsigned c
        dm->drawMappedEdgesInterp(dm, draw_dm_edges_sel_interp__setDrawOptions, draw_dm_edges_sel_interp__setDrawInterpOptions, cols);
 }
 
-       /* Draw only seam edges */
-static int draw_dm_edges_seams__setDrawOptions(void *userData, int index)
+/* Draw only seam edges */
+static DMDrawOption draw_dm_edges_seams__setDrawOptions(void *userData, int index)
 {
-       BMEdge *eed = EDBM_get_edge_for_index(userData, index);
+       BMEdge *eed = EDBM_edge_at_index(userData, index);
 
-       return !BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BM_elem_flag_test(eed, BM_ELEM_SEAM);
+       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BM_elem_flag_test(eed, BM_ELEM_SEAM))
+               return DM_DRAW_OPTION_NORMAL;
+       else
+               return DM_DRAW_OPTION_SKIP;
 }
 
 static void draw_dm_edges_seams(BMEditMesh *em, DerivedMesh *dm)
@@ -2443,42 +2488,63 @@ static void draw_dm_edges_seams(BMEditMesh *em, DerivedMesh *dm)
        dm->drawMappedEdges(dm, draw_dm_edges_seams__setDrawOptions, em);
 }
 
-       /* Draw only sharp edges */
-static int draw_dm_edges_sharp__setDrawOptions(void *userData, int index)
+/* Draw only sharp edges */
+static DMDrawOption draw_dm_edges_sharp__setDrawOptions(void *userData, int index)
 {
-       BMEdge *eed = EDBM_get_edge_for_index(userData, index);
+       BMEdge *eed = EDBM_edge_at_index(userData, index);
 
-       return !BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BM_elem_flag_test(eed, BM_ELEM_SHARP);
+       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && !BM_elem_flag_test(eed, BM_ELEM_SMOOTH))
+               return DM_DRAW_OPTION_NORMAL;
+       else
+               return DM_DRAW_OPTION_SKIP;
 }
+
 static void draw_dm_edges_sharp(BMEditMesh *em, DerivedMesh *dm)
 {
        dm->drawMappedEdges(dm, draw_dm_edges_sharp__setDrawOptions, em);
 }
 
+/* Draw only Freestyle feature edges */
+static DMDrawOption draw_dm_edges_freestyle__setDrawOptions(void *userData, int index)
+{
+       BMEdge *eed = EDBM_edge_at_index(userData, index);
+
+       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BM_elem_flag_test(eed, BM_ELEM_FREESTYLE))
+               return DM_DRAW_OPTION_NORMAL;
+       else
+               return DM_DRAW_OPTION_SKIP;
+}
+
+static void draw_dm_edges_freestyle(BMEditMesh *em, DerivedMesh *dm)
+{
+       dm->drawMappedEdges(dm, draw_dm_edges_freestyle__setDrawOptions, em);
+}
 
-       /* Draw faces with color set based on selection
       * return 2 for the active face so it renders with stipple enabled */
-static int draw_dm_faces_sel__setDrawOptions(void *userData, int index, int *UNUSED(drawSmooth_r))
+/* Draw faces with color set based on selection
+ * return 2 for the active face so it renders with stipple enabled */
+static DMDrawOption draw_dm_faces_sel__setDrawOptions(void *userData, int index)
 {
-       drawDMFacesSel_userData * data = userData;
-       BMFace *efa = EDBM_get_face_for_index(data->em, index);
+       drawDMFacesSel_userData *data = userData;
+       BMFace *efa = EDBM_face_at_index(data->em, index);
        unsigned char *col;
        
        if (!efa)
-               return 0;
+               return DM_DRAW_OPTION_SKIP;
        
        if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
                if (efa == data->efa_act) {
-                       glColor4ubv(data->cols[2]);
-                       return 2; /* stipple */
-               } else {
-                       col = data->cols[BM_elem_flag_test(efa, BM_ELEM_SELECT)?1:0];
-                       if (col[3]==0) return 0;
+                       glColor4ubv(data->cols[3]);
+                       return DM_DRAW_OPTION_STIPPLE;
+               }
+               else {
+                       col = data->cols[BM_elem_flag_test(efa, BM_ELEM_SELECT) ? 1 : BM_elem_flag_test(efa, BM_ELEM_FREESTYLE) ? 2 : 0];
+                       if (col[3] == 0)
+                               return DM_DRAW_OPTION_SKIP;
                        glColor4ubv(col);
-                       return 1;
+                       return DM_DRAW_OPTION_NORMAL;
                }
        }
-       return 0;
+       return DM_DRAW_OPTION_SKIP;
 }
 
 static int draw_dm_faces_sel__compareDrawOptions(void *userData, int index, int next_index)
@@ -2490,22 +2556,22 @@ static int draw_dm_faces_sel__compareDrawOptions(void *userData, int index, int
 
        unsigned char *col, *next_col;
 
-       if(!data->orig_index)
+       if (!data->orig_index)
                return 0;
 
-       efa= EDBM_get_face_for_index(data->em, data->orig_index[index]);
-       next_efa= EDBM_get_face_for_index(data->em, data->orig_index[next_index]);
+       efa = EDBM_face_at_index(data->em, data->orig_index[index]);
+       next_efa = EDBM_face_at_index(data->em, data->orig_index[next_index]);
 
-       if(efa == next_efa)
+       if (efa == next_efa)
                return 1;
 
-       if(efa == data->efa_act || next_efa == data->efa_act)
+       if (efa == data->efa_act || next_efa == data->efa_act)
                return 0;
 
-       col = data->cols[BM_elem_flag_test(efa, BM_ELEM_SELECT)?1:0];
-       next_col = data->cols[BM_elem_flag_test(next_efa, BM_ELEM_SELECT)?1:0];
+       col = data->cols[BM_elem_flag_test(efa, BM_ELEM_SELECT) ? 1 : BM_elem_flag_test(efa, BM_ELEM_FREESTYLE) ? 2 : 0];
+       next_col = data->cols[BM_elem_flag_test(next_efa, BM_ELEM_SELECT) ? 1 : BM_elem_flag_test(next_efa, BM_ELEM_FREESTYLE) ? 2 : 0];
 
-       if(col[3]==0 || next_col[3]==0)
+       if (col[3] == 0 || next_col[3] == 0)
                return 0;
 
        return col == next_col;
@@ -2513,34 +2579,36 @@ static int draw_dm_faces_sel__compareDrawOptions(void *userData, int index, int
 
 /* also draws the active face */
 static void draw_dm_faces_sel(BMEditMesh *em, DerivedMesh *dm, unsigned char *baseCol, 
-                             unsigned char *selCol, unsigned char *actCol, BMFace *efa_act)
+                              unsigned char *selCol, unsigned char *markCol, unsigned char *actCol, BMFace *efa_act)
 {
        drawDMFacesSel_userData data;
-       data.dm= dm;
+       data.dm = dm;
        data.cols[0] = baseCol;
        data.em = em;
        data.cols[1] = selCol;
-       data.cols[2] = actCol;
+       data.cols[2] = markCol;
+       data.cols[3] = actCol;
        data.efa_act = efa_act;
        data.orig_index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
 
        dm->drawMappedFaces(dm, draw_dm_faces_sel__setDrawOptions, GPU_enable_material, draw_dm_faces_sel__compareDrawOptions, &data, 0);
 }
 
-static int draw_dm_creases__setDrawOptions(void *userData, int index)
+static DMDrawOption draw_dm_creases__setDrawOptions(void *userData, int index)
 {
        BMEditMesh *em = userData;
-       BMEdge *eed = EDBM_get_edge_for_index(userData, index);
+       BMEdge *eed = EDBM_edge_at_index(userData, index);
        float *crease = eed ? (float *)CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_CREASE) : NULL;
        
        if (!crease)
-               return 0;
+               return DM_DRAW_OPTION_SKIP;
        
-       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && *crease!=0.0f) {
+       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && *crease != 0.0f) {
                UI_ThemeColorBlend(TH_WIRE, TH_EDGE_CREASE, *crease);
-               return 1;
-       } else {
-               return 0;
+               return DM_DRAW_OPTION_NORMAL;
+       }
+       else {
+               return DM_DRAW_OPTION_SKIP;
        }
 }
 static void draw_dm_creases(BMEditMesh *em, DerivedMesh *dm)
@@ -2550,39 +2618,41 @@ static void draw_dm_creases(BMEditMesh *em, DerivedMesh *dm)
        glLineWidth(1.0);
 }
 
-static int draw_dm_bweights__setDrawOptions(void *userData, int index)
+static DMDrawOption draw_dm_bweights__setDrawOptions(void *userData, int index)
 {
        BMEditMesh *em = userData;
-       BMEdge *eed = EDBM_get_edge_for_index(userData, index);
+       BMEdge *eed = EDBM_edge_at_index(userData, index);
        float *bweight = (float *)CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_BWEIGHT);
 
        if (!bweight)
-               return 0;
+               return DM_DRAW_OPTION_SKIP;
        
-       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && *bweight!=0.0f) {
+       if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && *bweight != 0.0f) {
                UI_ThemeColorBlend(TH_WIRE, TH_EDGE_SELECT, *bweight);
-               return 1;
-       } else {
-               return 0;
+               return DM_DRAW_OPTION_NORMAL;
+       }
+       else {
+               return DM_DRAW_OPTION_SKIP;
        }
 }
-static void draw_dm_bweights__mapFunc(void *userData, int index, float *co, float *UNUSED(no_f), short *UNUSED(no_s))
+static void draw_dm_bweights__mapFunc(void *userData, int index, const float co[3],
+                                      const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
 {
        BMEditMesh *em = userData;
-       BMVert *eve = EDBM_get_vert_for_index(userData, index);
+       BMVert *eve = EDBM_vert_at_index(userData, index);
        float *bweight = (float *)CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_BWEIGHT);
        
        if (!bweight)
                return;
        
-       if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && *bweight!=0.0f) {
+       if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && *bweight != 0.0f) {
                UI_ThemeColorBlend(TH_VERTEX, TH_VERTEX_SELECT, *bweight);
                bglVertex3fv(co);
        }
 }
 static void draw_dm_bweights(BMEditMesh *em, Scene *scene, DerivedMesh *dm)
 {
-       ToolSettings *ts= scene->toolsettings;
+       ToolSettings *ts = scene->toolsettings;
 
        if (ts->selectmode & SCE_SELECT_VERTEX) {
                glPointSize(UI_GetThemeValuef(TH_VERTEX_SIZE) + 2);
@@ -2609,58 +2679,60 @@ static void draw_dm_bweights(BMEditMesh *em, Scene *scene, DerivedMesh *dm)
 static void draw_em_fancy_verts(Scene *scene, View3D *v3d, Object *obedit, 
                                 BMEditMesh *em, DerivedMesh *cageDM, BMVert *eve_act)
 {
-       ToolSettings *ts= scene->toolsettings;
+       ToolSettings *ts = scene->toolsettings;
        int sel;
 
-       if(v3d->zbuf) glDepthMask(0);           // disable write in zbuffer, zbuf select
+       if (v3d->zbuf) glDepthMask(0);      // disable write in zbuffer, zbuf select
 
-       for (sel=0; sel<2; sel++) {
+       for (sel = 0; sel < 2; sel++) {
                unsigned char col[4], fcol[4];
                int pass;
 
-               UI_GetThemeColor3ubv(sel?TH_VERTEX_SELECT:TH_VERTEX, col);
-               UI_GetThemeColor3ubv(sel?TH_FACE_DOT:TH_WIRE, fcol);
+               UI_GetThemeColor3ubv(sel ? TH_VERTEX_SELECT : TH_VERTEX, col);
+               UI_GetThemeColor3ubv(sel ? TH_FACE_DOT : TH_WIRE, fcol);
 
-               for (pass=0; pass<2; pass++) {
+               for (pass = 0; pass < 2; pass++) {
                        float size = UI_GetThemeValuef(TH_VERTEX_SIZE);
                        float fsize = UI_GetThemeValuef(TH_FACEDOT_SIZE);
 
-                       if (pass==0) {
-                               if(v3d->zbuf && !(v3d->flag&V3D_ZBUF_SELECT)) {
+                       if (pass == 0) {
+                               if (v3d->zbuf && !(v3d->flag & V3D_ZBUF_SELECT)) {
                                        glDisable(GL_DEPTH_TEST);
-                                               
+
                                        glEnable(GL_BLEND);
-                               } else {
+                               }
+                               else {
                                        continue;
                                }
 
-                               size = (size > 2.1f ? size/2.0f:size);
-                               fsize = (fsize > 2.1f ? fsize/2.0f:fsize);
+                               size = (size > 2.1f ? size / 2.0f : size);
+                               fsize = (fsize > 2.1f ? fsize / 2.0f : fsize);
                                col[3] = fcol[3] = 100;
-                       } else {
+                       }
+                       else {
                                col[3] = fcol[3] = 255;
                        }
-                               
-                       if(ts->selectmode & SCE_SELECT_VERTEX) {
+
+                       if (ts->selectmode & SCE_SELECT_VERTEX) {
                                glPointSize(size);
                                glColor4ubv(col);
                                draw_dm_verts(em, cageDM, sel, eve_act);
                        }
                        
-                       if(check_ob_drawface_dot(scene, v3d, obedit->dt)) {
+                       if (check_ob_drawface_dot(scene, v3d, obedit->dt)) {
                                glPointSize(fsize);
                                glColor4ubv(fcol);
                                draw_dm_face_centers(em, cageDM, sel);
                        }
                        
-                       if (pass==0) {
+                       if (pass == 0) {
                                glDisable(GL_BLEND);
                                glEnable(GL_DEPTH_TEST);
                        }
                }
        }
 
-       if(v3d->zbuf) glDepthMask(1);
+       if (v3d->zbuf) glDepthMask(1);
        glPointSize(1.0);
 }
 
@@ -2668,7 +2740,7 @@ static void draw_em_fancy_edges(BMEditMesh *em, Scene *scene, View3D *v3d,
                                 Mesh *me, DerivedMesh *cageDM, short sel_only,
                                 BMEdge *eed_act)
 {
-       ToolSettings *ts= scene->toolsettings;
+       ToolSettings *ts = scene->toolsettings;
        int pass;
        unsigned char wireCol[4], selCol[4], actCol[4];
 
@@ -2677,36 +2749,39 @@ static void draw_em_fancy_edges(BMEditMesh *em, Scene *scene, View3D *v3d,
        UI_GetThemeColor4ubv(TH_WIRE, wireCol);
        UI_GetThemeColor4ubv(TH_EDITMESH_ACTIVE, actCol);
        
-       /* when sel only is used, dont render wire, only selected, this is used for
+       /* when sel only is used, don't render wire, only selected, this is used for
         * textured draw mode when the 'edges' option is disabled */
        if (sel_only)
                wireCol[3] = 0;
 
-       for (pass=0; pass<2; pass++) {
-                       /* show wires in transparant when no zbuf clipping for select */
-               if (pass==0) {
-                       if (v3d->zbuf && (v3d->flag & V3D_ZBUF_SELECT)==0) {
+       for (pass = 0; pass < 2; pass++) {
+               /* show wires in transparant when no zbuf clipping for select */
+               if (pass == 0) {
+                       if (v3d->zbuf && (v3d->flag & V3D_ZBUF_SELECT) == 0) {
                                glEnable(GL_BLEND);
                                glDisable(GL_DEPTH_TEST);
                                selCol[3] = 85;
                                if (!sel_only) wireCol[3] = 85;
-                       } else {
+                       }
+                       else {
                                continue;
                        }
-               } else {
+               }
+               else {
                        selCol[3] = 255;
                        if (!sel_only) wireCol[3] = 255;
                }
 
-               if(ts->selectmode == SCE_SELECT_FACE) {
+               if (ts->selectmode == SCE_SELECT_FACE) {
                        draw_dm_edges_sel(em, cageDM, wireCol, selCol, actCol, eed_act);
-               }       
-               else if( (me->drawflag & ME_DRAWEDGES) || (ts->selectmode & SCE_SELECT_EDGE) ) {        
-                       if(cageDM->drawMappedEdgesInterp && (ts->selectmode & SCE_SELECT_VERTEX)) {
+               }
+               else if ( (me->drawflag & ME_DRAWEDGES) || (ts->selectmode & SCE_SELECT_EDGE) ) {
+                       if (cageDM->drawMappedEdgesInterp && (ts->selectmode & SCE_SELECT_VERTEX)) {
                                glShadeModel(GL_SMOOTH);
                                draw_dm_edges_sel_interp(em, cageDM, wireCol, selCol);
                                glShadeModel(GL_FLAT);
-                       } else {
+                       }
+                       else {
                                draw_dm_edges_sel(em, cageDM, wireCol, selCol, actCol, eed_act);
                        }
                }
@@ -2717,7 +2792,7 @@ static void draw_em_fancy_edges(BMEditMesh *em, Scene *scene, View3D *v3d,
                        }
                }
 
-               if (pass==0) {
+               if (pass == 0) {
                        glDisable(GL_BLEND);
                        glEnable(GL_DEPTH_TEST);
                }
@@ -2726,50 +2801,53 @@ static void draw_em_fancy_edges(BMEditMesh *em, Scene *scene, View3D *v3d,
 
 static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitSettings *unit)
 {
-       Mesh *me= ob->data;
+       const short txt_flag = V3D_CACHE_TEXT_ASCII | V3D_CACHE_TEXT_LOCALCLIP;
+       Mesh *me = ob->data;
        float v1[3], v2[3], v3[3], vmid[3], fvec[3];
        char numstr[32]; /* Stores the measurement display text here */
        const char *conv_float; /* Use a float conversion matching the grid size */
-       unsigned char col[4]= {0, 0, 0, 255}; /* color of the text to draw */
+       unsigned char col[4] = {0, 0, 0, 255}; /* color of the text to draw */
        float area; /* area of the face */
-       float grid= unit->system ? unit->scale_length : v3d->grid;
-       const int do_split= unit->flag & USER_UNIT_OPT_SPLIT;
-       const int do_global= v3d->flag & V3D_GLOBAL_STATS;
-       const int do_moving= G.moving;
+       float grid = unit->system ? unit->scale_length : v3d->grid;
+       const int do_split = unit->flag & USER_UNIT_OPT_SPLIT;
+       const int do_global = v3d->flag & V3D_GLOBAL_STATS;
+       const int do_moving = G.moving;
 
        BMIter iter;
        int i;
 
        /* make the precision of the pronted value proportionate to the gridsize */
 
-       if (grid < 0.01f)               conv_float= "%.6g";
-       else if (grid < 0.1f)   conv_float= "%.5g";
-       else if (grid < 1.0f)   conv_float= "%.4g";
-       else if (grid < 10.0f)  conv_float= "%.3g";
-       else                                    conv_float= "%.2g";
+       if (grid < 0.01f) conv_float = "%.6g";
+       else if (grid < 0.1f) conv_float = "%.5g";
+       else if (grid < 1.0f) conv_float = "%.4g";
+       else if (grid < 10.0f) conv_float = "%.3g";
+       else conv_float = "%.2g";
        
-       if(me->drawflag & ME_DRAWEXTRA_EDGELEN) {
+       if (me->drawflag & ME_DRAWEXTRA_EDGELEN) {
                BMEdge *eed;
 
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_EDGELEN, col);
 
                eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
-               for(; eed; eed=BM_iter_step(&iter)) {
+               for (; eed; eed = BM_iter_step(&iter)) {
                        /* draw selected edges, or edges next to selected verts while draging */
-                       if(BM_elem_flag_test(eed, BM_ELEM_SELECT) ||
-                               (do_moving && (BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) || BM_elem_flag_test(eed->v2, BM_ELEM_SELECT) ))) {
+                       if (BM_elem_flag_test(eed, BM_ELEM_SELECT) ||
+                           (do_moving && (BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) ||
+                                          BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))))
+                       {
 
                                copy_v3_v3(v1, eed->v1->co);
                                copy_v3_v3(v2, eed->v2->co);
 
                                mid_v3_v3v3(vmid, v1, v2);
 
-                               if(do_global) {
+                               if (do_global) {
                                        mul_mat3_m4_v3(ob->obmat, v1);
                                        mul_mat3_m4_v3(ob->obmat, v2);
                                }
 
-                               if(unit->system) {
+                               if (unit->system) {
                                        bUnit_AsString(numstr, sizeof(numstr), len_v3v3(v1, v2) * unit->scale_length, 3,
                                                       unit->system, B_UNIT_LENGTH, do_split, FALSE);
                                }
@@ -2777,27 +2855,27 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
                                        sprintf(numstr, conv_float, len_v3v3(v1, v2));
                                }
 
-                               view3d_cached_text_draw_add(vmid, numstr, 0, V3D_CACHE_TEXT_ASCII, col);
+                               view3d_cached_text_draw_add(vmid, numstr, 0, txt_flag, col);
                        }
                }
        }
 
-       if(me->drawflag & ME_DRAWEXTRA_FACEAREA) {
-               /* would be nice to use BM_face_area_calc, but that is for 2d faces
-               so instead add up tessalation triangle areas */
+       if (me->drawflag & ME_DRAWEXTRA_FACEAREA) {
+               /* would be nice to use BM_face_calc_area, but that is for 2d faces
+                * so instead add up tessellation triangle areas */
                BMFace *f;
                int n;
 
-#define DRAW_EM_MEASURE_STATS_FACEAREA()                                             \
-               if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {                                            \
-                       mul_v3_fl(vmid, 1.0/n);                                                  \
-                       if(unit->system)                                                         \
-                               bUnit_AsString(numstr, sizeof(numstr), area*unit->scale_length,      \
-                                       3, unit->system, B_UNIT_LENGTH, do_split, FALSE);                \
-                       else                                                                     \
-                               BLI_snprintf(numstr, sizeof(numstr), conv_float, area);              \
-                       view3d_cached_text_draw_add(vmid, numstr, 0, V3D_CACHE_TEXT_ASCII, col); \
-               }
+#define DRAW_EM_MEASURE_STATS_FACEAREA()                                      \
+       if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {                               \
+               mul_v3_fl(vmid, 1.0 / n);                                             \
+               if (unit->system)                                                     \
+                       bUnit_AsString(numstr, sizeof(numstr), area * unit->scale_length, \
+                                      3, unit->system, B_UNIT_LENGTH, do_split, FALSE);  \
+               else                                                                  \
+                       BLI_snprintf(numstr, sizeof(numstr), conv_float, area);           \
+               view3d_cached_text_draw_add(vmid, numstr, 0, txt_flag, col);          \
+       }
 
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_FACEAREA, col);
                
@@ -2805,9 +2883,9 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
                area = 0.0;
                zero_v3(vmid);
                n = 0;
-               for(i = 0; i < em->tottri; i++) {
+               for (i = 0; i < em->tottri; i++) {
                        BMLoop **l = em->looptris[i];
-                       if(f && l[0]->f != f) {
+                       if (f && l[0]->f != f) {
                                DRAW_EM_MEASURE_STATS_FACEAREA();
                                zero_v3(vmid);
                                area = 0.0;
@@ -2818,7 +2896,7 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
                        copy_v3_v3(v1, l[0]->v->co);
                        copy_v3_v3(v2, l[1]->v->co);
                        copy_v3_v3(v3, l[2]->v->co);
-                       if(do_global) {
+                       if (do_global) {
                                mul_mat3_m4_v3(ob->obmat, v1);
                                mul_mat3_m4_v3(ob->obmat, v2);
                                mul_mat3_m4_v3(ob->obmat, v3);
@@ -2830,35 +2908,36 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
                        n += 3;
                }
 
-               if(f){
+               if (f) {
                        DRAW_EM_MEASURE_STATS_FACEAREA();
                }
 #undef DRAW_EM_MEASURE_STATS_FACEAREA
        }
 
-       if(me->drawflag & ME_DRAWEXTRA_FACEANG) {
+       if (me->drawflag & ME_DRAWEXTRA_FACEANG) {
                BMFace *efa;
 
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_FACEANG, col);
 
 
-               for(efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
-                   efa; efa=BM_iter_step(&iter)) {
+               for (efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
+                    efa; efa = BM_iter_step(&iter))
+               {
                        BMIter liter;
                        BMLoop *loop;
 
-                       BM_face_center_bounds_calc(em->bm, efa, vmid);
-
-                       for(loop = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
-                           loop; loop = BM_iter_step(&liter)) {
+                       BM_face_calc_center_bounds(efa, vmid);
 
+                       for (loop = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
+                            loop; loop = BM_iter_step(&liter))
+                       {
                                float v1[3], v2[3], v3[3];
 
                                copy_v3_v3(v1, loop->prev->v->co);
                                copy_v3_v3(v2, loop->v->co);
                                copy_v3_v3(v3, loop->next->v->co);
 
-                               if(do_global){
+                               if (do_global) {
                                        mul_mat3_m4_v3(ob->obmat, v1);
                                        mul_mat3_m4_v3(ob->obmat, v2);
                                        mul_mat3_m4_v3(ob->obmat, v3);
@@ -2869,7 +2948,7 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
                                {
                                        BLI_snprintf(numstr, sizeof(numstr), "%.3g", RAD2DEGF(angle_v3v3v3(v1, v2, v3)));
                                        interp_v3_v3v3(fvec, vmid, v2, 0.8f);
-                                       view3d_cached_text_draw_add(fvec, numstr, 0, V3D_CACHE_TEXT_ASCII, col);
+                                       view3d_cached_text_draw_add(fvec, numstr, 0, txt_flag, col);
                                }
                        }
                }
@@ -2878,6 +2957,7 @@ static void draw_em_measure_stats(View3D *v3d, Object *ob, BMEditMesh *em, UnitS
 
 static void draw_em_indices(BMEditMesh *em)
 {
+       const short txt_flag = V3D_CACHE_TEXT_ASCII | V3D_CACHE_TEXT_LOCALCLIP;
        BMEdge *e;
        BMFace *f;
        BMVert *v;
@@ -2887,65 +2967,68 @@ static void draw_em_indices(BMEditMesh *em)
        unsigned char col[4];
 
        BMIter iter;
-       BMesh *bm= em->bm;
+       BMesh *bm = em->bm;
 
        /* For now, reuse appropriate theme colors from stats text colors */
-       i= 0;
+       i = 0;
        if (em->selectmode & SCE_SELECT_VERTEX) {
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_FACEANG, col);
-               BM_ITER(v, &iter, bm, BM_VERTS_OF_MESH, NULL) {
+               BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
                        if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
                                sprintf(numstr, "%d", i);
-                               view3d_cached_text_draw_add(v->co, numstr, 0, V3D_CACHE_TEXT_ASCII, col);
+                               view3d_cached_text_draw_add(v->co, numstr, 0, txt_flag, col);
                        }
                        i++;
                }
        }
 
        if (em->selectmode & SCE_SELECT_EDGE) {
-               i= 0;
+               i = 0;
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_EDGELEN, col);
-               BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
+               BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
                        if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
                                sprintf(numstr, "%d", i);
                                mid_v3_v3v3(pos, e->v1->co, e->v2->co);
-                               view3d_cached_text_draw_add(pos, numstr, 0, V3D_CACHE_TEXT_ASCII, col);
+                               view3d_cached_text_draw_add(pos, numstr, 0, txt_flag, col);
                        }
                        i++;
                }
        }
 
        if (em->selectmode & SCE_SELECT_FACE) {
-               i= 0;
+               i = 0;
                UI_GetThemeColor3ubv(TH_DRAWEXTRA_FACEAREA, col);
-               BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
+               BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
                        if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
-                               BM_face_center_mean_calc(bm, f, pos);
+                               BM_face_calc_center_mean(f, pos);
                                sprintf(numstr, "%d", i);
-                               view3d_cached_text_draw_add(pos, numstr, 0, V3D_CACHE_TEXT_ASCII, col);
+                               view3d_cached_text_draw_add(pos, numstr, 0, txt_flag, col);
                        }
                        i++;
                }
        }
 }
 
-static int draw_em_fancy__setFaceOpts(void *userData, int index, int *UNUSED(drawSmooth_r))
+static DMDrawOption draw_em_fancy__setFaceOpts(void *userData, int index)
 {
-       BMFace *efa = EDBM_get_face_for_index(userData, index);
+       BMFace *efa = EDBM_face_at_index(userData, index);
 
        if (efa && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
-               GPU_enable_material(efa->mat_nr+1, NULL);
-               return 1;
+               GPU_enable_material(efa->mat_nr + 1, NULL);
+               return DM_DRAW_OPTION_NORMAL;
        }
        else
-               return 0;
+               return DM_DRAW_OPTION_SKIP;
 }
 
-static int draw_em_fancy__setGLSLFaceOpts(void *userData, int index)
+static DMDrawOption draw_em_fancy__setGLSLFaceOpts(void *userData, int index)
 {
-       BMFace *efa = EDBM_get_face_for_index(userData, index);
+       BMFace *efa = EDBM_face_at_index(userData, index);
 
-       return !BM_elem_flag_test(efa, BM_ELEM_HIDDEN);
+       if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
+               return DM_DRAW_OPTION_SKIP;
+       else
+               return DM_DRAW_OPTION_NORMAL;
 }
 
 static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
@@ -2958,23 +3041,28 @@ static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
        BMVert *eve_act = NULL;
        
        if (em->bm->selected.last) {
-               BMEditSelection *ese= em->bm->selected.last;
+               BMEditSelection *ese = em->bm->selected.last;
                /* face is handeled above */
-               /*if (ese->type == BM_FACE ) {
+#if 0
+               if (ese->type == BM_FACE) {
                        efa_act = (BMFace *)ese->data;
-               } else */ if ( ese->htype == BM_EDGE ) {
-                       eed_act = (BMEdge *)ese->data;
-               } else if ( ese->htype == BM_VERT ) {
-                       eve_act = (BMVert *)ese->data;
+               }
+               else 
+#endif
+               if (ese->htype == BM_EDGE) {
+                       eed_act = (BMEdge *)ese->ele;
+               }
+               else if (ese->htype == BM_VERT) {
+                       eve_act = (BMVert *)ese->ele;
                }
        }
        
-       EDBM_init_index_arrays(em, 1, 1, 1);
+       EDBM_index_arrays_init(em, 1, 1, 1);
 
-       if(dt>OB_WIRE) {
-               if(CHECK_OB_DRAWTEXTURE(v3d, dt)) {
-                       if(draw_glsl_material(scene, ob, v3d, dt)) {
-                               glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW);
+       if (dt > OB_WIRE) {
+               if (check_object_draw_texture(scene, v3d, dt)) {
+                       if (draw_glsl_material(scene, ob, v3d, dt)) {
+                               glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
 
                                finalDM->drawMappedFacesGLSL(finalDM, GPU_enable_material,
                                                             draw_em_fancy__setGLSLFaceOpts, em);
@@ -2989,134 +3077,151 @@ static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
                else {
                        /* 3 floats for position,
                         * 3 for normal and times two because the faces may actually be quads instead of triangles */
-                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, me->flag & ME_TWOSIDED);
+                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, (me->flag & ME_TWOSIDED) ? GL_TRUE : GL_FALSE);
 
                        glEnable(GL_LIGHTING);
-                       glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW);
+                       glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
                        finalDM->drawMappedFaces(finalDM, draw_em_fancy__setFaceOpts, GPU_enable_material, NULL, me->edit_btmesh, 0);
 
                        glFrontFace(GL_CCW);
                        glDisable(GL_LIGHTING);
+                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
                }
-                       
+
                // Setup for drawing wire over, disable zbuffer
                // write to show selected edge wires better
                UI_ThemeColor(TH_WIRE);
 
                bglPolygonOffset(rv3d->dist, 1.0);
                glDepthMask(0);
-       } 
+       }
        else {
-               if (cageDM!=finalDM) {
+               if (cageDM != finalDM) {
                        UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.7);
                        finalDM->drawEdges(finalDM, 1, 0);
                }
        }
        
-       if(me->drawflag & ME_DRAWFACES) {       /* transp faces */
-               unsigned char col1[4], col2[4], col3[4];
-                       
+       if (me->drawflag & ME_DRAWFACES) {  /* transp faces */
+               unsigned char col1[4], col2[4], col3[4], col4[4];
+
                UI_GetThemeColor4ubv(TH_FACE, col1);
                UI_GetThemeColor4ubv(TH_FACE_SELECT, col2);
-               UI_GetThemeColor4ubv(TH_EDITMESH_ACTIVE, col3);
+               UI_GetThemeColor4ubv(TH_FREESTYLE_FACE_MARK, col3);
+               UI_GetThemeColor4ubv(TH_EDITMESH_ACTIVE, col4);
                
                glEnable(GL_BLEND);
-               glDepthMask(0);         // disable write in zbuffer, needed for nice transp
+               glDepthMask(0);     // disable write in zbuffer, needed for nice transp
                
-               /* dont draw unselected faces, only selected, this is MUCH nicer when texturing */
-               if CHECK_OB_DRAWTEXTURE(v3d, dt)
+               /* don't draw unselected faces, only selected, this is MUCH nicer when texturing */
+               if (check_object_draw_texture(scene, v3d, dt))
                        col1[3] = 0;
                
-               draw_dm_faces_sel(em, cageDM, col1, col2, col3, efa_act);
+               if (!(me->drawflag & ME_DRAW_FREESTYLE_FACE))
+                       col3[3] = 0;
+
+               draw_dm_faces_sel(em, cageDM, col1, col2, col3, col4, efa_act);
 
                glDisable(GL_BLEND);
-               glDepthMask(1);         // restore write in zbuffer
-       } else if (efa_act) {
+               glDepthMask(1);     // restore write in zbuffer
+       }
+       else if (efa_act) {
                /* even if draw faces is off it would be nice to draw the stipple face
                 * Make all other faces zero alpha except for the active
                 * */
-               unsigned char col1[4], col2[4], col3[4];
-               col1[3] = col2[3] = 0; /* dont draw */
-               UI_GetThemeColor4ubv(TH_EDITMESH_ACTIVE, col3);
+               unsigned char col1[4], col2[4], col3[4], col4[4];
+               col1[3] = col2[3] = col3[3] = 0; /* don't draw */
+               UI_GetThemeColor4ubv(TH_EDITMESH_ACTIVE, col4);
                
                glEnable(GL_BLEND);
-               glDepthMask(0);         // disable write in zbuffer, needed for nice transp
+               glDepthMask(0);     // disable write in zbuffer, needed for nice transp
                
-               draw_dm_faces_sel(em, cageDM, col1, col2, col3, efa_act);
+               draw_dm_faces_sel(em, cageDM, col1, col2, col3, col4, efa_act);
 
                glDisable(GL_BLEND);
-               glDepthMask(1);         // restore write in zbuffer
+               glDepthMask(1);     // restore write in zbuffer
                
        }
 
        /* here starts all fancy draw-extra over */
-       if((me->drawflag & ME_DRAWEDGES)==0 && CHECK_OB_DRAWTEXTURE(v3d, dt)) {
-               /* we are drawing textures and 'ME_DRAWEDGES' is disabled, dont draw any edges */
+       if ((me->drawflag & ME_DRAWEDGES) == 0 && check_object_draw_texture(scene, v3d, dt)) {
+               /* we are drawing textures and 'ME_DRAWEDGES' is disabled, don't draw any edges */
                
                /* only draw selected edges otherwise there is no way of telling if a face is selected */
                draw_em_fancy_edges(em, scene, v3d, me, cageDM, 1, eed_act);
                
-       } else {
-               if(me->drawflag & ME_DRAWSEAMS) {
+       }
+       else {
+               if (me->drawflag & ME_DRAWSEAMS) {
                        UI_ThemeColor(TH_EDGE_SEAM);
                        glLineWidth(2);
-       
+
                        draw_dm_edges_seams(em, cageDM);
-       
-                       glColor3ub(0,0,0);
+
+                       glColor3ub(0, 0, 0);
                        glLineWidth(1);
                }
                
-               if(me->drawflag & ME_DRAWSHARP) {
+               if (me->drawflag & ME_DRAWSHARP) {
                        UI_ThemeColor(TH_EDGE_SHARP);
                        glLineWidth(2);
-       
+
                        draw_dm_edges_sharp(em, cageDM);
+
+                       glColor3ub(0, 0, 0);
+                       glLineWidth(1);
+               }
+
+               if(me->drawflag & ME_DRAW_FREESTYLE_EDGE) {
+                       UI_ThemeColor(TH_FREESTYLE_EDGE_MARK);
+                       glLineWidth(2);
+       
+                       draw_dm_edges_freestyle(em, cageDM);
        
                        glColor3ub(0,0,0);
                        glLineWidth(1);
                }
        
-               if(me->drawflag & ME_DRAWCREASES && CustomData_has_layer(&em->bm->edata, CD_CREASE)) {
+               if (me->drawflag & ME_DRAWCREASES && CustomData_has_layer(&em->bm->edata, CD_CREASE)) {
                        draw_dm_creases(em, cageDM);
                }
-               if(me->drawflag & ME_DRAWBWEIGHTS) {
+               if (me->drawflag & ME_DRAWBWEIGHTS) {
                        draw_dm_bweights(em, scene, cageDM);
                }
 
                draw_em_fancy_edges(em, scene, v3d, me, cageDM, 0, eed_act);
        }
-       if(em) {
+       if (em) {
                draw_em_fancy_verts(scene, v3d, ob, em, cageDM, eve_act);
 
-               if(me->drawflag & ME_DRAWNORMALS) {
+               if (me->drawflag & ME_DRAWNORMALS) {
                        UI_ThemeColor(TH_NORMAL);
                        draw_dm_face_normals(em, scene, cageDM);
                }
-               if(me->drawflag & ME_DRAW_VNORMALS) {
+               if (me->drawflag & ME_DRAW_VNORMALS) {
                        UI_ThemeColor(TH_VNORMAL);
                        draw_dm_vert_normals(em, scene, cageDM);
                }
 
-               if ( (me->drawflag & (ME_DRAWEXTRA_EDGELEN|ME_DRAWEXTRA_FACEAREA|ME_DRAWEXTRA_FACEANG)) &&
+               if ( (me->drawflag & (ME_DRAWEXTRA_EDGELEN | ME_DRAWEXTRA_FACEAREA | ME_DRAWEXTRA_FACEANG)) &&
                     !(v3d->flag2 & V3D_RENDER_OVERRIDE))
                {
                        draw_em_measure_stats(v3d, ob, em, &scene->unit);
                }
 
-               if ((G.f & G_DEBUG) && (me->drawflag & ME_DRAWEXTRA_INDICES) &&
+               if ((G.debug & G_DEBUG) && (me->drawflag & ME_DRAWEXTRA_INDICES) &&
                    !(v3d->flag2 & V3D_RENDER_OVERRIDE)) {
                        draw_em_indices(em);
                }
        }
 
-       if(dt>OB_WIRE) {
+       if (dt > OB_WIRE) {
                glDepthMask(1);
                bglPolygonOffset(rv3d->dist, 0.0);
                GPU_disable_material();
        }
 
-       EDBM_free_index_arrays(em);
+       EDBM_index_arrays_free(em);
 }
 
 /* Mesh drawing routines */
@@ -3124,14 +3229,16 @@ static void draw_em_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d,
 static void draw_mesh_object_outline(View3D *v3d, Object *ob, DerivedMesh *dm)
 {
        
-       if(v3d->transp==0) {    // not when we draw the transparent pass
+       if ((v3d->transp == FALSE) &&  /* not when we draw the transparent pass */
+           (ob->mode & OB_MODE_ALL_PAINT) == FALSE) /* not when painting (its distracting) - campbell */
+       {
                glLineWidth(UI_GetThemeValuef(TH_OUTLINE_WIDTH) * 2.0f);
                glDepthMask(0);
                
                /* if transparent, we cannot draw the edges for solid select... edges have no material info.
-                  drawFacesSolid() doesn't draw the transparent faces */
-               if(ob->dtx & OB_DRAWTRANSP) {
-                       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
+                * drawFacesSolid() doesn't draw the transparent faces */
+               if (ob->dtx & OB_DRAWTRANSP) {
+                       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                        dm->drawFacesSolid(dm, NULL, 0, GPU_enable_material);
                        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
                        GPU_disable_material();
@@ -3139,44 +3246,38 @@ static void draw_mesh_object_outline(View3D *v3d, Object *ob, DerivedMesh *dm)
                else {
                        dm->drawEdges(dm, 0, 1);
                }
-                                       
+
                glLineWidth(1.0);
                glDepthMask(1);
        }
 }
 
-static int wpaint__setSolidDrawOptions(void *UNUSED(userData), int UNUSED(index), int *drawSmooth_r)
-{
-       *drawSmooth_r = 1;
-       return 1;
-}
-
 static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, Base *base, int dt, int flag)
 {
-       Object *ob= base->object;
+       Object *ob = base->object;
        Mesh *me = ob->data;
-       Material *ma= give_current_material(ob, 1);
+       Material *ma = give_current_material(ob, 1);
        const short hasHaloMat = (ma && (ma->material_type == MA_TYPE_HALO));
-       eWireDrawMode draw_wire= OBDRAW_WIRE_OFF;
+       eWireDrawMode draw_wire = OBDRAW_WIRE_OFF;
        int /* totvert,*/ totedge, totface;
-       DerivedMesh *dm= mesh_get_derived_final(scene, ob, scene->customdata_mask);
-       const short is_obact= (ob == OBACT);
+       DerivedMesh *dm = mesh_get_derived_final(scene, ob, scene->customdata_mask);
+       const short is_obact = (ob == OBACT);
        int draw_flags = (is_obact && paint_facesel_test(ob)) ? DRAW_FACE_SELECT : 0;
 
-       if(!dm)
+       if (!dm)
                return;
 
        /* Check to draw dynamic paint colors (or weights from WeightVG modifiers).
         * Note: Last "preview-active" modifier in stack will win! */
-       if(DM_get_tessface_data_layer(dm, CD_WEIGHT_MCOL) && modifiers_isPreview(ob))
+       if (DM_get_tessface_data_layer(dm, CD_PREVIEW_MCOL) && modifiers_isPreview(ob))
                draw_flags |= DRAW_MODIFIERS_PREVIEW;
 
        /* Unwanted combination */
        if (draw_flags & DRAW_FACE_SELECT) {
-               draw_wire= OBDRAW_WIRE_OFF;
+               draw_wire = OBDRAW_WIRE_OFF;
        }
        else if (ob->dtx & OB_DRAWWIRE) {
-               draw_wire= OBDRAW_WIRE_ON_DEPTH; /* draw wire after solid using zoffset and depth buffer adjusment */
+               draw_wire = OBDRAW_WIRE_ON_DEPTH; /* draw wire after solid using zoffset and depth buffer adjusment */
        }
        
        /* totvert = dm->getNumVerts(dm); */ /*UNUSED*/
@@ -3184,25 +3285,25 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
        totface = dm->getNumTessFaces(dm);
        
        /* vertexpaint, faceselect wants this, but it doesnt work for shaded? */
-       glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW);
+       glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
 
-       if(dt==OB_BOUNDBOX) {
-               if((v3d->flag2 & V3D_RENDER_OVERRIDE && v3d->drawtype >= OB_WIRE)==0)
+       if (dt == OB_BOUNDBOX) {
+               if (((v3d->flag2 & V3D_RENDER_OVERRIDE) && v3d->drawtype >= OB_WIRE) == 0)
                        draw_bounding_volume(scene, ob, ob->boundtype);
        }
-       else if(hasHaloMat || (totface==0 && totedge==0)) {
+       else if (hasHaloMat || (totface == 0 && totedge == 0)) {
                glPointSize(1.5);
                dm->drawVerts(dm);
                glPointSize(1.0);
        }
-       else if(dt==OB_WIRE || totface==0) {
-               draw_wire= OBDRAW_WIRE_ON; /* draw wire only, no depth buffer stuff  */
+       else if (dt == OB_WIRE || totface == 0) {
+               draw_wire = OBDRAW_WIRE_ON; /* draw wire only, no depth buffer stuff  */
        }
        else if ( (draw_flags & DRAW_FACE_SELECT || (is_obact && ob->mode & OB_MODE_TEXTURE_PAINT)) ||
-                 CHECK_OB_DRAWTEXTURE(v3d, dt))
+                 check_object_draw_texture(scene, v3d, dt))
        {
                if ( (v3d->flag & V3D_SELECT_OUTLINE) &&
-                    ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) &&
+                    ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
                     (base->flag & SELECT) &&
                     !(G.f & G_PICKSEL || (draw_flags & DRAW_FACE_SELECT)) &&
                     (draw_wire == OBDRAW_WIRE_OFF))
@@ -3210,11 +3311,11 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                        draw_mesh_object_outline(v3d, ob, dm);
                }
 
-               if(draw_glsl_material(scene, ob, v3d, dt) && !(draw_flags & DRAW_MODIFIERS_PREVIEW)) {
-                       glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW);
+               if (draw_glsl_material(scene, ob, v3d, dt) && !(draw_flags & DRAW_MODIFIERS_PREVIEW)) {
+                       glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
 
                        dm->drawFacesGLSL(dm, GPU_enable_material);
-//                     if(get_ob_property(ob, "Text"))
+//                     if (get_ob_property(ob, "Text"))
 // XXX                         draw_mesh_text(ob, 1);
                        GPU_disable_material();
 
@@ -3224,25 +3325,26 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                        draw_mesh_textured(scene, v3d, rv3d, ob, dm, draw_flags);
                }
 
-               if(!(draw_flags & DRAW_FACE_SELECT)) {
-                       if(base->flag & SELECT)
+               if (!(draw_flags & DRAW_FACE_SELECT)) {
+                       if (base->flag & SELECT)
                                UI_ThemeColor(is_obact ? TH_ACTIVE : TH_SELECT);
                        else
                                UI_ThemeColor(TH_WIRE);
 
-                       if((v3d->flag2 & V3D_RENDER_OVERRIDE)==0)
+                       if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0)
                                dm->drawLooseEdges(dm);
                }
        }
-       else if(dt==OB_SOLID) {
-               if(is_obact && ob->mode & OB_MODE_WEIGHT_PAINT) {
+       else if (dt == OB_SOLID) {
+               if (is_obact && ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
                        /* weight paint in solid mode, special case. focus on making the weights clear
                         * rather than the shading, this is also forced in wire view */
                        GPU_enable_material(0, NULL);
-                       dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, GPU_enable_material, NULL, me->mpoly, 1);
-               
+                       dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, me->mpoly,
+                                           DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH);
+
                        bglPolygonOffset(rv3d->dist, 1.0);
-                       glDepthMask(0); // disable write in zbuffer, selected edge wires show better
+                       glDepthMask(0); // disable write in zbuffer, selected edge wires show better
 
                        glEnable(GL_BLEND);
                        glColor4ub(255, 255, 255, 96);
@@ -3258,18 +3360,18 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
 
                        GPU_disable_material();
                        
-                       /* since we already draw wire as wp guide, dont draw over the top */
-                       draw_wire= OBDRAW_WIRE_OFF;
+                       /* since we already draw wire as wp guide, don't draw over the top */
+                       draw_wire = OBDRAW_WIRE_OFF;
                }
                else if (draw_flags & DRAW_MODIFIERS_PREVIEW) {
                        /* for object selection draws no shade */
-                       if (flag & (DRAW_PICKING|DRAW_CONSTCOLOR)) {
+                       if (flag & (DRAW_PICKING | DRAW_CONSTCOLOR)) {
                                dm->drawFacesSolid(dm, NULL, 0, GPU_enable_material);
                        }
                        else {
                                /* draw outline */
                                if ( (v3d->flag & V3D_SELECT_OUTLINE) &&
-                                    ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) &&
+                                    ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
                                     (base->flag & SELECT) &&
                                     (draw_wire == OBDRAW_WIRE_OFF) &&
                                     (ob->sculpt == NULL))
@@ -3284,7 +3386,7 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                                
                                /* set default spec */
                                glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
-                               glEnable(GL_COLOR_MATERIAL);    /* according manpages needed */
+                               glEnable(GL_COLOR_MATERIAL);    /* according manpages needed */
                                glColor3ub(120, 120, 120);
                                glDisable(GL_COLOR_MATERIAL);
                                /* diffuse */
@@ -3292,7 +3394,7 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                                glEnable(GL_LIGHTING);
                                glEnable(GL_COLOR_MATERIAL);
 
-                               dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, NULL, 1);
+                               dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, NULL, DM_DRAW_USE_COLORS);
                                glDisable(GL_COLOR_MATERIAL);
                                glDisable(GL_LIGHTING);
 
@@ -3303,7 +3405,7 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                        Paint *p;
 
                        if ( (v3d->flag & V3D_SELECT_OUTLINE) &&
-                            ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) &&
+                            ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) &&
                             (base->flag & SELECT) &&
                             (draw_wire == OBDRAW_WIRE_OFF) &&
                             (ob->sculpt == NULL))
@@ -3311,18 +3413,18 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                                draw_mesh_object_outline(v3d, ob, dm);
                        }
 
-                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, me->flag & ME_TWOSIDED );
+                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, (me->flag & ME_TWOSIDED) ? GL_TRUE : GL_FALSE);
 
                        glEnable(GL_LIGHTING);
-                       glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW);
+                       glFrontFace((ob->transflag & OB_NEG_SCALE) ? GL_CW : GL_CCW);
 
-                       if(ob->sculpt && (p=paint_get_active(scene))) {
+                       if (ob->sculpt && (p = paint_get_active(scene))) {
                                float planes[4][4];
                                float (*fpl)[4] = NULL;
-                               int fast= (p->flags & PAINT_FAST_NAVIGATE) && (rv3d->rflag & RV3D_NAVIGATING);
+                               int fast = (p->flags & PAINT_FAST_NAVIGATE) && (rv3d->rflag & RV3D_NAVIGATING);
 
-                               if(ob->sculpt->partial_redraw) {
-                                       if(ar->do_draw & RGN_DRAW_PARTIAL) {
+                               if (ob->sculpt->partial_redraw) {
+                                       if (ar->do_draw & RGN_DRAW_PARTIAL) {
                                                sculpt_get_redraw_planes(planes, ar, rv3d, ob);
                                                fpl = planes;
                                                ob->sculpt->partial_redraw = 0;
@@ -3339,24 +3441,27 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                        glFrontFace(GL_CCW);
                        glDisable(GL_LIGHTING);
 
-                       if(base->flag & SELECT) {
+                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
+
+                       if (base->flag & SELECT) {
                                UI_ThemeColor(is_obact ? TH_ACTIVE : TH_SELECT);
-                       } else {
+                       }
+                       else {
                                UI_ThemeColor(TH_WIRE);
                        }
-                       if(!ob->sculpt && (v3d->flag2 & V3D_RENDER_OVERRIDE)==0)
+                       if (!ob->sculpt && (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0)
                                dm->drawLooseEdges(dm);
                }
        }
-       else if(dt==OB_PAINT) {
+       else if (dt == OB_PAINT) {
                if (is_obact) {
-                       if(ob && ob->mode & OB_MODE_WEIGHT_PAINT) {
+                       if (ob && ob->mode & OB_MODE_WEIGHT_PAINT) {
                                /* enforce default material settings */
                                GPU_enable_material(0, NULL);
                                
                                /* but set default spec */
                                glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
-                               glEnable(GL_COLOR_MATERIAL);    /* according manpages needed */
+                               glEnable(GL_COLOR_MATERIAL);    /* according manpages needed */
                                glColor3ub(120, 120, 120);
                                glDisable(GL_COLOR_MATERIAL);
                                /* diffuse */
@@ -3364,40 +3469,44 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                                glEnable(GL_LIGHTING);
                                glEnable(GL_COLOR_MATERIAL);
 
-                               dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, GPU_enable_material, NULL, me->mpoly, 1);
+                               dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, me->mpoly,
+                                                   DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH);
                                glDisable(GL_COLOR_MATERIAL);
                                glDisable(GL_LIGHTING);
 
                                GPU_disable_material();
                        }
-                       else if(ob->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)) {
-                               if(me->mloopcol)
-                                       dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, GPU_enable_material, NULL, NULL, 1);
+                       else if (ob->mode & OB_MODE_VERTEX_PAINT) {
+                               if (me->mloopcol)
+                                       dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, NULL,
+                                                           DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH);
                                else {
                                        glColor3f(1.0f, 1.0f, 1.0f);
-                                       dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, GPU_enable_material, NULL, NULL, 0);
+                                       dm->drawMappedFaces(dm, NULL, GPU_enable_material, NULL, NULL,
+                                                           DM_DRAW_ALWAYS_SMOOTH);
                                }
                        }
                }
        }
        
        /* set default draw color back for wire or for draw-extra later on */
-       if (dt!=OB_WIRE) {
-               if(base->flag & SELECT) {
+       if (dt != OB_WIRE) {
+               if (base->flag & SELECT) {
                        if (is_obact && ob->flag & OB_FROMGROUP)
                                UI_ThemeColor(TH_GROUP_ACTIVE);
-                       else if(ob->flag & OB_FROMGROUP) 
+                       else if (ob->flag & OB_FROMGROUP)
                                UI_ThemeColorShade(TH_GROUP_ACTIVE, -16);
-                       else if(flag!=DRAW_CONSTCOLOR)
+                       else if (flag != DRAW_CONSTCOLOR)
                                UI_ThemeColor(is_obact ? TH_ACTIVE : TH_SELECT);
                        else
-                               glColor3ub(80,80,80);
-               } else {
-                       if (ob->flag & OB_FROMGROUP) 
+                               glColor3ub(80, 80, 80);
+               }
+               else {
+                       if (ob->flag & OB_FROMGROUP)
                                UI_ThemeColor(TH_GROUP);
                        else {
-                               if(ob->dtx & OB_DRAWWIRE && flag==DRAW_CONSTCOLOR)
-                                       glColor3ub(80,80,80);
+                               if (ob->dtx & OB_DRAWWIRE && flag == DRAW_CONSTCOLOR)
+                                       glColor3ub(80, 80, 80);
                                else
                                        UI_ThemeColor(TH_WIRE);
                        }
@@ -3405,10 +3514,10 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
        }
        if (draw_wire != OBDRAW_WIRE_OFF) {
 
-               /* When using wireframe object traw in particle edit mode
+               /* When using wireframe object draw in particle edit mode
                 * the mesh gets in the way of seeing the particles, fade the wire color
                 * with the background. */
-               if(is_obact && (ob->mode & OB_MODE_PARTICLE_EDIT)) {
+               if (is_obact && (ob->mode & OB_MODE_PARTICLE_EDIT)) {
                        float col_wire[4], col_bg[4], col[3];
 
                        UI_GetThemeColor3fv(TH_BACK, col_bg);
@@ -3426,21 +3535,21 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
                 * if draw wire is 1 then just drawing wire, no need for depth buffer stuff,
                 * otherwise this wire is to overlay solid mode faces so do some depth buffer tricks.
                 */
-               if (dt!=OB_WIRE && (draw_wire == OBDRAW_WIRE_ON_DEPTH)) {
+               if (dt != OB_WIRE && (draw_wire == OBDRAW_WIRE_ON_DEPTH)) {
                        bglPolygonOffset(rv3d->dist, 1.0);
-                       glDepthMask(0); // disable write in zbuffer, selected edge wires show better
+                       glDepthMask(0); // disable write in zbuffer, selected edge wires show better
                }
                
-               if((v3d->flag2 & V3D_RENDER_OVERRIDE && v3d->drawtype >= OB_SOLID)==0)
-                       dm->drawEdges(dm, (dt==OB_WIRE || totface==0), me->drawflag & ME_ALLEDGES);
+               if (((v3d->flag2 & V3D_RENDER_OVERRIDE) && v3d->drawtype >= OB_SOLID) == 0)
+                       dm->drawEdges(dm, (dt == OB_WIRE || totface == 0), me->drawflag & ME_ALLEDGES);
 
-               if (dt!=OB_WIRE && (draw_wire == OBDRAW_WIRE_ON_DEPTH)) {
+               if (dt != OB_WIRE && (draw_wire == OBDRAW_WIRE_ON_DEPTH)) {
                        glDepthMask(1);
                        bglPolygonOffset(rv3d->dist, 0.0);
                }
        }
        
-       if(is_obact && paint_vertsel_test(ob)) {
+       if (is_obact && paint_vertsel_test(ob)) {
                
                glColor3f(0.0f, 0.0f, 0.0f);
                glPointSize(UI_GetThemeValuef(TH_VERTEX_SIZE));
@@ -3455,39 +3564,39 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
 /* returns 1 if nothing was drawn, for detecting to draw an object center */
 static int draw_mesh_object(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, Base *base, int dt, int flag)
 {
-       Object *ob= base->object;
-       Object *obedit= scene->obedit;
-       Mesh *me= ob->data;
-       BMEditMesh *em= me->edit_btmesh;
-       int do_alpha_after= 0, drawlinked= 0, retval= 0, glsl, check_alpha, i;
+       Object *ob = base->object;
+       Object *obedit = scene->obedit;
+       Mesh *me = ob->data;
+       BMEditMesh *em = me->edit_btmesh;
+       int do_alpha_after = 0, drawlinked = 0, retval = 0, glsl, check_alpha, i;
 
        /* If we are drawing shadows and any of the materials don't cast a shadow,
         * then don't draw the object */
        if (v3d->flag2 & V3D_RENDER_SHADOW) {
-               for(i=0; i<ob->totcol; ++i) {
-                       Material *ma= give_current_material(ob, i);
+               for (i = 0; i < ob->totcol; ++i) {
+                       Material *ma = give_current_material(ob, i);
                        if (ma && !(ma->mode & MA_SHADBUF)) {
                                return 1;
                        }
                }
        }
        
-       if(obedit && ob!=obedit && ob->data==obedit->data) {
-               if(ob_get_key(ob) || ob_get_key(obedit));
-               else if(ob->modifiers.first || obedit->modifiers.first);
-               else drawlinked= 1;
+       if (obedit && ob != obedit && ob->data == obedit->data) {
+               if (ob_get_key(ob) || ob_get_key(obedit)) {}
+               else if (ob->modifiers.first || obedit->modifiers.first) {}
+               else drawlinked = 1;
        }
        
-       if(ob==obedit || drawlinked) {
+       if (ob == obedit || drawlinked) {
                DerivedMesh *finalDM, *cageDM;
                
-               if (obedit!=ob)
+               if (obedit != ob)
                        finalDM = cageDM = editbmesh_get_derived_base(ob, em);
                else
                        cageDM = editbmesh_get_derived_cage_and_final(scene, ob, em, &finalDM,
-                                                                                       scene->customdata_mask);
+                                                                     scene->customdata_mask);
 
-               if(dt>OB_WIRE) {
+               if (dt > OB_WIRE) {
                        glsl = draw_glsl_material(scene, ob, v3d, dt);
 
                        GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl, NULL);
@@ -3497,40 +3606,40 @@ static int draw_mesh_object(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
 
                GPU_end_object_materials();
 
-               if (obedit!=ob && finalDM)
+               if (obedit != ob && finalDM)
                        finalDM->release(finalDM);
        }
        else {
                /* don't create boundbox here with mesh_get_bb(), the derived system will make it, puts deformed bb's OK */
-               if(me->totpoly <= 4 || ED_view3d_boundbox_clip(rv3d, ob->obmat, (ob->bb)? ob->bb: me->bb)) {
+               if (me->totpoly <= 4 || ED_view3d_boundbox_clip(rv3d, ob->obmat, (ob->bb) ? ob->bb : me->bb)) {
                        glsl = draw_glsl_material(scene, ob, v3d, dt);
                        check_alpha = check_alpha_pass(base);
 
-                       if(dt==OB_SOLID || glsl) {
+                       if (dt == OB_SOLID || glsl) {
                                GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl,
-                                       (check_alpha)? &do_alpha_after: NULL);
+                                                          (check_alpha) ? &do_alpha_after : NULL);
                        }
 
                        draw_mesh_fancy(scene, ar, v3d, rv3d, base, dt, flag);
 
                        GPU_end_object_materials();
                        
-                       if(me->totvert==0) retval= 1;
+                       if (me->totvert == 0) retval = 1;
                }
        }
        
        /* GPU_begin_object_materials checked if this is needed */
-       if(do_alpha_after) {
-               if(ob->dtx & OB_DRAWXRAY) {
+       if (do_alpha_after) {
+               if (ob->dtx & OB_DRAWXRAY) {
                        add_view3d_after(&v3d->afterdraw_xraytransp, base, flag);
                }
                else {
                        add_view3d_after(&v3d->afterdraw_transp, base, flag);
                }
        }
-       else if(ob->dtx & OB_DRAWXRAY && ob->dtx & OB_DRAWTRANSP) {
+       else if (ob->dtx & OB_DRAWXRAY && ob->dtx & OB_DRAWTRANSP) {
                /* special case xray+transp when alpha is 1.0, without this the object vanishes */
-               if(v3d->xray == 0 && v3d->transp == 0) {
+               if (v3d->xray == 0 && v3d->transp == 0) {
                        add_view3d_after(&v3d->afterdraw_xray, base, flag);
                }
        }
@@ -3540,8 +3649,8 @@ static int draw_mesh_object(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
 
 /* ************** DRAW DISPLIST ****************** */
 
-static int draw_index_wire= 1;
-static int index3_nors_incr= 1;
+static int draw_index_wire = 1;
+static int index3_nors_incr = 1;
 
 /* returns 1 when nothing was drawn */
 static int drawDispListwire(ListBase *dlbase)
@@ -3550,87 +3659,87 @@ static int drawDispListwire(ListBase *dlbase)
        int parts, nr;
        float *data;
 
-       if(dlbase==NULL) return 1;
+       if (dlbase == NULL) return 1;
        
        glEnableClientState(GL_VERTEX_ARRAY);
-       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
 
-       for(dl= dlbase->first; dl; dl= dl->next) {
-               if(dl->parts==0 || dl->nr==0)
+       for (dl = dlbase->first; dl; dl = dl->next) {
+               if (dl->parts == 0 || dl->nr == 0)
                        continue;
                
-               data= dl->verts;
-       
-               switch(dl->type) {
-               case DL_SEGM:
-                       
-                       glVertexPointer(3, GL_FLOAT, 0, data);
-                       
-                       for(parts=0; parts<dl->parts; parts++)
-                               glDrawArrays(GL_LINE_STRIP, parts*dl->nr, dl->nr);
-                               
-                       break;
-               case DL_POLY:
-                       
-                       glVertexPointer(3, GL_FLOAT, 0, data);
-                       
-                       for(parts=0; parts<dl->parts; parts++)
-                               glDrawArrays(GL_LINE_LOOP, parts*dl->nr, dl->nr);
-                       
-                       break;
-               case DL_SURF:
-                       
-                       glVertexPointer(3, GL_FLOAT, 0, data);
-                       
-                       for(parts=0; parts<dl->parts; parts++) {
-                               if(dl->flag & DL_CYCL_U) 
-                                       glDrawArrays(GL_LINE_LOOP, parts*dl->nr, dl->nr);
-                               else
-                                       glDrawArrays(GL_LINE_STRIP, parts*dl->nr, dl->nr);
-                       }
-                       
-                       for(nr=0; nr<dl->nr; nr++) {
-                               int ofs= 3*dl->nr;
-                               
-                               data= (  dl->verts )+3*nr;
-                               parts= dl->parts;
+               data = dl->verts;
+
+               switch (dl->type) {
+                       case DL_SEGM:
 
-                               if(dl->flag & DL_CYCL_V) glBegin(GL_LINE_LOOP);
-                               else glBegin(GL_LINE_STRIP);
+                               glVertexPointer(3, GL_FLOAT, 0, data);
+
+                               for (parts = 0; parts < dl->parts; parts++)
+                                       glDrawArrays(GL_LINE_STRIP, parts * dl->nr, dl->nr);
                                
-                               while(parts--) {
-                                       glVertex3fv(data);
-                                       data+=ofs;
+                               break;
+                       case DL_POLY:
+
+                               glVertexPointer(3, GL_FLOAT, 0, data);
+
+                               for (parts = 0; parts < dl->parts; parts++)
+                                       glDrawArrays(GL_LINE_LOOP, parts * dl->nr, dl->nr);
+
+                               break;
+                       case DL_SURF:
+
+                               glVertexPointer(3, GL_FLOAT, 0, data);
+
+                               for (parts = 0; parts < dl->parts; parts++) {
+                                       if (dl->flag & DL_CYCL_U)
+                                               glDrawArrays(GL_LINE_LOOP, parts * dl->nr, dl->nr);
+                                       else
+                                               glDrawArrays(GL_LINE_STRIP, parts * dl->nr, dl->nr);
                                }
-                               glEnd();
-                               
-                               /* (ton) this code crashes for me when resolv is 86 or higher... no clue */
+
+                               for (nr = 0; nr < dl->nr; nr++) {
+                                       int ofs = 3 * dl->nr;
+
+                                       data = (dl->verts) + 3 * nr;
+                                       parts = dl->parts;
+
+                                       if (dl->flag & DL_CYCL_V) glBegin(GL_LINE_LOOP);
+                                       else glBegin(GL_LINE_STRIP);
+
+                                       while (parts--) {
+                                               glVertex3fv(data);
+                                               data += ofs;
+                                       }
+                                       glEnd();
+
+/* (ton) this code crashes for me when resolv is 86 or higher... no clue */
 //                             glVertexPointer(3, GL_FLOAT, sizeof(float)*3*dl->nr, data + 3*nr);
-//                             if(dl->flag & DL_CYCL_V) 
+//                             if (dl->flag & DL_CYCL_V)
 //                                     glDrawArrays(GL_LINE_LOOP, 0, dl->parts);
 //                             else
 //                                     glDrawArrays(GL_LINE_STRIP, 0, dl->parts);
-                       }
-                       break;
-                       
-               case DL_INDEX3:
-                       if(draw_index_wire) {
-                               glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                               glDrawElements(GL_TRIANGLES, 3*dl->parts, GL_UNSIGNED_INT, dl->index);
-                       }
-                       break;
-                       
-               case DL_INDEX4:
-                       if(draw_index_wire) {
-                               glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                               glDrawElements(GL_QUADS, 4*dl->parts, GL_UNSIGNED_INT, dl->index);
-                       }
-                       break;
+                               }
+                               break;
+
+                       case DL_INDEX3:
+                               if (draw_index_wire) {
+                                       glVertexPointer(3, GL_FLOAT, 0, dl->verts);
+                                       glDrawElements(GL_TRIANGLES, 3 * dl->parts, GL_UNSIGNED_INT, dl->index);
+                               }
+                               break;
+
+                       case DL_INDEX4:
+                               if (draw_index_wire) {
+                                       glVertexPointer(3, GL_FLOAT, 0, dl->verts);
+                                       glDrawElements(GL_QUADS, 4 * dl->parts, GL_UNSIGNED_INT, dl->index);
+                               }
+                               break;
                }
        }
        
        glDisableClientState(GL_VERTEX_ARRAY);
-       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); 
+       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        
        return 0;
 }
@@ -3642,7 +3751,7 @@ static void drawDispListsolid(ListBase *lb, Object *ob, int glsl)
        float *data, curcol[4];
        float *ndata;
        
-       if(lb==NULL) return;
+       if (lb == NULL) return;
        
        /* for drawing wire */
        glGetFloatv(GL_CURRENT_COLOR, curcol);
@@ -3650,103 +3759,103 @@ static void drawDispListsolid(ListBase *lb, Object *ob, int glsl)
        glEnable(GL_LIGHTING);
        glEnableClientState(GL_VERTEX_ARRAY);
        
-       if(ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
+       if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
        else glFrontFace(GL_CCW);
        
-       if(ob->type==OB_MBALL) {        // mball always smooth shaded
+       if (ob->type == OB_MBALL) {   // mball always smooth shaded
                glShadeModel(GL_SMOOTH);
        }
        
-       dl= lb->first;
-       while(dl) {
-               data= dl->verts;
-               ndata= dl->nors;
+       dl = lb->first;
+       while (dl) {
+               data = dl->verts;
+               ndata = dl->nors;
 
-               switch(dl->type) {
-               case DL_SEGM:
-                       if(ob->type==OB_SURF) {
-                               int nr;
+               switch (dl->type) {
+                       case DL_SEGM:
+                               if (ob->type == OB_SURF) {
+                                       int nr;
 
-                               glDisable(GL_LIGHTING);
-                               glColor3fv(curcol);
-                               
-                               // glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                               // glDrawArrays(GL_LINE_STRIP, 0, dl->nr);
+                                       glDisable(GL_LIGHTING);
+                                       glColor3fv(curcol);
 
-                               glBegin(GL_LINE_STRIP);
-                               for(nr= dl->nr; nr; nr--, data+=3)
-                                       glVertex3fv(data);
-                               glEnd();
+                                       // glVertexPointer(3, GL_FLOAT, 0, dl->verts);
+                                       // glDrawArrays(GL_LINE_STRIP, 0, dl->nr);
 
-                               glEnable(GL_LIGHTING);
-                       }
-                       break;
-               case DL_POLY:
-                       if(ob->type==OB_SURF) {
-                               int nr;
+                                       glBegin(GL_LINE_STRIP);
+                                       for (nr = dl->nr; nr; nr--, data += 3)
+                                               glVertex3fv(data);
+                                       glEnd();
 
-                               glDisable(GL_LIGHTING);
-                               
-                               /* for some reason glDrawArrays crashes here in half of the platforms (not osx) */
-                               //glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                               //glDrawArrays(GL_LINE_LOOP, 0, dl->nr);
-                               
-                               glBegin(GL_LINE_LOOP);
-                               for(nr= dl->nr; nr; nr--, data+=3)
-                                       glVertex3fv(data);
-                               glEnd();
-                               
-                               glEnable(GL_LIGHTING);
+                                       glEnable(GL_LIGHTING);
+                               }
                                break;
-                       }
-               case DL_SURF:
-                       
-                       if(dl->index) {
-                               GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL);
-                               
-                               if(dl->rt & CU_SMOOTH) glShadeModel(GL_SMOOTH);
-                               else glShadeModel(GL_FLAT);
+                       case DL_POLY:
+                               if (ob->type == OB_SURF) {
+                                       int nr;
+
+                                       glDisable(GL_LIGHTING);
+
+                                       /* for some reason glDrawArrays crashes here in half of the platforms (not osx) */
+                                       //glVertexPointer(3, GL_FLOAT, 0, dl->verts);
+                                       //glDrawArrays(GL_LINE_LOOP, 0, dl->nr);
+
+                                       glBegin(GL_LINE_LOOP);
+                                       for (nr = dl->nr; nr; nr--, data += 3)
+                                               glVertex3fv(data);
+                                       glEnd();
+
+                                       glEnable(GL_LIGHTING);
+                                       break;
+                               }
+                       case DL_SURF:
+
+                               if (dl->index) {
+                                       GPU_enable_material(dl->col + 1, (glsl) ? &gattribs : NULL);
+
+                                       if (dl->rt & CU_SMOOTH) glShadeModel(GL_SMOOTH);
+                                       else glShadeModel(GL_FLAT);
+
+                                       glEnableClientState(GL_NORMAL_ARRAY);
+                                       glVertexPointer(3, GL_FLOAT, 0, dl->verts);
+                                       glNormalPointer(GL_FLOAT, 0, dl->nors);
+                                       glDrawElements(GL_QUADS, 4 * dl->totindex, GL_UNSIGNED_INT, dl->index);
+                                       glDisableClientState(GL_NORMAL_ARRAY);
+                               }
+                               break;
+
+                       case DL_INDEX3:
+                               GPU_enable_material(dl->col + 1, (glsl) ? &gattribs : NULL);
 
-                               glEnableClientState(GL_NORMAL_ARRAY);
                                glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                               glNormalPointer(GL_FLOAT, 0, dl->nors);
-                               glDrawElements(GL_QUADS, 4*dl->totindex, GL_UNSIGNED_INT, dl->index);
-                               glDisableClientState(GL_NORMAL_ARRAY);
-                       }                       
-                       break;
 
-               case DL_INDEX3:
-                       GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL);
-                       
-                       glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                       
-                       /* voor polys only one normal needed */
-                       if(index3_nors_incr) {
+                               /* voor polys only one normal needed */
+                               if (index3_nors_incr) {
+                                       glEnableClientState(GL_NORMAL_ARRAY);
+                                       glNormalPointer(GL_FLOAT, 0, dl->nors);
+                               }
+                               else
+                                       glNormal3fv(ndata);
+
+                               glDrawElements(GL_TRIANGLES, 3 * dl->parts, GL_UNSIGNED_INT, dl->index);
+
+                               if (index3_nors_incr)
+                                       glDisableClientState(GL_NORMAL_ARRAY);
+
+                               break;
+
+                       case DL_INDEX4:
+                               GPU_enable_material(dl->col + 1, (glsl) ? &gattribs : NULL);
+
                                glEnableClientState(GL_NORMAL_ARRAY);
+                               glVertexPointer(3, GL_FLOAT, 0, dl->verts);
                                glNormalPointer(GL_FLOAT, 0, dl->nors);
-                       }
-                       else
-                               glNormal3fv(ndata);
-                       
-                       glDrawElements(GL_TRIANGLES, 3*dl->parts, GL_UNSIGNED_INT, dl->index);
-                       
-                       if(index3_nors_incr)
+                               glDrawElements(GL_QUADS, 4 * dl->parts, GL_UNSIGNED_INT, dl->index);
                                glDisableClientState(GL_NORMAL_ARRAY);
 
-                       break;
-
-               case DL_INDEX4:
-                       GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL);
-                       
-                       glEnableClientState(GL_NORMAL_ARRAY);
-                       glVertexPointer(3, GL_FLOAT, 0, dl->verts);
-                       glNormalPointer(GL_FLOAT, 0, dl->nors);
-                       glDrawElements(GL_QUADS, 4*dl->parts, GL_UNSIGNED_INT, dl->index);
-                       glDisableClientState(GL_NORMAL_ARRAY);
-
-                       break;
+                               break;
                }
-               dl= dl->next;
+               dl = dl->next;
        }
 
        glDisableClientState(GL_VERTEX_ARRAY);
@@ -3758,25 +3867,24 @@ static void drawDispListsolid(ListBase *lb, Object *ob, int glsl)
 static void drawCurveDMWired(Object *ob)
 {
        DerivedMesh *dm = ob->derivedFinal;
-       dm->drawEdges (dm, 1, 0);
+       dm->drawEdges(dm, 1, 0);
 }
 
 /* return 1 when nothing was drawn */
 static int drawCurveDerivedMesh(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base, int dt)
 {
-       Object *ob= base->object;
+       Object *ob = base->object;
        DerivedMesh *dm = ob->derivedFinal;
 
        if (!dm) {
                return 1;
        }
 
-       if(dt>OB_WIRE && dm->getNumTessFaces(dm)) {
+       if (dt > OB_WIRE && dm->getNumTessFaces(dm)) {
                int glsl = draw_glsl_material(scene, ob, v3d, dt);
                GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl, NULL);
 
-               if(!glsl) {
-                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
+               if (!glsl) {
                        glEnable(GL_LIGHTING);
                        dm->drawFacesSolid(dm, NULL, 0, GPU_enable_material);
                        glDisable(GL_LIGHTING);
@@ -3785,9 +3893,10 @@ static int drawCurveDerivedMesh(Scene *scene, View3D *v3d, RegionView3D *rv3d, B
                        dm->drawFacesGLSL(dm, GPU_enable_material);
 
                GPU_end_object_materials();
-       } else {
-               if((v3d->flag2 & V3D_RENDER_OVERRIDE && v3d->drawtype >= OB_SOLID)==0)
-                       drawCurveDMWired (ob);
+       }
+       else {
+               if (((v3d->flag2 & V3D_RENDER_OVERRIDE) && v3d->drawtype >= OB_SOLID) == 0)
+                       drawCurveDMWired(ob);
        }
 
        return 0;
@@ -3796,121 +3905,118 @@ static int drawCurveDerivedMesh(Scene *scene, View3D *v3d, RegionView3D *rv3d, B
 /* returns 1 when nothing was drawn */
 static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base, int dt)
 {
-       Object *ob= base->object;
-       ListBase *lb=NULL;
+       Object *ob = base->object;
+       ListBase *lb = NULL;
        DispList *dl;
        Curve *cu;
-       const short render_only= (v3d->flag2 & V3D_RENDER_OVERRIDE);
-       const short solid= (dt > OB_WIRE);
-       int retval= 0;
+       const short render_only = (v3d->flag2 & V3D_RENDER_OVERRIDE);
+       const short solid = (dt > OB_WIRE);
+       int retval = 0;
 
        if (drawCurveDerivedMesh(scene, v3d, rv3d, base, dt) == 0) {
                return 0;
        }
 
-       switch(ob->type) {
-       case OB_FONT:
-       case OB_CURVE:
-               cu= ob->data;
-               
-               lb= &ob->disp;
-               
-               if(solid) {
-                       dl= lb->first;
-                       if(dl==NULL) return 1;
+       switch (ob->type) {
+               case OB_FONT:
+               case OB_CURVE:
+                       cu = ob->data;
 
-                       if(dl->nors==NULL) addnormalsDispList(lb);
-                       index3_nors_incr= 0;
-                       
-                       if( displist_has_faces(lb)==0) {
-                               if(!render_only) {
-                                       draw_index_wire= 0;
-                                       drawDispListwire(lb);
-                                       draw_index_wire= 1;
+                       lb = &ob->disp;
+
+                       if (solid) {
+                               dl = lb->first;
+                               if (dl == NULL) return 1;
+
+                               if (dl->nors == NULL) addnormalsDispList(lb);
+                               index3_nors_incr = 0;
+
+                               if (displist_has_faces(lb) == 0) {
+                                       if (!render_only) {
+                                               draw_index_wire = 0;
+                                               drawDispListwire(lb);
+                                               draw_index_wire = 1;
+                                       }
                                }
+                               else {
+                                       if (draw_glsl_material(scene, ob, v3d, dt)) {
+                                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
+                                               drawDispListsolid(lb, ob, 1);
+                                               GPU_end_object_materials();
+                                       }
+                                       else {
+                                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
+                                               drawDispListsolid(lb, ob, 0);
+                                               GPU_end_object_materials();
+                                       }
+                                       if (cu->editnurb && cu->bevobj == NULL && cu->taperobj == NULL && cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
+                                               cpack(0);
+                                               draw_index_wire = 0;
+                                               drawDispListwire(lb);
+                                               draw_index_wire = 1;
+                                       }
+                               }
+                               index3_nors_incr = 1;
                        }
                        else {
-                               if(draw_glsl_material(scene, ob, v3d, dt)) {
+                               if (!render_only || (render_only && displist_has_faces(lb))) {
+                                       draw_index_wire = 0;
+                                       retval = drawDispListwire(lb);
+                                       draw_index_wire = 1;
+                               }
+                       }
+                       break;
+               case OB_SURF:
+
+                       lb = &ob->disp;
+
+                       if (solid) {
+                               dl = lb->first;
+                               if (dl == NULL) return 1;
+
+                               if (dl->nors == NULL) addnormalsDispList(lb);
+
+                               if (draw_glsl_material(scene, ob, v3d, dt)) {
                                        GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
                                        drawDispListsolid(lb, ob, 1);
                                        GPU_end_object_materials();
                                }
                                else {
                                        GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
-                                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
                                        drawDispListsolid(lb, ob, 0);
                                        GPU_end_object_materials();
                                }
-                               if(cu->editnurb && cu->bevobj==NULL && cu->taperobj==NULL && cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
-                                       cpack(0);
-                                       draw_index_wire= 0;
-                                       drawDispListwire(lb);
-                                       draw_index_wire= 1;
-                               }
-                       }
-                       index3_nors_incr= 1;
-               }
-               else {
-                       if(!render_only || (render_only && displist_has_faces(lb))) {
-                               draw_index_wire= 0;
-                               retval= drawDispListwire(lb);
-                               draw_index_wire= 1;
-                       }
-               }
-               break;
-       case OB_SURF:
-
-               lb= &ob->disp;
-               
-               if(solid) {
-                       dl= lb->first;
-                       if(dl==NULL) return 1;
-                       
-                       if(dl->nors==NULL) addnormalsDispList(lb);
-                       
-                       if(draw_glsl_material(scene, ob, v3d, dt)) {
-                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
-                               drawDispListsolid(lb, ob, 1);
-                               GPU_end_object_materials();
                        }
                        else {
-                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
-                               glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
-                               drawDispListsolid(lb, ob, 0);
-                               GPU_end_object_materials();
+                               retval = drawDispListwire(lb);
                        }
-               }
-               else {
-                       retval= drawDispListwire(lb);
-               }
-               break;
-       case OB_MBALL:
-               
-               if( is_basis_mball(ob)) {
-                       lb= &ob->disp;
-                       if(lb->first==NULL) makeDispListMBall(scene, ob);
-                       if(lb->first==NULL) return 1;
-                       
-                       if(solid) {
-                               
-                               if(draw_glsl_material(scene, ob, v3d, dt)) {
-                                       GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
-                                       drawDispListsolid(lb, ob, 1);
-                                       GPU_end_object_materials();
+                       break;
+               case OB_MBALL:
+
+                       if (BKE_metaball_is_basis(ob)) {
+                               lb = &ob->disp;
+                               if (lb->first == NULL) makeDispListMBall(scene, ob);
+                               if (lb->first == NULL) return 1;
+
+                               if (solid) {
+
+                                       if (draw_glsl_material(scene, ob, v3d, dt)) {
+                                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 1, NULL);
+                                               drawDispListsolid(lb, ob, 1);
+                                               GPU_end_object_materials();
+                                       }
+                                       else {
+                                               GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
+                                               drawDispListsolid(lb, ob, 0);
+                                               GPU_end_object_materials();
+                                       }
                                }
                                else {
-                                       GPU_begin_object_materials(v3d, rv3d, scene, ob, 0, NULL);
-                                       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
-                                       drawDispListsolid(lb, ob, 0);
-                                       GPU_end_object_materials();
+                                       /* MetaBalls use DL_INDEX4 type of DispList */
+                                       retval = drawDispListwire(lb);
                                }
                        }
-                       else{
-                               /* MetaBalls use DL_INDEX4 type of DispList */
-                               retval= drawDispListwire(lb);
-                       }
-               }
-               break;
+                       break;
        }
        
        return retval;
@@ -3920,21 +4026,21 @@ static int drawDispList(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *bas
 static void draw_particle_arrays(int draw_as, int totpoint, int ob_dt, int select)
 {
        /* draw created data arrays */
-       switch(draw_as){
+       switch (draw_as) {
                case PART_DRAW_AXIS:
                case PART_DRAW_CROSS:
-                       glDrawArrays(GL_LINES, 0, 6*totpoint);
+                       glDrawArrays(GL_LINES, 0, 6 * totpoint);
                        break;
                case PART_DRAW_LINE:
-                       glDrawArrays(GL_LINES, 0, 2*totpoint);
+                       glDrawArrays(GL_LINES, 0, 2 * totpoint);
                        break;
                case PART_DRAW_BB:
-                       if(ob_dt<=OB_WIRE || select)
-                               glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
+                       if (ob_dt <= OB_WIRE || select)
+                               glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                        else
-                               glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); 
+                               glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
 
-                       glDrawArrays(GL_QUADS, 0, 4*totpoint);
+                       glDrawArrays(GL_QUADS, 0, 4 * totpoint);
                        break;
                default:
                        glDrawArrays(GL_POINTS, 0, totpoint);
@@ -3947,102 +4053,102 @@ static void draw_particle(ParticleKey *state, int draw_as, short draw, float pix
        float vec[3], vec2[3];
        float *vd = NULL;
        float *cd = NULL;
-       float ma_col[3]= {0.0f, 0.0f, 0.0f};
+       float ma_col[3] = {0.0f, 0.0f, 0.0f};
 
        /* null only for PART_DRAW_CIRC */
-       if(pdd) {
+       if (pdd) {
                vd = pdd->vd;
                cd = pdd->cd;
 
-               if(pdd->ma_col) {
+               if (pdd->ma_col) {
                        copy_v3_v3(ma_col, pdd->ma_col);
                }
        }
 
-       switch(draw_as){
+       switch (draw_as) {
                case PART_DRAW_DOT:
                {
-                       if(vd) {
-                               copy_v3_v3(vd,state->co); pdd->vd+=3;
+                       if (vd) {
+                               copy_v3_v3(vd, state->co); pdd->vd += 3;
                        }
-                       if(cd) {
+                       if (cd) {
                                copy_v3_v3(cd, pdd->ma_col);
-                               pdd->cd+=3;
+                               pdd->cd += 3;
                        }
                        break;
                }
                case PART_DRAW_CROSS:
                case PART_DRAW_AXIS:
                {
-                       vec[0]=2.0f*pixsize;
-                       vec[1]=vec[2]=0.0;
-                       mul_qt_v3(state->rot,vec);
-                       if(draw_as==PART_DRAW_AXIS) {
-                               if(cd) {
-                                       cd[1]=cd[2]=cd[4]=cd[5]=0.0;
-                                       cd[0]=cd[3]=1.0;
-                                       cd[6]=cd[8]=cd[9]=cd[11]=0.0;
-                                       cd[7]=cd[10]=1.0;
-                                       cd[13]=cd[12]=cd[15]=cd[16]=0.0;
-                                       cd[14]=cd[17]=1.0;
-                                       pdd->cd+=18;
+                       vec[0] = 2.0f * pixsize;
+                       vec[1] = vec[2] = 0.0;
+                       mul_qt_v3(state->rot, vec);
+                       if (draw_as == PART_DRAW_AXIS) {
+                               if (cd) {
+                                       cd[1] = cd[2] = cd[4] = cd[5] = 0.0;
+                                       cd[0] = cd[3] = 1.0;
+                                       cd[6] = cd[8] = cd[9] = cd[11] = 0.0;
+                                       cd[7] = cd[10] = 1.0;
+                                       cd[13] = cd[12] = cd[15] = cd[16] = 0.0;
+                                       cd[14] = cd[17] = 1.0;
+                                       pdd->cd += 18;
                                }
 
-                               copy_v3_v3(vec2,state->co);
+                               copy_v3_v3(vec2, state->co);
                        }
                        else {
-                               if(cd) {
-                                       cd[0]=cd[3]=cd[6]=cd[ 9]=cd[12]=cd[15]= ma_col[0];
-                                       cd[1]=cd[4]=cd[7]=cd[10]=cd[13]=cd[16]= ma_col[1];
-                                       cd[2]=cd[5]=cd[8]=cd[11]=cd[14]=cd[17]= ma_col[2];
-                                       pdd->cd+=18;
+                               if (cd) {
+                                       cd[0] = cd[3] = cd[6] = cd[9] = cd[12] = cd[15] = ma_col[0];
+                                       cd[1] = cd[4] = cd[7] = cd[10] = cd[13] = cd[16] = ma_col[1];
+                                       cd[2] = cd[5] = cd[8] = cd[11] = cd[14] = cd[17] = ma_col[2];
+                                       pdd->cd += 18;
                                }
                                sub_v3_v3v3(vec2, state->co, vec);
                        }
 
                        add_v3_v3(vec, state->co);
-                       copy_v3_v3(pdd->vd,vec); pdd->vd+=3;
-                       copy_v3_v3(pdd->vd,vec2); pdd->vd+=3;
-                               
-                       vec[1]=2.0f*pixsize;
-                       vec[0]=vec[2]=0.0;
-                       mul_qt_v3(state->rot,vec);
-                       if(draw_as==PART_DRAW_AXIS){
-                               copy_v3_v3(vec2,state->co);
-                       }               
+                       copy_v3_v3(pdd->vd, vec); pdd->vd += 3;
+                       copy_v3_v3(pdd->vd, vec2); pdd->vd += 3;
+
+                       vec[1] = 2.0f * pixsize;
+                       vec[0] = vec[2] = 0.0;
+                       mul_qt_v3(state->rot, vec);
+                       if (draw_as == PART_DRAW_AXIS) {
+                               copy_v3_v3(vec2, state->co);
+                       }
                        else sub_v3_v3v3(vec2, state->co, vec);
 
                        add_v3_v3(vec, state->co);
-                       copy_v3_v3(pdd->vd,vec); pdd->vd+=3;
-                       copy_v3_v3(pdd->vd,vec2); pdd->vd+=3;
+                       copy_v3_v3(pdd->vd, vec); pdd->vd += 3;
+                       copy_v3_v3(pdd->vd, vec2); pdd->vd += 3;
 
-                       vec[2]=2.0f*pixsize;
-                       vec[0]=vec[1]=0.0;
-                       mul_qt_v3(state->rot,vec);
-                       if(draw_as==PART_DRAW_AXIS){
-                               copy_v3_v3(vec2,state->co);
+                       vec[2] = 2.0f * pixsize;
+                       vec[0] = vec[1] = 0.0;
+                       mul_qt_v3(state->rot, vec);
+                       if (draw_as == PART_DRAW_AXIS) {
+                               copy_v3_v3(vec2, state->co);
                        }
                        else sub_v3_v3v3(vec2, state->co, vec);
 
                        add_v3_v3(vec, state->co);
 
-                       copy_v3_v3(pdd->vd,vec); pdd->vd+=3;
-                       copy_v3_v3(pdd->vd,vec2); pdd->vd+=3;
+                       copy_v3_v3(pdd->vd, vec); pdd->vd += 3;
+                       copy_v3_v3(pdd->vd, vec2); pdd->vd += 3;
                        break;
                }
                case PART_DRAW_LINE:
                {
-                       copy_v3_v3(vec,state->vel);
+                       copy_v3_v3(vec, state->vel);
                        normalize_v3(vec);
-                       if(draw & PART_DRAW_VEL_LENGTH)
-                               mul_v3_fl(vec,len_v3(state->vel));
-                       madd_v3_v3v3fl(pdd->vd, state->co, vec, -draw_line[0]); pdd->vd+=3;
-                       madd_v3_v3v3fl(pdd->vd, state->co, vec,  draw_line[1]); pdd->vd+=3;
-                       if(cd) {
-                               cd[0]=cd[3]= ma_col[0];
-                               cd[1]=cd[4]= ma_col[1];
-                               cd[2]=cd[5]= ma_col[2];
-                               pdd->cd+=6;
+                       if (draw & PART_DRAW_VEL_LENGTH)
+                               mul_v3_fl(vec, len_v3(state->vel));
+                       madd_v3_v3v3fl(pdd->vd, state->co, vec, -draw_line[0]); pdd->vd += 3;
+                       madd_v3_v3v3fl(pdd->vd, state->co, vec,  draw_line[1]); pdd->vd += 3;
+                       if (cd) {
+                               cd[0] = cd[3] = ma_col[0];
+                               cd[1] = cd[4] = ma_col[1];
+                               cd[2] = cd[5] = ma_col[2];
+                               pdd->cd += 6;
                        }
                        break;
                }
@@ -4054,11 +4160,11 @@ static void draw_particle(ParticleKey *state, int draw_as, short draw, float pix
                case PART_DRAW_BB:
                {
                        float xvec[3], yvec[3], zvec[3], bb_center[3];
-                       if(cd) {
-                               cd[0]=cd[3]=cd[6]=cd[ 9]= ma_col[0];
-                               cd[1]=cd[4]=cd[7]=cd[10]= ma_col[1];
-                               cd[2]=cd[5]=cd[8]=cd[11]= ma_col[2];
-                               pdd->cd+=12;
+                       if (cd) {
+                               cd[0] = cd[3] = cd[6] = cd[9] = ma_col[0];
+                               cd[1] = cd[4] = cd[7] = cd[10] = ma_col[1];
+                               cd[2] = cd[5] = cd[8] = cd[11] = ma_col[2];
+                               pdd->cd += 12;
                        }
 
 
@@ -4068,21 +4174,21 @@ static void draw_particle(ParticleKey *state, int draw_as, short draw, float pix
                        psys_make_billboard(bb, xvec, yvec, zvec, bb_center);
                        
                        add_v3_v3v3(pdd->vd, bb_center, xvec);
-                       add_v3_v3(pdd->vd, yvec); pdd->vd+=3;
+                       add_v3_v3(pdd->vd, yvec); pdd->vd += 3;
 
                        sub_v3_v3v3(pdd->vd, bb_center, xvec);
-                       add_v3_v3(pdd->vd, yvec); pdd->vd+=3;
+                       add_v3_v3(pdd->vd, yvec); pdd->vd += 3;
 
                        sub_v3_v3v3(pdd->vd, bb_center, xvec);
-                       sub_v3_v3v3(pdd->vd, pdd->vd,yvec); pdd->vd+=3;
+                       sub_v3_v3v3(pdd->vd, pdd->vd, yvec); pdd->vd += 3;
 
                        add_v3_v3v3(pdd->vd, bb_center, xvec);
-                       sub_v3_v3v3(pdd->vd, pdd->vd, yvec); pdd->vd+=3;
+                       sub_v3_v3v3(pdd->vd, pdd->vd, yvec); pdd->vd += 3;
 
-                       copy_v3_v3(pdd->nd, zvec); pdd->nd+=3;
-                       copy_v3_v3(pdd->nd, zvec); pdd->nd+=3;
-                       copy_v3_v3(pdd->nd, zvec); pdd->nd+=3;
-                       copy_v3_v3(pdd->nd, zvec); pdd->nd+=3;
+                       copy_v3_v3(pdd->nd, zvec); pdd->nd += 3;
+                       copy_v3_v3(pdd->nd, zvec); pdd->nd += 3;
+                       copy_v3_v3(pdd->nd, zvec); pdd->nd += 3;
+                       copy_v3_v3(pdd->nd, zvec); pdd->nd += 3;
                        break;
                }
        }
@@ -4091,7 +4197,7 @@ static void draw_particle(ParticleKey *state, int draw_as, short draw, float pix
 /* mostly tries to use vertex arrays for speed                                                                         */
 
 /* 1. check that everything is ok & updated */
-/* 2. start initialising things                                */
+/* 2. start initializing things                                */
 /* 3. initialize according to draw type                */
 /* 4. allocate drawing data arrays                     */
 /* 5. start filling the arrays                         */
@@ -4100,91 +4206,86 @@ static void draw_particle(ParticleKey *state, int draw_as, short draw, float pix
 static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv3d,
                                      Base *base, ParticleSystem *psys, int ob_dt)
 {
-       Object *ob=base->object;
+       Object *ob = base->object;
        ParticleEditSettings *pset = PE_settings(scene);
-       ParticleSettings *part;
-       ParticleData *pars, *pa;
-       ParticleKey state, *states=NULL;
+       ParticleSettings *part = psys->part;
+       ParticleData *pars = psys->particles;
+       ParticleData *pa;
+       ParticleKey state, *states = NULL;
        ParticleBillboardData bb;
-       ParticleSimulationData sim= {NULL};
+       ParticleSimulationData sim = {NULL};
        ParticleDrawData *pdd = psys->pdd;
        Material *ma;
        float vel[3], imat[4][4];
        float timestep, pixsize_scale, pa_size, r_tilt, r_length;
        float pa_time, pa_birthtime, pa_dietime, pa_health, intensity;
        float cfra;
-       float ma_col[3]= {0.0f, 0.0f, 0.0f};
-       int a, totpart, totpoint=0, totve=0, drawn, draw_as, totchild=0;
-       int select=ob->flag&SELECT, create_cdata=0, need_v=0;
+       float ma_col[3] = {0.0f, 0.0f, 0.0f};
+       int a, totpart, totpoint = 0, totve = 0, drawn, draw_as, totchild = 0;
+       int select = ob->flag & SELECT, create_cdata = 0, need_v = 0;
        GLint polygonmode[2];
        char numstr[32];
-       unsigned char tcol[4]= {0, 0, 0, 255};
+       unsigned char tcol[4] = {0, 0, 0, 255};
 
 /* 1. */
-       if(psys==NULL)
-               return;
-
-       part=psys->part;
-       pars=psys->particles;
-
-       if(part==NULL || !psys_check_enabled(ob, psys))
+       if (part == NULL || !psys_check_enabled(ob, psys))
                return;
 
-       if(pars==NULL) return;
+       if (pars == NULL) return;
 
        /* don't draw normal paths in edit mode */
-       if(psys_in_edit_mode(scene, psys) && (pset->flag & PE_DRAW_PART)==0)
+       if (psys_in_edit_mode(scene, psys) && (pset->flag & PE_DRAW_PART) == 0)
                return;
-               
-       if(part->draw_as == PART_DRAW_REND)
+
+       if (part->draw_as == PART_DRAW_REND)
                draw_as = part->ren_as;
        else
                draw_as = part->draw_as;
 
-       if(draw_as == PART_DRAW_NOT)
+       if (draw_as == PART_DRAW_NOT)
                return;
 
 /* 2. */
-       sim.scene= scene;
-       sim.ob= ob;
-       sim.psys= psys;
-       sim.psmd = psys_get_modifier(ob,psys);
+       sim.scene = scene;
+       sim.ob = ob;
+       sim.psys = psys;
+       sim.psmd = psys_get_modifier(ob, psys);
 
-       if(part->phystype==PART_PHYS_KEYED){
-               if(psys->flag&PSYS_KEYED){
+       if (part->phystype == PART_PHYS_KEYED) {
+               if (psys->flag & PSYS_KEYED) {
                        psys_count_keyed_targets(&sim);
-                       if(psys->totkeyed==0)
+                       if (psys->totkeyed == 0)
                                return;
                }
        }
 
-       if(select){
-               select=0;
-               if(psys_get_current(ob)==psys)
-                       select=1;
+       if (select) {
+               select = 0;
+               if (psys_get_current(ob) == psys)
+                       select = 1;
        }
 
-       psys->flag|=PSYS_DRAWING;
+       psys->flag |= PSYS_DRAWING;
 
-       if(part->type==PART_HAIR && !psys->childcache)
-               totchild=0;
+       if (part->type == PART_HAIR && !psys->childcache)
+               totchild = 0;
        else
-               totchild=psys->totchild*part->disp/100;
+               totchild = psys->totchild * part->disp / 100;
 
-       ma= give_current_material(ob,part->omat);
+       ma = give_current_material(ob, part->omat);
 
-       if(v3d->zbuf) glDepthMask(1);
+       if (v3d->zbuf) glDepthMask(1);
 
-       if((ma) && (part->draw_col == PART_DRAW_COL_MAT)) {
+       if ((ma) && (part->draw_col == PART_DRAW_COL_MAT)) {
                rgb_float_to_uchar(tcol, &(ma->r));
                copy_v3_v3(ma_col, &ma->r);
        }
 
        glColor3ubv(tcol);
 
-       timestep= psys_get_timestep(&sim);
+       timestep = psys_get_timestep(&sim);
 
-       if( (base->flag & OB_FROMDUPLI) && (ob->flag & OB_FROMGROUP) ) {
+       if ( (base->flag & OB_FROMDUPLI) && (ob->flag & OB_FROMGROUP) ) {
                float mat[4][4];
                mult_m4_m4m4(mat, ob->obmat, psys->imat);
                glMultMatrixf(mat);
@@ -4193,27 +4294,27 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
        /* needed for text display */
        invert_m4_m4(ob->imat, ob->obmat);
 
-       totpart=psys->totpart;
+       totpart = psys->totpart;
 
-       cfra= BKE_curframe(scene);
+       cfra = BKE_curframe(scene);
 
-       if(draw_as==PART_DRAW_PATH && psys->pathcache==NULL && psys->childcache==NULL)
-               draw_as=PART_DRAW_DOT;
+       if (draw_as == PART_DRAW_PATH && psys->pathcache == NULL && psys->childcache == NULL)
+               draw_as = PART_DRAW_DOT;
 
 /* 3. */
-       switch(draw_as){
+       switch (draw_as) {
                case PART_DRAW_DOT:
-                       if(part->draw_size)
+                       if (part->draw_size)
                                glPointSize(part->draw_size);
                        else
-                               glPointSize(2.0); /* default dot size */
+                               glPointSize(2.0);  /* default dot size */
                        break;
                case PART_DRAW_CIRC:
                        /* calculate view aligned matrix: */
                        copy_m4_m4(imat, rv3d->viewinv);
                        normalize_v3(imat[0]);
                        normalize_v3(imat[1]);
-                       /* no break! */
+               /* no break! */
                case PART_DRAW_CROSS:
                case PART_DRAW_AXIS:
                        /* lets calculate the scale: */
@@ -4223,36 +4324,36 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
                        else
                                pixsize_scale = part->draw_size;
 
-                       if(draw_as==PART_DRAW_AXIS)
+                       if (draw_as == PART_DRAW_AXIS)
                                create_cdata = 1;
                        break;
                case PART_DRAW_OB:
-                       if(part->dup_ob==NULL)
-                               draw_as=PART_DRAW_DOT;
+                       if (part->dup_ob == NULL)
+                               draw_as = PART_DRAW_DOT;
                        else
-                               draw_as=0;
+                               draw_as = 0;
                        break;
                case PART_DRAW_GR:
-                       if(part->dup_group==NULL)
-                               draw_as=PART_DRAW_DOT;
+                       if (part->dup_group == NULL)
+                               draw_as = PART_DRAW_DOT;
                        else
-                               draw_as=0;
+                               draw_as = 0;
                        break;
                case PART_DRAW_BB:
-                       if(v3d->camera==NULL && part->bb_ob==NULL){
+                       if (v3d->camera == NULL && part->bb_ob == NULL) {
                                printf("Billboards need an active camera or a target object!\n");
 
-                               draw_as=part->draw_as=PART_DRAW_DOT;
+                               draw_as = part->draw_as = PART_DRAW_DOT;
 
-                               if(part->draw_size)
+                               if (part->draw_size)
                                        glPointSize(part->draw_size);
                                else
-                                       glPointSize(2.0); /* default dot size */
+                                       glPointSize(2.0);  /* default dot size */
                        }
-                       else if(part->bb_ob)
-                               bb.ob=part->bb_ob;
+                       else if (part->bb_ob)
+                               bb.ob = part->bb_ob;
                        else
-                               bb.ob=v3d->camera;
+                               bb.ob = v3d->camera;
 
                        bb.align = part->bb_align;
                        bb.anim = part->bb_anim;
@@ -4261,42 +4362,44 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
                case PART_DRAW_PATH:
                        break;
                case PART_DRAW_LINE:
-                       need_v=1;
+                       need_v = 1;
                        break;
        }
-       if(part->draw & PART_DRAW_SIZE && part->draw_as!=PART_DRAW_CIRC){
+       if (part->draw & PART_DRAW_SIZE && part->draw_as != PART_DRAW_CIRC) {
                copy_m4_m4(imat, rv3d->viewinv);
                normalize_v3(imat[0]);
                normalize_v3(imat[1]);
        }
 
-       if(ELEM3(draw_as, PART_DRAW_DOT, PART_DRAW_CROSS, PART_DRAW_LINE)
-               && part->draw_col > PART_DRAW_COL_MAT)
+       if (ELEM3(draw_as, PART_DRAW_DOT, PART_DRAW_CROSS, PART_DRAW_LINE) &&
+           (part->draw_col > PART_DRAW_COL_MAT))
+       {
                create_cdata = 1;
+       }
 
-       if(!create_cdata && pdd && pdd->cdata) {
+       if (!create_cdata && pdd && pdd->cdata) {
                MEM_freeN(pdd->cdata);
                pdd->cdata = pdd->cd = NULL;
        }
 
 /* 4. */
-       if(draw_as && ELEM(draw_as, PART_DRAW_PATH, PART_DRAW_CIRC)==0) {
+       if (draw_as && ELEM(draw_as, PART_DRAW_PATH, PART_DRAW_CIRC) == 0) {
                int tot_vec_size = (totpart + totchild) * 3 * sizeof(float);
                int create_ndata = 0;
 
-               if(!pdd)
+               if (!pdd)
                        pdd = psys->pdd = MEM_callocN(sizeof(ParticleDrawData), "ParticlDrawData");
 
-               if(part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
+               if (part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
                        tot_vec_size *= part->trail_count;
                        psys_make_temp_pointcache(ob, psys);
                }
 
-               switch(draw_as) {
+               switch (draw_as) {
                        case PART_DRAW_AXIS:
                        case PART_DRAW_CROSS:
                                tot_vec_size *= 6;
-                               if(draw_as != PART_DRAW_CROSS)
+                               if (draw_as != PART_DRAW_CROSS)
                                        create_cdata = 1;
                                break;
                        case PART_DRAW_LINE:
@@ -4308,231 +4411,236 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
                                break;
                }
 
-               if(pdd->tot_vec_size != tot_vec_size)
+               if (pdd->tot_vec_size != tot_vec_size)
                        psys_free_pdd(psys);
 
-               if(!pdd->vdata)
+               if (!pdd->vdata)
                        pdd->vdata = MEM_callocN(tot_vec_size, "particle_vdata");
-               if(create_cdata && !pdd->cdata)
+               if (create_cdata && !pdd->cdata)
                        pdd->cdata = MEM_callocN(tot_vec_size, "particle_cdata");
-               if(create_ndata && !pdd->ndata)
+               if (create_ndata && !pdd->ndata)
                        pdd->ndata = MEM_callocN(tot_vec_size, "particle_ndata");
 
-               if(part->draw & PART_DRAW_VEL && draw_as != PART_DRAW_LINE) {
-                       if(!pdd->vedata)
+               if (part->draw & PART_DRAW_VEL && draw_as != PART_DRAW_LINE) {
+                       if (!pdd->vedata)
                                pdd->vedata = MEM_callocN(2 * (totpart + totchild) * 3 * sizeof(float), "particle_vedata");
 
                        need_v = 1;
-               } else if (pdd->vedata) {
+               }
+               else if (pdd->vedata) {
                        /* velocity data not needed, so free it */
                        MEM_freeN(pdd->vedata);
-                       pdd->vedata= NULL;
+                       pdd->vedata = NULL;
                }
 
-               pdd->vd= pdd->vdata;
-               pdd->ved= pdd->vedata;
-               pdd->cd= pdd->cdata;
-               pdd->nd= pdd->ndata;
-               pdd->tot_vec_size= tot_vec_size;
+               pdd->vd = pdd->vdata;
+               pdd->ved = pdd->vedata;
+               pdd->cd = pdd->cdata;
+               pdd->nd = pdd->ndata;
+               pdd->tot_vec_size = tot_vec_size;
        }
-       else if(psys->pdd) {
+       else if (psys->pdd) {
                psys_free_pdd(psys);
                MEM_freeN(psys->pdd);
                pdd = psys->pdd = NULL;
        }
 
-       if(pdd) {
-               pdd->ma_col= ma_col;
+       if (pdd) {
+               pdd->ma_col = ma_col;
        }
 
-       psys->lattice= psys_get_lattice(&sim);
+       psys->lattice = psys_get_lattice(&sim);
 
        /* circles don't use drawdata, so have to add a special case here */
-       if((pdd || draw_as==PART_DRAW_CIRC) && draw_as!=PART_DRAW_PATH){
-/* 5. */
-               if(pdd && (pdd->flag & PARTICLE_DRAW_DATA_UPDATED)
-                       && (pdd->vedata || part->draw & (PART_DRAW_SIZE|PART_DRAW_NUM|PART_DRAW_HEALTH))==0) {
+       if ((pdd || draw_as == PART_DRAW_CIRC) && draw_as != PART_DRAW_PATH) {
+               /* 5. */
+               if (pdd && (pdd->flag & PARTICLE_DRAW_DATA_UPDATED) &&
+                   (pdd->vedata || part->draw & (PART_DRAW_SIZE | PART_DRAW_NUM | PART_DRAW_HEALTH)) == 0)
+               {
                        totpoint = pdd->totpoint; /* draw data is up to date */
                }
-               else for(a=0,pa=pars; a<totpart+totchild; a++, pa++){
-                       /* setup per particle individual stuff */
-                       if(a<totpart){
-                               if(totchild && (part->draw&PART_DRAW_PARENT)==0) continue;
-                               if(pa->flag & PARS_NO_DISP || pa->flag & PARS_UNEXIST) continue;
-
-                               pa_time=(cfra-pa->time)/pa->lifetime;
-                               pa_birthtime=pa->time;
-                               pa_dietime = pa->dietime;
-                               pa_size=pa->size;
-                               if(part->phystype==PART_PHYS_BOIDS)
-                                       pa_health = pa->boid->data.health;
-                               else
-                                       pa_health = -1.0;
-
-                               r_tilt = 2.0f*(PSYS_FRAND(a + 21) - 0.5f);
-                               r_length = PSYS_FRAND(a + 22);
-
-                               if(part->draw_col > PART_DRAW_COL_MAT) {
-                                       switch(part->draw_col) {
-                                               case PART_DRAW_COL_VEL:
-                                                       intensity = len_v3(pa->state.vel)/part->color_vec_max;
-                                                       break;
-                                               case PART_DRAW_COL_ACC:
-                                                       intensity = len_v3v3(pa->state.vel, pa->prev_state.vel)/((pa->state.time-pa->prev_state.time)*part->color_vec_max);
-                                                       break;
-                                               default:
-                                                       intensity= 1.0f; /* should never happen */
+               else {
+                       for (a = 0, pa = pars; a < totpart + totchild; a++, pa++) {
+                               /* setup per particle individual stuff */
+                               if (a < totpart) {
+                                       if (totchild && (part->draw & PART_DRAW_PARENT) == 0) continue;
+                                       if (pa->flag & PARS_NO_DISP || pa->flag & PARS_UNEXIST) continue;
+
+                                       pa_time = (cfra - pa->time) / pa->lifetime;
+                                       pa_birthtime = pa->time;
+                                       pa_dietime = pa->dietime;
+                                       pa_size = pa->size;
+                                       if (part->phystype == PART_PHYS_BOIDS)
+                                               pa_health = pa->boid->data.health;
+                                       else
+                                               pa_health = -1.0;
+
+                                       r_tilt = 2.0f * (PSYS_FRAND(a + 21) - 0.5f);
+                                       r_length = PSYS_FRAND(a + 22);
+
+                                       if (part->draw_col > PART_DRAW_COL_MAT) {
+                                               switch (part->draw_col) {
+                                                       case PART_DRAW_COL_VEL:
+                                                               intensity = len_v3(pa->state.vel) / part->color_vec_max;
+                                                               break;
+                                                       case PART_DRAW_COL_ACC:
+                                                               intensity = len_v3v3(pa->state.vel, pa->prev_state.vel) / ((pa->state.time - pa->prev_state.time) * part->color_vec_max);
+                                                               break;
+                                                       default:
+                                                               intensity = 1.0f; /* should never happen */
+                                               }
+                                               CLAMP(intensity, 0.f, 1.f);
+                                               weight_to_rgb(ma_col, intensity);
                                        }
-                                       CLAMP(intensity, 0.f, 1.f);
-                                       weight_to_rgb(ma_col, intensity);
                                }
-                       }
-                       else{
-                               ChildParticle *cpa= &psys->child[a-totpart];
-
-                               pa_time=psys_get_child_time(psys,cpa,cfra,&pa_birthtime,&pa_dietime);
-                               pa_size=psys_get_child_size(psys,cpa,cfra,NULL);
-
-                               pa_health = -1.0;
+                               else {
+                                       ChildParticle *cpa = &psys->child[a - totpart];
 
-                               r_tilt = 2.0f*(PSYS_FRAND(a + 21) - 0.5f);
-                               r_length = PSYS_FRAND(a + 22);
-                       }
+                                       pa_time = psys_get_child_time(psys, cpa, cfra, &pa_birthtime, &pa_dietime);
+                                       pa_size = psys_get_child_size(psys, cpa, cfra, NULL);
 
-                       drawn = 0;
-                       if(part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
-                               float length = part->path_end * (1.0f - part->randlength * r_length);
-                               int trail_count = part->trail_count * (1.0f - part->randlength * r_length);
-                               float ct = ((part->draw & PART_ABS_PATH_TIME) ? cfra : pa_time) - length;
-                               float dt = length / (trail_count ? (float)trail_count : 1.0f);
-                               int i=0;
+                                       pa_health = -1.0;
 
-                               ct+=dt;
-                               for(i=0; i < trail_count; i++, ct += dt) {
-                                       float pixsize;
+                                       r_tilt = 2.0f * (PSYS_FRAND(a + 21) - 0.5f);
+                                       r_length = PSYS_FRAND(a + 22);
+                               }
 
-                                       if(part->draw & PART_ABS_PATH_TIME) {
-                                               if(ct < pa_birthtime || ct > pa_dietime)
+                               drawn = 0;
+                               if (part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
+                                       float length = part->path_end * (1.0f - part->randlength * r_length);
+                                       int trail_count = part->trail_count * (1.0f - part->randlength * r_length);
+                                       float ct = ((part->draw & PART_ABS_PATH_TIME) ? cfra : pa_time) - length;
+                                       float dt = length / (trail_count ? (float)trail_count : 1.0f);
+                                       int i = 0;
+
+                                       ct += dt;
+                                       for (i = 0; i < trail_count; i++, ct += dt) {
+                                               float pixsize;
+
+                                               if (part->draw & PART_ABS_PATH_TIME) {
+                                                       if (ct < pa_birthtime || ct > pa_dietime)
+                                                               continue;
+                                               }
+                                               else if (ct < 0.0f || ct > 1.0f)
                                                        continue;
-                                       }
-                                       else if(ct < 0.0f || ct > 1.0f)
-                                               continue;
 
-                                       state.time = (part->draw & PART_ABS_PATH_TIME) ? -ct : -(pa_birthtime + ct * (pa_dietime - pa_birthtime));
-                                       psys_get_particle_on_path(&sim,a,&state,need_v);
-                                       
-                                       if(psys->parent)
-                                               mul_m4_v3(psys->parent->obmat, state.co);
-
-                                       /* create actiual particle data */
-                                       if(draw_as == PART_DRAW_BB) {
-                                               bb.offset[0] = part->bb_offset[0];
-                                               bb.offset[1] = part->bb_offset[1];
-                                               bb.size[0] = part->bb_size[0] * pa_size;
-                                               if (part->bb_align==PART_BB_VEL) {
-                                                       float pa_vel = len_v3(state.vel);
-                                                       float head = part->bb_vel_head*pa_vel;
-                                                       float tail = part->bb_vel_tail*pa_vel;
-                                                       bb.size[1] = part->bb_size[1]*pa_size + head + tail;
-                                                       /* use offset to adjust the particle center. this is relative to size, so need to divide! */
-                                                       if (bb.size[1] > 0.0f)
-                                                               bb.offset[1] += (head-tail) / bb.size[1];
+                                               state.time = (part->draw & PART_ABS_PATH_TIME) ? -ct : -(pa_birthtime + ct * (pa_dietime - pa_birthtime));
+                                               psys_get_particle_on_path(&sim, a, &state, need_v);
+
+                                               if (psys->parent)
+                                                       mul_m4_v3(psys->parent->obmat, state.co);
+
+                                               /* create actiual particle data */
+                                               if (draw_as == PART_DRAW_BB) {
+                                                       bb.offset[0] = part->bb_offset[0];
+                                                       bb.offset[1] = part->bb_offset[1];
+                                                       bb.size[0] = part->bb_size[0] * pa_size;
+                                                       if (part->bb_align == PART_BB_VEL) {
+                                                               float pa_vel = len_v3(state.vel);
+                                                               float head = part->bb_vel_head * pa_vel;
+                                                               float tail = part->bb_vel_tail * pa_vel;
+                                                               bb.size[1] = part->bb_size[1] * pa_size + head + tail;
+                                                               /* use offset to adjust the particle center. this is relative to size, so need to divide! */
+                                                               if (bb.size[1] > 0.0f)
+                                                                       bb.offset[1] += (head - tail) / bb.size[1];
+                                                       }
+                                                       else
+                                                               bb.size[1] = part->bb_size[1] * pa_size;
+                                                       bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
+                                                       bb.time = ct;
                                                }
-                                               else
-                                                       bb.size[1] = part->bb_size[1] * pa_size;
-                                               bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
-                                               bb.time = ct;
-                                       }
 
-                                       pixsize = ED_view3d_pixel_size(rv3d, state.co) * pixsize_scale;
+                                               pixsize = ED_view3d_pixel_size(rv3d, state.co) * pixsize_scale;
 
-                                       draw_particle(&state, draw_as, part->draw, pixsize, imat, part->draw_line, &bb, psys->pdd);
+                                               draw_particle(&state, draw_as, part->draw, pixsize, imat, part->draw_line, &bb, psys->pdd);
 
-                                       totpoint++;
-                                       drawn = 1;
+                                               totpoint++;
+                                               drawn = 1;
+                                       }
                                }
-                       }
-                       else
-                       {
-                               state.time=cfra;
-                               if(psys_get_particle_state(&sim,a,&state,0)){
-                                       float pixsize;
-
-                                       if(psys->parent)
-                                               mul_m4_v3(psys->parent->obmat, state.co);
-
-                                       /* create actiual particle data */
-                                       if(draw_as == PART_DRAW_BB) {
-                                               bb.offset[0] = part->bb_offset[0];
-                                               bb.offset[1] = part->bb_offset[1];
-                                               bb.size[0] = part->bb_size[0] * pa_size;
-                                               if (part->bb_align==PART_BB_VEL) {
-                                                       float pa_vel = len_v3(state.vel);
-                                                       float head = part->bb_vel_head*pa_vel;
-                                                       float tail = part->bb_vel_tail*pa_vel;
-                                                       bb.size[1] = part->bb_size[1]*pa_size + head + tail;
-                                                       /* use offset to adjust the particle center. this is relative to size, so need to divide! */
-                                                       if (bb.size[1] > 0.0f)
-                                                               bb.offset[1] += (head-tail) / bb.size[1];
+                               else {
+                                       state.time = cfra;
+                                       if (psys_get_particle_state(&sim, a, &state, 0)) {
+                                               float pixsize;
+
+                                               if (psys->parent)
+                                                       mul_m4_v3(psys->parent->obmat, state.co);
+
+                                               /* create actiual particle data */
+                                               if (draw_as == PART_DRAW_BB) {
+                                                       bb.offset[0] = part->bb_offset[0];
+                                                       bb.offset[1] = part->bb_offset[1];
+                                                       bb.size[0] = part->bb_size[0] * pa_size;
+                                                       if (part->bb_align == PART_BB_VEL) {
+                                                               float pa_vel = len_v3(state.vel);
+                                                               float head = part->bb_vel_head * pa_vel;
+                                                               float tail = part->bb_vel_tail * pa_vel;
+                                                               bb.size[1] = part->bb_size[1] * pa_size + head + tail;
+                                                               /* use offset to adjust the particle center. this is relative to size, so need to divide! */
+                                                               if (bb.size[1] > 0.0f)
+                                                                       bb.offset[1] += (head - tail) / bb.size[1];
+                                                       }
+                                                       else
+                                                               bb.size[1] = part->bb_size[1] * pa_size;
+                                                       bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
+                                                       bb.time = pa_time;
                                                }
-                                               else
-                                                       bb.size[1] = part->bb_size[1] * pa_size;
-                                               bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
-                                               bb.time = pa_time;
-                                       }
 
-                                       pixsize = ED_view3d_pixel_size(rv3d, state.co) * pixsize_scale;
+                                               pixsize = ED_view3d_pixel_size(rv3d, state.co) * pixsize_scale;
 
-                                       draw_particle(&state, draw_as, part->draw, pixsize, imat, part->draw_line, &bb, pdd);
+                                               draw_particle(&state, draw_as, part->draw, pixsize, imat, part->draw_line, &bb, pdd);
 
-                                       totpoint++;
-                                       drawn = 1;
+                                               totpoint++;
+                                               drawn = 1;
+                                       }
                                }
-                       }
-
-                       if(drawn) {
-                               /* additional things to draw for each particle  */
-                               /* (velocity, size and number)                                  */
-                               if((part->draw & PART_DRAW_VEL) && pdd && pdd->vedata){
-                                       copy_v3_v3(pdd->ved,state.co);
-                                       pdd->ved += 3;
-                                       mul_v3_v3fl(vel, state.vel, timestep);
-                                       add_v3_v3v3(pdd->ved, state.co, vel);
-                                       pdd->ved+=3;
 
-                                       totve++;
-                               }
+                               if (drawn) {
+                                       /* additional things to draw for each particle  */
+                                       /* (velocity, size and number)                                  */
+                                       if ((part->draw & PART_DRAW_VEL) && pdd && pdd->vedata) {
+                                               copy_v3_v3(pdd->ved, state.co);
+                                               pdd->ved += 3;
+                                               mul_v3_v3fl(vel, state.vel, timestep);
+                                               add_v3_v3v3(pdd->ved, state.co, vel);
+                                               pdd->ved += 3;
+
+                                               totve++;
+                                       }
 
-                               if(part->draw & PART_DRAW_SIZE){
-                                       setlinestyle(3);
-                                       drawcircball(GL_LINE_LOOP, state.co, pa_size, imat);
-                                       setlinestyle(0);
-                               }
+                                       if (part->draw & PART_DRAW_SIZE) {
+                                               setlinestyle(3);
+                                               drawcircball(GL_LINE_LOOP, state.co, pa_size, imat);
+                                               setlinestyle(0);
+                                       }
 
 
-                               if((part->draw & PART_DRAW_NUM || part->draw & PART_DRAW_HEALTH) && (v3d->flag2 & V3D_RENDER_OVERRIDE)==0){
-                                       float vec_txt[3];
-                                       char *val_pos= numstr;
-                                       numstr[0]= '\0';
+                                       if ((part->draw & PART_DRAW_NUM || part->draw & PART_DRAW_HEALTH) &&
+                                           (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0)
+                                       {
+                                               float vec_txt[3];
+                                               char *val_pos = numstr;
+                                               numstr[0] = '\0';
 
-                                       if(part->draw&PART_DRAW_NUM) {
-                                               if(a < totpart && (part->draw & PART_DRAW_HEALTH) && (part->phystype==PART_PHYS_BOIDS)) {
-                                                       sprintf(val_pos, "%d:%.2f", a, pa_health);
+                                               if (part->draw & PART_DRAW_NUM) {
+                                                       if (a < totpart && (part->draw & PART_DRAW_HEALTH) && (part->phystype == PART_PHYS_BOIDS)) {
+                                                               sprintf(val_pos, "%d:%.2f", a, pa_health);
+                                                       }
+                                                       else {
+                                                               sprintf(val_pos, "%d", a);
+                                                       }
                                                }
                                                else {
-                                                       sprintf(val_pos, "%d", a);
-                                               }
-                                       }
-                                       else {
-                                               if(a < totpart && (part->draw & PART_DRAW_HEALTH) && (part->phystype==PART_PHYS_BOIDS)) {
-                                                       sprintf(val_pos, "%.2f", pa_health);
+                                                       if (a < totpart && (part->draw & PART_DRAW_HEALTH) && (part->phystype == PART_PHYS_BOIDS)) {
+                                                               sprintf(val_pos, "%.2f", pa_health);
+                                                       }
                                                }
-                                       }
 
-                                       /* in path drawing state.co is the end point */
-                                       /* use worldspace beause object matrix is already applied */
-                                       mul_v3_m4v3(vec_txt, ob->imat, state.co);
-                                       view3d_cached_text_draw_add(vec_txt, numstr, 10, V3D_CACHE_TEXT_WORLDSPACE|V3D_CACHE_TEXT_ASCII, tcol);
+                                               /* in path drawing state.co is the end point */
+                                               /* use worldspace beause object matrix is already applied */
+                                               mul_v3_m4v3(vec_txt, ob->imat, state.co);
+                                               view3d_cached_text_draw_add(vec_txt, numstr,&n