fix [#34098] Crash after using Decimate or Remesh modifiers
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.c
index c28958d5b0db4291d90277a8c94e562811ed61fe..8e740075bc64a2cf9f0203fb7e2ccc9e55982c2a 100644 (file)
 #include "BLI_math.h"
 #include "BLI_memarena.h"
 #include "BLI_array.h"
-#include "BLI_pbvh.h"
 #include "BLI_utildefines.h"
 #include "BLI_linklist.h"
 
-#include "BLF_translation.h"
-
+#include "BKE_pbvh.h"
 #include "BKE_cdderivedmesh.h"
 #include "BKE_displist.h"
 #include "BKE_key.h"
 #include "BKE_modifier.h"
 #include "BKE_mesh.h"
 #include "BKE_object.h"
+#include "BKE_object_deform.h"
 #include "BKE_paint.h"
 #include "BKE_texture.h"
 #include "BKE_multires.h"
@@ -74,7 +73,7 @@
 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
 #endif
 
-#include "BLO_sys_types.h" // for intptr_t support
+#include "BLO_sys_types.h" /* for intptr_t support */
 
 #include "GL/glew.h"
 
@@ -95,7 +94,7 @@ static MVert *dm_getVertArray(DerivedMesh *dm)
 
        if (!mvert) {
                mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
-                       dm->getNumVerts(dm));
+                                            dm->getNumVerts(dm));
                CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
                dm->copyVertArray(dm, mvert);
        }
@@ -109,7 +108,7 @@ static MEdge *dm_getEdgeArray(DerivedMesh *dm)
 
        if (!medge) {
                medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
-                       dm->getNumEdges(dm));
+                                            dm->getNumEdges(dm));
                CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
                dm->copyEdgeArray(dm, medge);
        }
@@ -146,7 +145,7 @@ static MLoop *dm_getLoopArray(DerivedMesh *dm)
 
        if (!mloop) {
                mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
-                       dm->getNumLoops(dm));
+                                            dm->getNumLoops(dm));
                CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
                dm->copyLoopArray(dm, mloop);
        }
@@ -160,7 +159,7 @@ static MPoly *dm_getPolyArray(DerivedMesh *dm)
 
        if (!mpoly) {
                mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
-                       dm->getNumPolys(dm));
+                                            dm->getNumPolys(dm));
                CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
                dm->copyPolyArray(dm, mpoly);
        }
@@ -170,8 +169,8 @@ static MPoly *dm_getPolyArray(DerivedMesh *dm)
 
 static MVert *dm_dupVertArray(DerivedMesh *dm)
 {
-       MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
-                                                        "dm_dupVertArray tmp");
+       MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm),
+                                "dm_dupVertArray tmp");
 
        if (tmp) dm->copyVertArray(dm, tmp);
 
@@ -180,8 +179,8 @@ static MVert *dm_dupVertArray(DerivedMesh *dm)
 
 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
 {
-       MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
-                                                        "dm_dupEdgeArray tmp");
+       MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm),
+                                "dm_dupEdgeArray tmp");
 
        if (tmp) dm->copyEdgeArray(dm, tmp);
 
@@ -190,8 +189,8 @@ static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
 
 static MFace *dm_dupFaceArray(DerivedMesh *dm)
 {
-       MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
-                                                        "dm_dupFaceArray tmp");
+       MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
+                                "dm_dupFaceArray tmp");
 
        if (tmp) dm->copyTessFaceArray(dm, tmp);
 
@@ -200,8 +199,8 @@ static MFace *dm_dupFaceArray(DerivedMesh *dm)
 
 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
 {
-       MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumLoops(dm),
-                                                        "dm_dupLoopArray tmp");
+       MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm),
+                                "dm_dupLoopArray tmp");
 
        if (tmp) dm->copyLoopArray(dm, tmp);
 
@@ -210,8 +209,8 @@ static MLoop *dm_dupLoopArray(DerivedMesh *dm)
 
 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
 {
-       MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumPolys(dm),
-                                                        "dm_dupPolyArray tmp");
+       MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm),
+                                "dm_dupPolyArray tmp");
 
        if (tmp) dm->copyPolyArray(dm, tmp);
 
@@ -266,9 +265,11 @@ void DM_init_funcs(DerivedMesh *dm)
        dm->getVertData = DM_get_vert_data;
        dm->getEdgeData = DM_get_edge_data;
        dm->getTessFaceData = DM_get_tessface_data;
+       dm->getPolyData = DM_get_poly_data;
        dm->getVertDataArray = DM_get_vert_data_layer;
        dm->getEdgeDataArray = DM_get_edge_data_layer;
        dm->getTessFaceDataArray = DM_get_tessface_data_layer;
+       dm->getPolyDataArray = DM_get_poly_data_layer;
 
        bvhcache_init(&dm->bvhCache);
 }
@@ -288,6 +289,13 @@ void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
        dm->needsFree = 1;
        dm->auto_bump_scale = -1.0f;
        dm->dirty = 0;
+
+       /* don't use CustomData_reset(...); because we dont want to touch customdata */
+       fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
+       fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
+       fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
+       fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
+       fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
 }
 
 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
@@ -295,16 +303,18 @@ void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type
                       int numLoops, int numPolys)
 {
        CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
-                                       CD_CALLOC, numVerts);
+                       CD_CALLOC, numVerts);
        CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
-                                       CD_CALLOC, numEdges);
+                       CD_CALLOC, numEdges);
        CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
-                                       CD_CALLOC, numTessFaces);
+                       CD_CALLOC, numTessFaces);
        CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
                        CD_CALLOC, numLoops);
        CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
                        CD_CALLOC, numPolys);
 
+       dm->cd_flag = source->cd_flag;
+
        dm->type = type;
        dm->numVertData = numVerts;
        dm->numEdgeData = numEdges;
@@ -322,7 +332,7 @@ int DM_release(DerivedMesh *dm)
 {
        if (dm->needsFree) {
                bvhcache_free(&dm->bvhCache);
-               GPU_drawobject_free( dm );
+               GPU_drawobject_free(dm);
                CustomData_free(&dm->vertData, dm->numVertData);
                CustomData_free(&dm->edgeData, dm->numEdgeData);
                CustomData_free(&dm->faceData, dm->numTessFaceData);
@@ -371,7 +381,7 @@ void DM_ensure_tessface(DerivedMesh *dm)
        const int numTessFaces = dm->getNumTessFaces(dm);
        const int numPolys =     dm->getNumPolys(dm);
 
-       if ( (numTessFaces == 0) && (numPolys != 0)) {
+       if ((numTessFaces == 0) && (numPolys != 0)) {
                dm->recalcTessellation(dm);
 
                if (dm->getNumTessFaces(dm) != 0) {
@@ -383,8 +393,8 @@ void DM_ensure_tessface(DerivedMesh *dm)
                }
        }
 
-       else if (dm->dirty && DM_DIRTY_TESS_CDLAYERS) {
-               BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX));
+       else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
+               BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX) || numTessFaces == 0);
                DM_update_tessface_data(dm);
        }
 
@@ -408,7 +418,7 @@ void DM_update_tessface_data(DerivedMesh *dm)
        const int hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
        const int hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
 
-       int *polyindex = CustomData_get_layer(fdata, CD_POLYINDEX);
+       int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
 
        int mf_idx,
            totface = dm->getNumTessFaces(dm),
@@ -426,7 +436,7 @@ void DM_update_tessface_data(DerivedMesh *dm)
 
                /* Find out loop indices. */
                /* XXX Is there a better way to do this? */
-               /* NOTE: This assumes tessface are valid and in sync with loop/poly Else, most likely, segfault! */
+               /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
                for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
                        MLoop *tml = &ml[i];
                        if (tml->v == mf->v1) {
@@ -446,10 +456,10 @@ void DM_update_tessface_data(DerivedMesh *dm)
                                not_done--;
                        }
                }
-               mesh_loops_to_mface_corners(fdata, ldata, pdata,
-                                           ml_idx, mf_idx, polyindex[mf_idx],
-                                           mf_len,
-                                           numTex, numCol, hasPCol, hasOrigSpace);
+               BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata,
+                                               ml_idx, mf_idx, polyindex[mf_idx],
+                                               mf_len,
+                                               numTex, numCol, hasPCol, hasOrigSpace);
        }
 
        if (G.debug & G_DEBUG)
@@ -463,42 +473,44 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
        /* dm might depend on me, so we need to do everything with a local copy */
        Mesh tmp = *me;
        int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
-       int did_shapekeys=0;
+       int did_shapekeys = 0;
        
-       memset(&tmp.vdata, 0, sizeof(tmp.vdata));
-       memset(&tmp.edata, 0, sizeof(tmp.edata));
-       memset(&tmp.fdata, 0, sizeof(tmp.fdata));
-       memset(&tmp.ldata, 0, sizeof(tmp.ldata));
-       memset(&tmp.pdata, 0, sizeof(tmp.pdata));
+       CustomData_reset(&tmp.vdata);
+       CustomData_reset(&tmp.edata);
+       CustomData_reset(&tmp.fdata);
+       CustomData_reset(&tmp.ldata);
+       CustomData_reset(&tmp.pdata);
 
        totvert = tmp.totvert = dm->getNumVerts(dm);
        totedge = tmp.totedge = dm->getNumEdges(dm);
        totloop = tmp.totloop = dm->getNumLoops(dm);
        totpoly = tmp.totpoly = dm->getNumPolys(dm);
+       tmp.totface = 0;
 
        CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
        CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
        CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
        CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
+       me->cd_flag = dm->cd_flag;
 
        if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
                KeyBlock *kb;
                int uid;
                
                if (ob) {
-                       kb = BLI_findlink(&me->key->block, ob->shapenr-1);
+                       kb = BLI_findlink(&me->key->block, ob->shapenr - 1);
                        if (kb) {
                                uid = kb->uid;
                        }
                        else {
                                printf("%s: error - could not find active shapekey %d!\n",
-                                      __func__, ob->shapenr-1);
+                                      __func__, ob->shapenr - 1);
 
                                uid = INT_MAX;
                        }
                }
                else {
-                       /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
+                       /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
                        uid = INT_MAX;
                }
 
@@ -530,9 +542,10 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
        }
 
        /* yes, must be before _and_ after tessellate */
-       mesh_update_customdata_pointers(&tmp, TRUE);
+       mesh_update_customdata_pointers(&tmp, false);
 
-       BKE_mesh_tessface_calc(&tmp);
+       /* since 2.65 caller must do! */
+       // BKE_mesh_tessface_calc(&tmp);
 
        CustomData_free(&me->vdata, me->totvert);
        CustomData_free(&me->edata, me->totedge);
@@ -541,7 +554,7 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
        CustomData_free(&me->pdata, me->totpoly);
 
        /* ok, this should now use new CD shapekey data,
-        * which shouuld be fed through the modifier
+        * which should be fed through the modifier
         * stack*/
        if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
                printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
@@ -549,6 +562,13 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
                tmp.key = NULL;
        }
 
+       /* Clear selection history */
+       tmp.mselect = NULL;
+       tmp.totselect = 0;
+       if (me->mselect) {
+               MEM_freeN(me->mselect);
+       }
+
        *me = tmp;
 }
 
@@ -558,16 +578,16 @@ void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
        float *fp;
        MVert *mvert;
        
-       if (totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
+       if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) return;
        
        if (kb->data) MEM_freeN(kb->data);
-       kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
-       kb->totelem= totvert;
+       kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data");
+       kb->totelem = totvert;
        
-       fp= kb->data;
-       mvert=dm->getVertDataArray(dm, CD_MVERT);
+       fp = kb->data;
+       mvert = dm->getVertDataArray(dm, CD_MVERT);
        
-       for (a=0; a<kb->totelem; a++, fp+=3, mvert++) {
+       for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
                copy_v3_v3(fp, mvert->co);
        }
 }
@@ -577,6 +597,13 @@ void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
        CustomData_set_only_copy(&dm->vertData, mask);
        CustomData_set_only_copy(&dm->edgeData, mask);
        CustomData_set_only_copy(&dm->faceData, mask);
+       /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
+        * weight paint mode when there are modifiers applied, needs further investigation,
+        * see replies to r50969, Campbell */
+#if 0
+       CustomData_set_only_copy(&dm->loopData, mask);
+       CustomData_set_only_copy(&dm->polyData, mask);
+#endif
 }
 
 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
@@ -619,6 +646,12 @@ void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
        return CustomData_get(&dm->faceData, index, type);
 }
 
+void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
+{
+       return CustomData_get(&dm->polyData, index, type);
+}
+
+
 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
 {
        if (type == CD_MVERT)
@@ -669,24 +702,24 @@ void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
 }
 
 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
-                                          int source_index, int dest_index, int count)
+                       int source_index, int dest_index, int count)
 {
        CustomData_copy_data(&source->vertData, &dest->vertData,
-                                                source_index, dest_index, count);
+                            source_index, dest_index, count);
 }
 
 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
-                                          int source_index, int dest_index, int count)
+                       int source_index, int dest_index, int count)
 {
        CustomData_copy_data(&source->edgeData, &dest->edgeData,
-                                                source_index, dest_index, count);
+                            source_index, dest_index, count);
 }
 
 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
-                                          int source_index, int dest_index, int count)
+                           int source_index, int dest_index, int count)
 {
        CustomData_copy_data(&source->faceData, &dest->faceData,
-                                                source_index, dest_index, count);
+                            source_index, dest_index, count);
 }
 
 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
@@ -729,29 +762,29 @@ void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
 }
 
 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
-                                                int *src_indices, float *weights,
-                                                int count, int dest_index)
+                         int *src_indices, float *weights,
+                         int count, int dest_index)
 {
        CustomData_interp(&source->vertData, &dest->vertData, src_indices,
-                                         weights, NULL, count, dest_index);
+                         weights, NULL, count, dest_index);
 }
 
 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
-                                                int *src_indices,
-                                                float *weights, EdgeVertWeight *vert_weights,
-                                                int count, int dest_index)
+                         int *src_indices,
+                         float *weights, EdgeVertWeight *vert_weights,
+                         int count, int dest_index)
 {
        CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
-                                         weights, (float*)vert_weights, count, dest_index);
+                         weights, (float *)vert_weights, count, dest_index);
 }
 
 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
-                                                int *src_indices,
-                                                float *weights, FaceVertWeight *vert_weights,
-                                                int count, int dest_index)
+                             int *src_indices,
+                             float *weights, FaceVertWeight *vert_weights,
+                             int count, int dest_index)
 {
        CustomData_interp(&source->faceData, &dest->faceData, src_indices,
-                                         weights, (float*)vert_weights, count, dest_index);
+                         weights, (float *)vert_weights, count, dest_index);
 }
 
 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
@@ -801,20 +834,20 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
        DerivedMesh *dm;
        KeyBlock *kb;
 
-       md->scene= scene;
+       md->scene = scene;
        
-       if (!(md->mode&eModifierMode_Realtime)) return NULL;
+       if (!(md->mode & eModifierMode_Realtime)) return NULL;
        if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
        
-       if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr-1))) {
-               key_to_mesh(kb, me);
+       if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
+               BKE_key_convert_to_mesh(kb, me);
        }
        
-       if (mti->type==eModifierTypeType_OnlyDeform) {
+       if (mti->type == eModifierTypeType_OnlyDeform) {
                int numVerts;
                float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
 
-               mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
+               mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
                dm = mesh_create_derived(me, ob, deformedVerts);
 
                if (build_shapekey_layers)
@@ -828,7 +861,7 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
                if (build_shapekey_layers)
                        add_shapekey_layers(tdm, me, ob);
                
-               dm = mti->applyModifier(md, ob, tdm, 0, 0);
+               dm = mti->applyModifier(md, ob, tdm, 0);
 
                if (tdm != dm) tdm->release(tdm);
        }
@@ -836,48 +869,45 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
        return dm;
 }
 
-static float *get_editbmesh_orco_verts(BMEditMesh *em)
+static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
 {
        BMIter iter;
        BMVert *eve;
-       float *orco;
-       int a, totvert;
+       float (*orco)[3];
+       int i;
 
        /* these may not really be the orco's, but it's only for preview.
         * could be solver better once, but isn't simple */
-
-       totvert= em->bm->totvert;
        
-       orco = MEM_mallocN(sizeof(float)*3*totvert, "BMEditMesh Orco");
+       orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
 
-       eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
-       for (a=0; eve; eve=BM_iter_step(&iter), a+=3) {
-               copy_v3_v3(orco+a, eve->co);
+       BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
+               copy_v3_v3(orco[i], eve->co);
        }
        
        return orco;
 }
 
 /* orco custom data layer */
-static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
+static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
 {
-       *free= 0;
+       *free = 0;
 
        if (layer == CD_ORCO) {
                /* get original coordinates */
-               *free= 1;
+               *free = 1;
 
                if (em)
-                       return (float(*)[3])get_editbmesh_orco_verts(em);
+                       return get_editbmesh_orco_verts(em);
                else
-                       return (float(*)[3])get_mesh_orco_verts(ob);
+                       return BKE_mesh_orco_verts_get(ob);
        }
        else if (layer == CD_CLOTH_ORCO) {
                /* apply shape key for cloth, this should really be solved
                 * by a more flexible customdata system, but not simple */
                if (!em) {
                        ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
-                       KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
+                       KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
 
                        if (kb->data)
                                return kb->data;
@@ -895,10 +925,10 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int lay
        float (*orco)[3];
        int free;
 
-       if (em) dm= CDDM_from_BMEditMesh(em, me, FALSE, FALSE);
-       else dm= CDDM_from_mesh(me, ob);
+       if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
+       else dm = CDDM_from_mesh(me, ob);
 
-       orco= get_orco_coords_dm(ob, em, layer, &free);
+       orco = get_orco_coords_dm(ob, em, layer, &free);
 
        if (orco) {
                CDDM_apply_vert_coords(dm, orco);
@@ -911,16 +941,16 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int lay
 }
 
 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
-                                               DerivedMesh *orcodm, int layer)
+                        DerivedMesh *orcodm, int layer)
 {
        float (*orco)[3], (*layerorco)[3];
        int totvert, free;
 
-       totvert= dm->getNumVerts(dm);
+       totvert = dm->getNumVerts(dm);
 
        if (orcodm) {
-               orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
-               free= 1;
+               orco = MEM_callocN(sizeof(float) * 3 * totvert, "dm orco");
+               free = 1;
 
                if (orcodm->getNumVerts(orcodm) == totvert)
                        orcodm->getVertCos(orcodm, orco);
@@ -928,18 +958,18 @@ static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
                        dm->getVertCos(dm, orco);
        }
        else
-               orco= get_orco_coords_dm(ob, em, layer, &free);
+               orco = get_orco_coords_dm(ob, em, layer, &free);
 
        if (orco) {
                if (layer == CD_ORCO)
-                       transform_mesh_orco_verts(ob->data, orco, totvert, 0);
+                       BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
 
                if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
                        DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
                        layerorco = DM_get_vert_data_layer(dm, layer);
                }
 
-               memcpy(layerorco, orco, sizeof(float)*3*totvert);
+               memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
                if (free) MEM_freeN(orco);
        }
 }
@@ -954,41 +984,41 @@ static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
 
 void weight_to_rgb(float r_rgb[3], const float weight)
 {
-       const float blend= ((weight/2.0f)+0.5f);
+       const float blend = ((weight / 2.0f) + 0.5f);
 
-       if (weight<=0.25f) {    // blue->cyan
-               r_rgb[0]= 0.0f;
-               r_rgb[1]= blend*weight*4.0f;
-               r_rgb[2]= blend;
+       if (weight <= 0.25f) {    /* blue->cyan */
+               r_rgb[0] = 0.0f;
+               r_rgb[1] = blend * weight * 4.0f;
+               r_rgb[2] = blend;
        }
-       else if (weight<=0.50f) {       // cyan->green
-               r_rgb[0]= 0.0f;
-               r_rgb[1]= blend;
-               r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
+       else if (weight <= 0.50f) {  /* cyan->green */
+               r_rgb[0] = 0.0f;
+               r_rgb[1] = blend;
+               r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
        }
-       else if (weight <= 0.75f) {     // green->yellow
-               r_rgb[0]= blend * ((weight-0.50f)*4.0f);
-               r_rgb[1]= blend;
-               r_rgb[2]= 0.0f;
+       else if (weight <= 0.75f) {  /* green->yellow */
+               r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
+               r_rgb[1] = blend;
+               r_rgb[2] = 0.0f;
        }
-       else if (weight <= 1.0f) { // yellow->red
-               r_rgb[0]= blend;
-               r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
-               r_rgb[2]= 0.0f;
+       else if (weight <= 1.0f) {  /* yellow->red */
+               r_rgb[0] = blend;
+               r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
+               r_rgb[2] = 0.0f;
        }
        else {
                /* exceptional value, unclamped or nan,
                 * avoid uninitialized memory use */
-               r_rgb[0]= 1.0f;
-               r_rgb[1]= 0.0f;
-               r_rgb[2]= 1.0f;
+               r_rgb[0] = 1.0f;
+               r_rgb[1] = 0.0f;
+               r_rgb[2] = 1.0f;
        }
 }
 
 /* draw_flag's for calc_weightpaint_vert_color */
 enum {
-       CALC_WP_MULTIPAINT= (1<<0),
-       CALC_WP_AUTO_NORMALIZE= (1<<1)
+       CALC_WP_MULTIPAINT = (1 << 0),
+       CALC_WP_AUTO_NORMALIZE = (1 << 1)
 };
 
 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
@@ -1015,26 +1045,26 @@ static void calc_weightpaint_vert_color(
         unsigned char r_col[4],
         MDeformVert *dv, ColorBand *coba,
         const int defbase_tot, const int defbase_act,
-        const char *dg_flags,
-        const int selected, const int draw_flag)
+        const char *defbase_sel, const int defbase_sel_tot,
+        const int draw_flag)
 {
        float input = 0.0f;
        
-       int make_black= FALSE;
+       int make_black = FALSE;
 
-       if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
-               int was_a_nonzero= FALSE;
+       if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
+               int was_a_nonzero = FALSE;
                unsigned int i;
 
-               MDeformWeight *dw= dv->dw;
+               MDeformWeight *dw = dv->dw;
                for (i = dv->totweight; i != 0; i--, dw++) {
                        /* in multipaint, get the average if auto normalize is inactive
                         * get the sum if it is active */
                        if (dw->def_nr < defbase_tot) {
-                               if (dg_flags[dw->def_nr]) {
+                               if (defbase_sel[dw->def_nr]) {
                                        if (dw->weight) {
                                                input += dw->weight;
-                                               was_a_nonzero= TRUE;
+                                               was_a_nonzero = TRUE;
                                        }
                                }
                        }
@@ -1045,19 +1075,19 @@ static void calc_weightpaint_vert_color(
                        make_black = TRUE;
                }
                else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
-                       input /= selected; /* get the average */
+                       input /= defbase_sel_tot; /* get the average */
                }
        }
        else {
                /* default, non tricky behavior */
-               input= defvert_find_weight(dv, defbase_act);
+               input = defvert_find_weight(dv, defbase_act);
        }
 
        if (make_black) { /* TODO, theme color */
-               r_col[3] = 0;
+               r_col[3] = 255;
                r_col[2] = 0;
                r_col[1] = 0;
-               r_col[0] = 255;
+               r_col[0] = 0;
        }
        else {
                CLAMP(input, 0.0f, 1.0f);
@@ -1065,11 +1095,11 @@ static void calc_weightpaint_vert_color(
        }
 }
 
-static ColorBand *stored_cb= NULL;
+static ColorBand *stored_cb = NULL;
 
 void vDM_ColorBand_store(ColorBand *coba)
 {
-       stored_cb= coba;
+       stored_cb = coba;
 }
 
 /* return an array of vertex weight colors, caller must free.
@@ -1081,7 +1111,7 @@ static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, i
 {
        MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
        int numVerts = dm->getNumVerts(dm);
-       unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * numVerts * 4, "weightmap_v");
+       unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * numVerts * 4, "weightmap_v");
 
        if (dv) {
                unsigned char *wc = wtcol_v;
@@ -1089,15 +1119,22 @@ static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, i
 
                /* variables for multipaint */
                const int defbase_tot = BLI_countlist(&ob->defbase);
-               const int defbase_act = ob->actdef-1;
-               char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
-               const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
+               const int defbase_act = ob->actdef - 1;
+
+               int defbase_sel_tot = 0;
+               char *defbase_sel = NULL;
+
+               if (draw_flag & CALC_WP_MULTIPAINT) {
+                       defbase_sel = BKE_objdef_selected_get(ob, defbase_tot, &defbase_sel_tot);
+               }
 
                for (i = numVerts; i != 0; i--, wc += 4, dv++) {
-                       calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
+                       calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
                }
 
-               MEM_freeN(dg_flags);
+               if (defbase_sel) {
+                       MEM_freeN(defbase_sel);
+               }
        }
        else {
                int col_i;
@@ -1128,122 +1165,67 @@ static unsigned char *calc_colors_from_weights_array(const int num, float *weigh
 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
                            float *weights, int num, const int *indices)
 {
-       ColorBand *coba= stored_cb;     /* warning, not a local var */
+       ColorBand *coba = stored_cb; /* warning, not a local var */
 
        unsigned char *wtcol_v;
-#if 0 /* See coment below. */
-       unsigned char *wtcol_f = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
-#endif
        unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
-#if 0 /* See coment below. */
-       MFace *mf = dm->getTessFaceArray(dm);
-#endif
        MLoop *mloop = dm->getLoopArray(dm), *ml;
        MPoly *mp = dm->getPolyArray(dm);
-#if 0
-       int numFaces = dm->getNumTessFaces(dm);
-#endif
        int numVerts = dm->getNumVerts(dm);
        int totloop;
        int i, j;
 
-#if 0 /* See comment below */
-       /* If no CD_PREVIEW_MCOL existed yet, add a new one! */
-       if (!wtcol_f)
-               wtcol_f = CustomData_add_layer(&dm->faceData, CD_PREVIEW_MCOL, CD_CALLOC, NULL, numFaces);
-
-       if (wtcol_f) {
-               unsigned char *wtcol_f_step = wtcol_f;
-# else
-#if 0
-       /* XXX We have to create a CD_PREVIEW_MCOL, else it might sigsev (after a SubSurf mod, eg)... */
-       if (!dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL))
-               CustomData_add_layer(&dm->faceData, CD_PREVIEW_MCOL, CD_CALLOC, NULL, numFaces);
-#endif
-
-       {
-#endif
-
-               /* Weights are given by caller. */
-               if (weights) {
-                       float *w = weights;
-                       /* If indices is not NULL, it means we do not have weights for all vertices,
-                        * so we must create them (and set them to zero)... */
-                       if (indices) {
-                               w = MEM_callocN(sizeof(float)*numVerts, "Temp weight array DM_update_weight_mcol");
-                               i = num;
-                               while (i--)
-                                       w[indices[i]] = weights[i];
-                       }
-
-                       /* Convert float weights to colors. */
-                       wtcol_v = calc_colors_from_weights_array(numVerts, w);
-
-                       if (indices)
-                               MEM_freeN(w);
+       /* Weights are given by caller. */
+       if (weights) {
+               float *w = weights;
+               /* If indices is not NULL, it means we do not have weights for all vertices,
+                * so we must create them (and set them to zero)... */
+               if (indices) {
+                       w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
+                       i = num;
+                       while (i--)
+                               w[indices[i]] = weights[i];
                }
 
-               /* No weights given, take them from active vgroup(s). */
-               else
-                       wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
+               /* Convert float weights to colors. */
+               wtcol_v = calc_colors_from_weights_array(numVerts, w);
 
-               /* Now copy colors in all face verts. */
-               /*first add colors to the tessellation faces*/
-               /* XXX Why update that layer? We have to update WEIGHT_MLOOPCOL anyway, 
-                *     and tessellation recreates mface layers from mloop/mpoly ones, so no
-                *     need to fill WEIGHT_MCOL here. */
-#if 0
-               for (i = 0; i < numFaces; i++, mf++, wtcol_f_step += (4 * 4)) {
-                       /*origindex being NULL means we're operating on original mesh data*/
-#if 0
-                       unsigned int fidx= mf->v4 ? 3:2;
-
-#else  /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
-                       unsigned int fidx;
-                       if (mf->v4) {
-                               fidx = 3;
-                       }
-                       else {
-                               fidx = 2;
-                               *(int *)(&wtcol_f_step[3 * 4]) = 0;
-                       }
-#endif
+               if (indices)
+                       MEM_freeN(w);
+       }
 
-                       do {
-                               copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
-                                               (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
-                       } while (fidx--);
-               }
-#endif
-               /*now add to loops, so the data can be passed through the modifier stack*/
-               /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
-               if (!wtcol_l) {
-                       BLI_array_declare(wtcol_l);
-                       totloop = 0;
-                       for (i=0; i<dm->numPolyData; i++, mp++) {
-                               ml = mloop + mp->loopstart;
-
-                               BLI_array_growitems(wtcol_l, mp->totloop);
-                               for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
-                                       copy_v4_v4_char((char *)&wtcol_l[totloop],
-                                                       (char *)&wtcol_v[4 * ml->v]);
-                               }
+       /* No weights given, take them from active vgroup(s). */
+       else
+               wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
+
+       /* now add to loops, so the data can be passed through the modifier stack */
+       /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
+       if (!wtcol_l) {
+               BLI_array_declare(wtcol_l);
+               totloop = 0;
+               for (i = 0; i < dm->numPolyData; i++, mp++) {
+                       ml = mloop + mp->loopstart;
+
+                       BLI_array_grow_items(wtcol_l, mp->totloop);
+                       for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
+                               copy_v4_v4_char((char *)&wtcol_l[totloop],
+                                               (char *)&wtcol_v[4 * ml->v]);
                        }
-                       CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
                }
-               else {
-                       totloop = 0;
-                       for (i=0; i < dm->numPolyData; i++, mp++) {
-                               ml = mloop + mp->loopstart;
+               CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
+       }
+       else {
+               totloop = 0;
+               for (i = 0; i < dm->numPolyData; i++, mp++) {
+                       ml = mloop + mp->loopstart;
 
-                               for (j=0; j < mp->totloop; j++, ml++, totloop++) {
-                                       copy_v4_v4_char((char *)&wtcol_l[totloop],
-                                                       (char *)&wtcol_v[4 * ml->v]);
-                               }
+                       for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
+                               copy_v4_v4_char((char *)&wtcol_l[totloop],
+                                               (char *)&wtcol_v[4 * ml->v]);
                        }
                }
-               MEM_freeN(wtcol_v);
        }
+       MEM_freeN(wtcol_v);
 
        dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
 }
@@ -1255,20 +1237,20 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
        int i, j, tot;
        
        if (!me->key)
-               return; 
+               return;
        
        tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
-       for (i=0; i<tot; i++) {
+       for (i = 0; i < tot; i++) {
                CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
                float (*cos)[3], (*kbcos)[3];
                
-               for (kb=me->key->block.first; kb; kb=kb->next) {
+               for (kb = me->key->block.first; kb; kb = kb->next) {
                        if (kb->uid == layer->uid)
                                break;
                }
                
                if (!kb) {
-                       kb = add_keyblock(me->key, layer->name);
+                       kb = BKE_keyblock_add(me->key, layer->name);
                        kb->uid = layer->uid;
                }
                
@@ -1278,28 +1260,28 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
                cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
                kb->totelem = dm->numVertData;
 
-               kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
+               kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
                if (kb->uid == actshape_uid) {
                        MVert *mvert = dm->getVertArray(dm);
                        
-                       for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
+                       for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
                                copy_v3_v3(*kbcos, mvert->co);
                        }
                }
                else {
-                       for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
+                       for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
                                copy_v3_v3(*kbcos, *cos);
                        }
                }
        }
        
-       for (kb=me->key->block.first; kb; kb=kb->next) {
+       for (kb = me->key->block.first; kb; kb = kb->next) {
                if (kb->totelem != dm->numVertData) {
                        if (kb->data)
                                MEM_freeN(kb->data);
                        
                        kb->totelem = dm->numVertData;
-                       kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
+                       kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
                        fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
                }
        }
@@ -1319,11 +1301,11 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
        if (me->totvert != dm->getNumVerts(dm)) {
                fprintf(stderr,
                        "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
-                       __func__, me->id.name+2, me->totvert, dm->getNumVerts(dm));
+                       __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
                return;
        }
 
-       for (i=0, kb=key->block.first; kb; kb=kb->next, i++) {
+       for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
                int ci;
                float *array;
 
@@ -1351,28 +1333,29 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
  * - apply deform modifiers and input vertexco
  */
 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
-                                                               DerivedMesh **deform_r, DerivedMesh **final_r,
-                                                               int useRenderParams, int useDeform,
-                                                               int needMapping, CustomDataMask dataMask, 
-                                                               int index, int useCache, int build_shapekey_layers)
+                                DerivedMesh **deform_r, DerivedMesh **final_r,
+                                int useRenderParams, int useDeform,
+                                int needMapping, CustomDataMask dataMask,
+                                int index, int useCache, int build_shapekey_layers)
 {
        Mesh *me = ob->data;
        ModifierData *firstmd, *md, *previewmd = NULL;
        CDMaskLink *datamasks, *curr;
        /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
-       CustomDataMask mask, nextmask, append_mask = CD_MASK_POLYINDEX;
+       CustomDataMask mask, nextmask, append_mask = CD_MASK_ORIGINDEX;
        float (*deformedVerts)[3] = NULL;
-       DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
+       DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
        int numVerts = me->totvert;
        int required_mode;
-       int isPrevDeform= FALSE;
+       int isPrevDeform = FALSE;
        int skipVirtualArmature = (useDeform < 0);
-       MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
+       MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
        int has_multires = mmd != NULL, multires_applied = 0;
        int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
+       int sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm);
 
-       const int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
-                             (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
+       const int draw_flag = ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
+                              (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
        /* Generic preview only in object mode! */
        const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
@@ -1383,6 +1366,13 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        /* XXX Same as above... For now, only weights preview in WPaint mode. */
        const int do_mod_wmcol = do_init_wmcol;
 
+       ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
+       ModifierApplyFlag deform_app_flags = app_flags;
+       if (useCache)
+               app_flags |= MOD_APPLY_USECACHE;
+       if (useDeform)
+               deform_app_flags |= MOD_APPLY_USECACHE;
+
        if (mmd && !mmd->sculptlvl)
                has_multires = 0;
 
@@ -1422,26 +1412,26 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        deformedVerts = inputVertexCos;
                
                /* Apply all leading deforming modifiers */
-               for (;md; md = md->next, curr = curr->next) {
+               for (; md; md = md->next, curr = curr->next) {
                        ModifierTypeInfo *mti = modifierType_getInfo(md->type);
 
-                       md->scene= scene;
+                       md->scene = scene;
                        
                        if (!modifier_isEnabled(scene, md, required_mode)) continue;
                        if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
 
-                       if (mti->type == eModifierTypeType_OnlyDeform) {
+                       if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
                                if (!deformedVerts)
                                        deformedVerts = mesh_getVertexCos(me, &numVerts);
 
-                               mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
+                               mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
                        }
                        else {
                                break;
                        }
                        
                        /* grab modifiers until index i */
-                       if ((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+                       if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
                                break;
                }
 
@@ -1477,28 +1467,33 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        orcodm = NULL;
        clothorcodm = NULL;
 
-       for (;md; md = md->next, curr = curr->next) {
+       for (; md; md = md->next, curr = curr->next) {
                ModifierTypeInfo *mti = modifierType_getInfo(md->type);
 
-               md->scene= scene;
+               md->scene = scene;
 
                if (!modifier_isEnabled(scene, md, required_mode)) continue;
                if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
                if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
-                       modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
+                       modifier_setError(md, "Modifier requires original data, bad stack position");
                        continue;
                }
-               if (sculpt_mode && (!has_multires || multires_applied)) {
-                       int unsupported= 0;
+               if (sculpt_mode &&
+                       (!has_multires || multires_applied || ob->sculpt->bm))
+               {
+                       int unsupported = 0;
+
+                       if (sculpt_dyntopo)
+                               unsupported = TRUE;
 
                        if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
-                               unsupported|= mti->type != eModifierTypeType_OnlyDeform;
+                               unsupported |= mti->type != eModifierTypeType_OnlyDeform;
 
-                       unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
-                       unsupported|= multires_applied;
+                       unsupported |= md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0;
+                       unsupported |= multires_applied;
 
                        if (unsupported) {
-                               modifier_setError(md, "%s", TIP_("Not supported in sculpt mode."));
+                               modifier_setError(md, "Not supported in sculpt mode");
                                continue;
                        }
                }
@@ -1529,7 +1524,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                                         */
                                        numVerts = dm->getNumVerts(dm);
                                        deformedVerts =
-                                               MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
+                                           MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
                                        dm->getVertCos(dm, deformedVerts);
                                }
                                else {
@@ -1539,7 +1534,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
 
                        /* if this is not the last modifier in the stack then recalculate the normals
                         * to avoid giving bogus normals to the next modifier see: [#23673] */
-                       if (isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
+                       if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
                                /* XXX, this covers bug #23673, but we may need normal calc for other types */
                                if (dm && dm->type == DM_TYPE_CDDM) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
@@ -1547,16 +1542,16 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                                }
                        }
 
-                       mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
+                       mti->deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
                }
                else {
                        DerivedMesh *ndm;
 
                        /* determine which data layers are needed by following modifiers */
                        if (curr->next)
-                               nextmask= curr->next->mask;
+                               nextmask = curr->next->mask;
                        else
-                               nextmask= dataMask;
+                               nextmask = dataMask;
 
                        /* apply vertex coordinates or build a DerivedMesh as necessary */
                        if (dm) {
@@ -1596,15 +1591,21 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                                        DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
 
-                                       range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
-                                       range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
-                                       range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
+#pragma omp parallel sections if (dm->numVertData + dm->numEdgeData + dm->numPolyData >= DM_OMP_LIMIT)
+                                       {
+#pragma omp section
+                                               { range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0); }
+#pragma omp section
+                                               { range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0); }
+#pragma omp section
+                                               { range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0); }
+                                       }
                                }
                        }
 
                        
                        /* set the DerivedMesh to only copy needed data */
-                       mask= curr->mask;
+                       mask = curr->mask;
                        /* needMapping check here fixes bug [#28112], otherwise its
                         * possible that it wont be copied */
                        mask |= append_mask;
@@ -1622,7 +1623,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                                }
                        }
 
-                       ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
+                       ndm = mti->applyModifier(md, ob, dm, app_flags);
 
                        if (ndm) {
                                /* if the modifier returned a new dm, release the old one */
@@ -1641,11 +1642,13 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        /* create an orco derivedmesh in parallel */
                        if (nextmask & CD_MASK_ORCO) {
                                if (!orcodm)
-                                       orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
+                                       orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
 
                                nextmask &= ~CD_MASK_ORCO;
-                               DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
-                               ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
+                               DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
+                                                (mti->requiredDataMask ?
+                                                 mti->requiredDataMask(ob, md) : 0));
+                               ndm = mti->applyModifier(md, ob, orcodm, app_flags & ~MOD_APPLY_USECACHE);
 
                                if (ndm) {
                                        /* if the modifier returned a new dm, release the old one */
@@ -1657,11 +1660,11 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        /* create cloth orco derivedmesh in parallel */
                        if (nextmask & CD_MASK_CLOTH_ORCO) {
                                if (!clothorcodm)
-                                       clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
+                                       clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
 
                                nextmask &= ~CD_MASK_CLOTH_ORCO;
                                DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
-                               ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
+                               ndm = mti->applyModifier(md, ob, clothorcodm, app_flags & ~MOD_APPLY_USECACHE);
 
                                if (ndm) {
                                        /* if the modifier returned a new dm, release the old one */
@@ -1681,17 +1684,17 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        }
                }
 
-               isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
+               isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
 
                /* grab modifiers until index i */
-               if ((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+               if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
                        break;
 
                if (sculpt_mode && md->type == eModifierType_Multires)
                        multires_applied = 1;
        }
 
-       for (md=firstmd; md; md=md->next)
+       for (md = firstmd; md; md = md->next)
                modifier_freeTemporaryData(md);
 
        /* Yay, we are done. If we have a DerivedMesh and deformed vertices
@@ -1722,18 +1725,18 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
 #endif
        }
        else {
-               int recalc_normals= 0;
+               int recalc_normals = 0;
 
                finaldm = CDDM_from_mesh(me, ob);
                
                if (build_shapekey_layers) {
                        add_shapekey_layers(finaldm, me, ob);
-                       recalc_normals= 1;
+                       recalc_normals = 1;
                }
                
                if (deformedVerts) {
                        CDDM_apply_vert_coords(finaldm, deformedVerts);
-                       recalc_normals= 1;
+                       recalc_normals = 1;
                }
 
                if (recalc_normals) {
@@ -1779,16 +1782,16 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
 #if 0
                if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
 #else
-               if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)) */
+               if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */
 #endif
                {
                        finaldm->recalcTessellation(finaldm);
                }
-               /* Even if tessellation is not needed, some modifiers migh have modified CD layers
+               /* Even if tessellation is not needed, some modifiers might have modified CD layers
                 * (like mloopcol or mloopuv), hence we have to update those. */
                else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
-                       /* A tessellation already exists, it should always have a CD_POLYINDEX. */
-                       BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX));
+                       /* A tessellation already exists, it should always have a CD_ORIGINDEX. */
+                       BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX));
                        DM_update_tessface_data(finaldm);
                }
                /* Need to watch this, it can cause issues, see bug [#29338]             */
@@ -1812,10 +1815,10 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        /* NavMesh - this is a hack but saves having a NavMesh modifier */
        if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
                DerivedMesh *tdm;
-               tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
+               tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
                if (finaldm != tdm) {
                        finaldm->release(finaldm);
-                       finaldm= tdm;
+                       finaldm = tdm;
                }
        }
 #endif /* WITH_GAMEENGINE */
@@ -1830,20 +1833,21 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        if (deformedVerts && deformedVerts != inputVertexCos)
                MEM_freeN(deformedVerts);
 
-       BLI_linklist_free((LinkNode*)datamasks, NULL);
+       BLI_linklist_free((LinkNode *)datamasks, NULL);
 }
 
 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
 {
-       int i, numVerts = *numVerts_r = em->bm->totvert;
-       float (*cos)[3];
        BMIter iter;
        BMVert *eve;
+       float (*cos)[3];
+       int i;
 
-       cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
+       *numVerts_r = em->bm->totvert;
 
-       eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
-       for (i=0; eve; eve=BM_iter_step(&iter), i++) {
+       cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
+
+       BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
                copy_v3_v3(cos[i], eve->co);
        }
 
@@ -1857,7 +1861,7 @@ int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *d
 
        if (!modifier_isEnabled(scene, md, required_mode)) return 0;
        if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
-               modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
+               modifier_setError(md, "Modifier requires original data, bad stack position");
                return 0;
        }
        
@@ -1865,8 +1869,8 @@ int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *d
 }
 
 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
-                                                                       DerivedMesh **final_r,
-                                                                       CustomDataMask dataMask)
+                                     DerivedMesh **final_r,
+                                     CustomDataMask dataMask)
 {
        ModifierData *md;
        float (*deformedVerts)[3] = NULL;
@@ -1891,7 +1895,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
        for (i = 0; md; i++, md = md->next, curr = curr->next) {
                ModifierTypeInfo *mti = modifierType_getInfo(md->type);
 
-               md->scene= scene;
+               md->scene = scene;
                
                if (!editbmesh_modifier_is_enabled(scene, md, dm))
                        continue;
@@ -1918,7 +1922,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                                         */
                                        numVerts = dm->getNumVerts(dm);
                                        deformedVerts =
-                                               MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
+                                           MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
                                        dm->getVertCos(dm, deformedVerts);
                                }
                                else {
@@ -1928,7 +1932,8 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
 
                        if (mti->deformVertsEM)
                                mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
-                       else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
+                       else
+                               mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
                }
                else {
                        DerivedMesh *ndm;
@@ -1951,7 +1956,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
 
                        }
                        else {
-                               dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
+                               dm = CDDM_from_editbmesh(em, FALSE, FALSE);
 
                                if (deformedVerts) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
@@ -1960,10 +1965,10 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                        }
 
                        /* create an orco derivedmesh in parallel */
-                       mask= curr->mask;
+                       mask = curr->mask;
                        if (mask & CD_MASK_ORCO) {
                                if (!orcodm)
-                                       orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
+                                       orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
 
                                mask &= ~CD_MASK_ORCO;
                                DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
@@ -1971,7 +1976,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                                if (mti->applyModifierEM)
                                        ndm = mti->applyModifierEM(md, ob, em, orcodm);
                                else
-                                       ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
+                                       ndm = mti->applyModifier(md, ob, orcodm, 0);
 
                                if (ndm) {
                                        /* if the modifier returned a new dm, release the old one */
@@ -1981,7 +1986,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                        }
 
                        /* set the DerivedMesh to only copy needed data */
-                       mask= curr->mask; /* CD_MASK_ORCO may have been cleared above */
+                       mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
 
                        DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
 
@@ -1995,7 +2000,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                        if (mti->applyModifierEM)
                                ndm = mti->applyModifierEM(md, ob, em, dm);
                        else
-                               ndm = mti->applyModifier(md, ob, dm, 0, 0);
+                               ndm = mti->applyModifier(md, ob, dm, 0);
 
                        if (ndm) {
                                if (dm && dm != ndm)
@@ -2020,13 +2025,13 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
                        }
                        else {
                                *cage_r =
-                                       getEditDerivedBMesh(em, ob,
-                                               deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
+                                   getEditDerivedBMesh(em, ob,
+                                                       deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
                        }
                }
        }
 
-       BLI_linklist_free((LinkNode*)datamasks, NULL);
+       BLI_linklist_free((LinkNode *)datamasks, NULL);
 
        /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
         * to apply these back onto the DerivedMesh. If we have no DerivedMesh
@@ -2042,12 +2047,18 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
        }
        else if (dm) {
                *final_r = dm;
-               (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
+
+               /* once we support skipping normal calculation with modifiers we may want to add this back */
+#if 0  // was added for bmesh but is not needed
+               (*final_r)->calcNormals(*final_r);
+#endif
        }
        else if (!deformedVerts && cage_r && *cage_r) {
                /* cage should already have up to date normals */
                *final_r = *cage_r;
-               (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
+#if 0  // was added for bmesh but is not needed
+               (*final_r)->calcNormals(*final_r);
+#endif
        }
        else {
                /* this is just a copy of the editmesh, no need to calc normals */
@@ -2063,7 +2074,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
        if ((*final_r)->type != DM_TYPE_EDITBMESH) {
                DM_ensure_tessface(*final_r);
        }
-       if (cage_r) {
+       if (cage_r && *cage_r) {
                if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
                        if (*cage_r != *final_r) {
                                DM_ensure_tessface(*cage_r);
@@ -2085,9 +2096,9 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D
 
 static void clear_mesh_caches(Object *ob)
 {
-       Mesh *me= ob->data;
+       Mesh *me = ob->data;
 
-               /* also serves as signal to remake texspace */
+       /* also serves as signal to remake texspace */
        if (ob->bb) {
                MEM_freeN(ob->bb);
                ob->bb = NULL;
@@ -2097,39 +2108,41 @@ static void clear_mesh_caches(Object *ob)
                me->bb = NULL;
        }
 
-       freedisplist(&ob->disp);
+       BKE_displist_free(&ob->disp);
 
        if (ob->derivedFinal) {
                ob->derivedFinal->needsFree = 1;
                ob->derivedFinal->release(ob->derivedFinal);
-               ob->derivedFinal= NULL;
+               ob->derivedFinal = NULL;
        }
        if (ob->derivedDeform) {
                ob->derivedDeform->needsFree = 1;
                ob->derivedDeform->release(ob->derivedDeform);
-               ob->derivedDeform= NULL;
+               ob->derivedDeform = NULL;
        }
 
        if (ob->sculpt) {
-               object_sculpt_modifiers_changed(ob);
+               BKE_object_sculpt_modifiers_changed(ob);
        }
 }
 
 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
                             int build_shapekey_layers)
 {
-       Object *obact = scene->basact?scene->basact->object:NULL;
+       Object *obact = scene->basact ? scene->basact->object : NULL;
        int editing = paint_facesel_test(ob);
        /* weight paint and face select need original indices because of selection buffer drawing */
-       int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
+       int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
+
+       BLI_assert(ob->type == OB_MESH);
 
        clear_mesh_caches(ob);
 
        mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
-                                               &ob->derivedFinal, 0, 1,
-                                               needMapping, dataMask, -1, 1, build_shapekey_layers);
+                           &ob->derivedFinal, 0, 1,
+                           needMapping, dataMask, -1, 1, build_shapekey_layers);
 
-       DM_set_object_boundbox (ob, ob->derivedFinal);
+       DM_set_object_boundbox(ob, ob->derivedFinal);
 
        ob->derivedFinal->needsFree = 0;
        ob->derivedDeform->needsFree = 0;
@@ -2138,7 +2151,7 @@ static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
        if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
                /* create PBVH immediately (would be created on the fly too,
                 * but this avoids waiting on first stroke) */
-               ob->sculpt->pbvh= ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
+               ob->sculpt->pbvh = ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
        }
 }
 
@@ -2147,7 +2160,7 @@ static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, C
        clear_mesh_caches(obedit);
 
        if (em->derivedFinal) {
-               if (em->derivedFinal!=em->derivedCage) {
+               if (em->derivedFinal != em->derivedCage) {
                        em->derivedFinal->needsFree = 1;
                        em->derivedFinal->release(em->derivedFinal);
                }
@@ -2160,7 +2173,7 @@ static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, C
        }
 
        editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
-       DM_set_object_boundbox (obedit, em->derivedFinal);
+       DM_set_object_boundbox(obedit, em->derivedFinal);
 
        em->lastDataMask = dataMask;
        em->derivedFinal->needsFree = 0;
@@ -2224,13 +2237,21 @@ DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask d
 {
        DerivedMesh *final;
 
+       /* XXX hack
+        * psys modifier updates particle state when called during dupli-list generation,
+        * which can lead to wrong transforms. This disables particle system modifier execution.
+        */
+       ob->transflag |= OB_NO_PSYS_UPDATE;
+
        mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
 
+       ob->transflag &= ~OB_NO_PSYS_UPDATE;
+
        return final;
 }
 
 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
-                                                                                  CustomDataMask dataMask)
+                                           CustomDataMask dataMask)
 {
        DerivedMesh *final;
        
@@ -2240,7 +2261,7 @@ DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*ver
 }
 
 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
-                                                                                       CustomDataMask dataMask)
+                                            CustomDataMask dataMask)
 {
        DerivedMesh *final;
        
@@ -2250,7 +2271,7 @@ DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*ve
 }
 
 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
-                                                                                       CustomDataMask dataMask)
+                                         CustomDataMask dataMask)
 {
        DerivedMesh *final;
        
@@ -2260,8 +2281,8 @@ DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertC
 }
 
 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
-                                                                                                 float (*vertCos)[3],
-                                                                                                 CustomDataMask dataMask)
+                                                  float (*vertCos)[3],
+                                                  CustomDataMask dataMask)
 {
        DerivedMesh *final;
 
@@ -2273,14 +2294,16 @@ DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
 /***/
 
 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
-                                                                                                CustomDataMask dataMask)
+                                                  CustomDataMask dataMask)
 {
        /* if there's no derived mesh or the last data mask used doesn't include
         * the data we need, rebuild the derived mesh
         */
        if (!em->derivedCage ||
-          (em->lastDataMask & dataMask) != dataMask)
+           (em->lastDataMask & dataMask) != dataMask)
+       {
                editbmesh_build_data(scene, obedit, em, dataMask);
+       }
 
        *final_r = em->derivedFinal;
        return em->derivedCage;
@@ -2292,8 +2315,10 @@ DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh
         * the data we need, rebuild the derived mesh
         */
        if (!em->derivedCage ||
-          (em->lastDataMask & dataMask) != dataMask)
+           (em->lastDataMask & dataMask) != dataMask)
+       {
                editbmesh_build_data(scene, obedit, em, dataMask);
+       }
 
        return em->derivedCage;
 }
@@ -2309,20 +2334,19 @@ DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
                                        const float no_f[3], const short no_s[3])
 {
-       float *vec = userData;
-       
-       vec+= 6*index;
+       DMCoNo *co_no = &((DMCoNo *)userData)[index];
 
        /* check if we've been here before (normal should not be 0) */
-       if (vec[3] || vec[4] || vec[5]) return;
+       if (!is_zero_v3(co_no->no)) {
+               return;
+       }
 
-       copy_v3_v3(vec, co);
-       vec+= 3;
+       copy_v3_v3(co_no->co, co);
        if (no_f) {
-               copy_v3_v3(vec, no_f);
+               copy_v3_v3(co_no->no, no_f);
        }
        else {
-               normal_short_to_float_v3(vec, no_s);
+               normal_short_to_float_v3(co_no->no, no_s);
        }
 }
 
@@ -2331,29 +2355,28 @@ static void make_vertexcosnos__mapFunc(void *userData, int index, const float co
 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
 /* in use now by vertex/weight paint and particle generating */
 
-float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
+DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
 {
-       Mesh *me= ob->data;
+       Mesh *me = ob->data;
        DerivedMesh *dm;
-       float *vertexcosnos;
+       DMCoNo *vertexcosnos;
        
        /* lets prevent crashing... */
-       if (ob->type!=OB_MESH || me->totvert==0)
+       if (ob->type != OB_MESH || me->totvert == 0)
                return NULL;
        
-       dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
-       vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
+       dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
        
        if (dm->foreachMappedVert) {
+               vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
                dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
        }
        else {
-               float *fp= vertexcosnos;
+               DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
                int a;
-               
-               for (a=0; a< me->totvert; a++, fp+=6) {
-                       dm->getVertCo(dm, a, fp);
-                       dm->getVertNo(dm, a, fp+3);
+               for (a = 0; a < me->totvert; a++, v_co_no++) {
+                       dm->getVertCo(dm, a, v_co_no->co);
+                       dm->getVertNo(dm, a, v_co_no->no);
                }
        }
        
@@ -2363,71 +2386,70 @@ float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
 
 /* ******************* GLSL ******************** */
 
-typedef struct
-{
-       float * precomputedFaceNormals;
-       MTFace * mtface;        // texture coordinates
-       MFace * mface;          // indices
-       MVert * mvert;          // vertices & normals
+typedef struct {
+       float *precomputedFaceNormals;
+       MTFace *mtface;     /* texture coordinates */
+       MFace *mface;       /* indices */
+       MVert *mvert;       /* vertices & normals */
        float (*orco)[3];
-       float (*tangent)[4];    // destination
+       float (*tangent)[4];    /* destination */
        int numTessFaces;
 
 } SGLSLMeshToTangent;
 
-// interface
+/* interface */
 #include "mikktspace.h"
 
-static int GetNumFaces(const SMikkTSpaceContext * pContext)
+static int GetNumFaces(const SMikkTSpaceContext *pContext)
 {
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
        return pMesh->numTessFaces;
 }
 
-static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
+static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
 {
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
-       return pMesh->mface[face_num].v4!=0 ? 4 : 3;
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
 }
 
-static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
+static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const int face_num, const int vert_index)
 {
-       //assert(vert_index>=0 && vert_index<4);
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
-       const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
+       //assert(vert_index >= 0 && vert_index < 4);
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
        copy_v3_v3(fPos, co);
 }
 
-static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
+static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[], const int face_num, const int vert_index)
 {
-       //assert(vert_index>=0 && vert_index<4);
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       //assert(vert_index >= 0 && vert_index < 4);
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
 
-       if (pMesh->mtface!=NULL) {
-               float * uv = pMesh->mtface[face_num].uv[vert_index];
-               fUV[0]=uv[0]; fUV[1]=uv[1];
+       if (pMesh->mtface != NULL) {
+               float *uv = pMesh->mtface[face_num].uv[vert_index];
+               fUV[0] = uv[0]; fUV[1] = uv[1];
        }
        else {
-               const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
-               map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
+               const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
+               map_to_sphere(&fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
        }
 }
 
-static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
+static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const int face_num, const int vert_index)
 {
-       //assert(vert_index>=0 && vert_index<4);
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       //assert(vert_index >= 0 && vert_index < 4);
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
 
        const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
-       if (!smoothnormal) {    // flat
+       if (!smoothnormal) {    // flat
                if (pMesh->precomputedFaceNormals) {
-                       copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
+                       copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3 * face_num]);
                }
                else {
-                       MFace *mf= &pMesh->mface[face_num];
-                       float *p0= pMesh->mvert[mf->v1].co;
-                       float *p1= pMesh->mvert[mf->v2].co;
-                       float *p2= pMesh->mvert[mf->v3].co;
+                       MFace *mf = &pMesh->mface[face_num];
+                       float *p0 = pMesh->mvert[mf->v1].co;
+                       float *p1 = pMesh->mvert[mf->v2].co;
+                       float *p2 = pMesh->mvert[mf->v3].co;
 
                        if (mf->v4) {
                                float *p3 = pMesh->mvert[mf->v4].co;
@@ -2439,32 +2461,28 @@ static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const
                }
        }
        else {
-               const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
+               const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
                normal_short_to_float_v3(fNorm, no);
        }
 }
-static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
+static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
 {
-       //assert(vert_index>=0 && vert_index<4);
-       SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
-       float * pRes = pMesh->tangent[4*face_num+iVert];
+       //assert(vert_index >= 0 && vert_index < 4);
+       SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
+       float *pRes = pMesh->tangent[4 * face_num + iVert];
        copy_v3_v3(pRes, fvTangent);
-       pRes[3]=fSign;
+       pRes[3] = fSign;
 }
 
 
 void DM_add_tangent_layer(DerivedMesh *dm)
 {
        /* mesh vars */
-       MTFace *mtface, *tf;
-       MFace *mface, *mf;
-       MVert *mvert, *v1, *v2, *v3, *v4;
-       MemArena *arena= NULL;
-       VertexTangent **vtangents= NULL;
-       float (*orco)[3]= NULL, (*tangent)[4];
-       float *uv1, *uv2, *uv3, *uv4, *vtang;
-       float fno[3], tang[3], uv[4][2];
-       int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
+       MVert *mvert;
+       MTFace *mtface;
+       MFace *mface;
+       float (*orco)[3] = NULL, (*tangent)[4];
+       int /* totvert, */ totface;
        float *nors;
 
        if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
@@ -2473,34 +2491,28 @@ void DM_add_tangent_layer(DerivedMesh *dm)
        nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
 
        /* check we have all the needed layers */
-       totvert= dm->getNumVerts(dm);
-       totface= dm->getNumTessFaces(dm);
+       /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
+       totface = dm->getNumTessFaces(dm);
 
-       mvert= dm->getVertArray(dm);
-       mface= dm->getTessFaceArray(dm);
-       mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
+       mvert = dm->getVertArray(dm);
+       mface = dm->getTessFaceArray(dm);
+       mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
 
        if (!mtface) {
-               orco= dm->getVertDataArray(dm, CD_ORCO);
+               orco = dm->getVertDataArray(dm, CD_ORCO);
                if (!orco)
                        return;
        }
        
        /* create tangent layer */
        DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
-       tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
+       tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
        
-       /* allocate some space */
-       arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
-       BLI_memarena_use_calloc(arena);
-       vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
-
-       // new computation method
-       iCalcNewMethod = 1;
-       if (iCalcNewMethod != 0) {
-               SGLSLMeshToTangent mesh2tangent= {0};
-               SMikkTSpaceContext sContext= {0};
-               SMikkTSpaceInterface sInterface= {0};
+       /* new computation method */
+       {
+               SGLSLMeshToTangent mesh2tangent = {0};
+               SMikkTSpaceContext sContext = {0};
+               SMikkTSpaceInterface sInterface = {0};
 
                mesh2tangent.precomputedFaceNormals = nors;
                mesh2tangent.mtface = mtface;
@@ -2519,129 +2531,55 @@ void DM_add_tangent_layer(DerivedMesh *dm)
                sInterface.m_getNormal = GetNormal;
                sInterface.m_setTSpaceBasic = SetTSpace;
 
-               // 0 if failed
-               iCalcNewMethod = genTangSpaceDefault(&sContext);
+               /* 0 if failed */
+               genTangSpaceDefault(&sContext);
        }
-
-       if (!iCalcNewMethod) {
-               /* sum tangents at connected vertices */
-               for (i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
-                       v1= &mvert[mf->v1];
-                       v2= &mvert[mf->v2];
-                       v3= &mvert[mf->v3];
-
-                       if (mf->v4) {
-                               v4= &mvert[mf->v4];
-                               normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
-                       }
-                       else {
-                               v4= NULL;
-                               normal_tri_v3( fno,v3->co, v2->co, v1->co);
-                       }
-               
-                       if (mtface) {
-                               uv1= tf->uv[0];
-                               uv2= tf->uv[1];
-                               uv3= tf->uv[2];
-                               uv4= tf->uv[3];
-                       }
-                       else {
-                               uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
-                               map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
-                               map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
-                               map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
-                               if (v4)
-                                       map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
-                       }
-               
-                       tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
-                       sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
-                       sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
-                       sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
-               
-                       if (mf->v4) {
-                               v4= &mvert[mf->v4];
-                       
-                               tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
-                               sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
-                               sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
-                               sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
-                       }
-               }
-       
-               /* write tangent to layer */
-               for (i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
-                       len= (mf->v4)? 4 : 3; 
-
-                       if (mtface == NULL) {
-                               map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
-                               map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
-                               map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
-                               if (len==4)
-                                       map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
-                       }
-               
-                       mf_vi[0]= mf->v1;
-                       mf_vi[1]= mf->v2;
-                       mf_vi[2]= mf->v3;
-                       mf_vi[3]= mf->v4;
-               
-                       for (j=0; j<len; j++) {
-                               vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
-                               normalize_v3_v3(tangent[j], vtang);
-                               ((float *) tangent[j])[3]=1.0f;
-                       }
-               }
-       }
-       
-       BLI_memarena_free(arena);
-       MEM_freeN(vtangents);
 }
 
 void DM_calc_auto_bump_scale(DerivedMesh *dm)
 {
-       /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
-       int totface= dm->getNumTessFaces(dm);
+       /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
+       int totface = dm->getNumTessFaces(dm);
 
-       MVert * mvert = dm->getVertArray(dm);
-       MFace * mface = dm->getTessFaceArray(dm);
-       MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
+       MVert *mvert = dm->getVertArray(dm);
+       MFace *mface = dm->getTessFaceArray(dm);
+       MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
 
        if (mtface) {
                double dsum = 0.0;
                int nr_accumulated = 0;
                int f;
 
-               for ( f=0; f < totface; f++ ) {
+               for (f = 0; f < totface; f++) {
                        {
-                               float * verts[4], * tex_coords[4];
-                               const int nr_verts = mface[f].v4!=0 ? 4 : 3;
+                               float *verts[4], *tex_coords[4];
+                               const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
                                int i, is_degenerate;
 
-                               verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
-                               tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
-                               if (nr_verts==4) {
-                                       verts[3]=mvert[mface[f].v4].co;
-                                       tex_coords[3]=mtface[f].uv[3];
+                               verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
+                               tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
+                               if (nr_verts == 4) {
+                                       verts[3] = mvert[mface[f].v4].co;
+                                       tex_coords[3] = mtface[f].uv[3];
                                }
 
-                               // discard degenerate faces
+                               /* discard degenerate faces */
                                is_degenerate = 0;
-                               if (    equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
-                                       equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
+                               if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
+                                   equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
                                {
                                        is_degenerate = 1;
                                }
 
-                               // verify last vertex as well if this is a quad
+                               /* verify last vertex as well if this is a quad */
                                if (is_degenerate == 0 && nr_verts == 4) {
                                        if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
-                                           equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
+                                           equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
                                        {
                                                is_degenerate = 1;
                                        }
 
-                                       // verify the winding is consistent
+                                       /* verify the winding is consistent */
                                        if (is_degenerate == 0) {
                                                float prev_edge[2];
                                                int is_signed = 0;
@@ -2650,10 +2588,10 @@ void DM_calc_auto_bump_scale(DerivedMesh *dm)
                                                i = 0;
                                                while (is_degenerate == 0 && i < 4) {
                                                        float cur_edge[2], signed_area;
-                                                       sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
-                                                       signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
+                                                       sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
+                                                       signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
 
-                                                       if (i == 0 ) {
+                                                       if (i == 0) {
                                                                is_signed = (signed_area < 0.0f) ? 1 : 0;
                                                        }
                                                        else if ((is_signed != 0) != (signed_area < 0.0f)) {
@@ -2662,17 +2600,17 @@ void DM_calc_auto_bump_scale(DerivedMesh *dm)
 
                                                        if (is_degenerate == 0) {
                                                                copy_v2_v2(prev_edge, cur_edge);
-                                                               ++i;
+                                                               i++;
                                                        }
                                                }
                                        }
                                }
 
-                               // proceed if not a degenerate face
+                               /* proceed if not a degenerate face */
                                if (is_degenerate == 0) {
-                                       int nr_tris_to_pile=0;
-                                       // quads split at shortest diagonal
-                                       int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
+                                       int nr_tris_to_pile = 0;
+                                       /* quads split at shortest diagonal */
+                                       int offs = 0;  /* initial triangulation is 0,1,2 and 0, 2, 3 */
                                        if (nr_verts == 4) {
                                                float pos_len_diag0, pos_len_diag1;
                                                float vtmp[3];
@@ -2681,10 +2619,10 @@ void DM_calc_auto_bump_scale(DerivedMesh *dm)
                                                sub_v3_v3v3(vtmp, verts[3], verts[1]);
                                                pos_len_diag1 = dot_v3v3(vtmp, vtmp);
 
-                                               if (pos_len_diag1<pos_len_diag0) {
-                                                       offs=1;         // alter split
+                                               if (pos_len_diag1 < pos_len_diag0) {
+                                                       offs = 1;     // alter split
                                                }
-                                               else if (pos_len_diag0==pos_len_diag1) { /* do UV check instead */
+                                               else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
                                                        float tex_len_diag0, tex_len_diag1;
 
                                                        sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
@@ -2692,37 +2630,36 @@ void DM_calc_auto_bump_scale(DerivedMesh *dm)
                                                        sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
                                                        tex_len_diag1 = dot_v2v2(vtmp, vtmp);
 
-                                                       if (tex_len_diag1<tex_len_diag0) {
-                                                               offs=1; /* alter split */
+                                                       if (tex_len_diag1 < tex_len_diag0) {
+                                                               offs = 1; /* alter split */
                                                        }
                                                }
                                        }
                                        nr_tris_to_pile = nr_verts - 2;
-                                       if (nr_tris_to_pile==1 || nr_tris_to_pile==2) {
-                                               const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
+                                       if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
+                                               const int indices[] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
                                                int t;
-                                               for ( t=0; t<nr_tris_to_pile; t++ )
-                                               {
+                                               for (t = 0; t < nr_tris_to_pile; t++) {
                                                        float f2x_area_uv;
-                                                       float * p0 = verts[indices[t*3+0]];
-                                                       float * p1 = verts[indices[t*3+1]];
-                                                       float * p2 = verts[indices[t*3+2]];
+                                                       float *p0 = verts[indices[t * 3 + 0]];
+                                                       float *p1 = verts[indices[t * 3 + 1]];
+                                                       float *p2 = verts[indices[t * 3 + 2]];
 
                                                        float edge_t0[2], edge_t1[2];
-                                                       sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
-                                                       sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
+                                                       sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
+                                                       sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
 
-                                                       f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
-                                                       if (f2x_area_uv>FLT_EPSILON) {
+                                                       f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
+                                                       if (f2x_area_uv > FLT_EPSILON) {
                                                                float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
                                                                sub_v3_v3v3(v0, p1, p0);
                                                                sub_v3_v3v3(v1, p2, p0);
                                                                cross_v3_v3v3(norm, v0, v1);
 
                                                                f2x_surf_area = len_v3(norm);
-                                                               fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
+                                                               fsurf_ratio = f2x_surf_area / f2x_area_uv;    // tri area divided by texture area
 
-                                                               ++nr_accumulated;
+                                                               nr_accumulated++;
                                                                dsum += (double)(fsurf_ratio);
                                                        }
                                                }
@@ -2731,10 +2668,10 @@ void DM_calc_auto_bump_scale(DerivedMesh *dm)
                        }
                }
 
-               // finalize
+               /* finalize */
                {
-                       const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
-                       const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
+                       const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
+                       const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
                        dm->auto_bump_scale = use_as_render_bump_scale;
                }
        }
@@ -2775,7 +2712,7 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
 
                                if (gattribs->layer[b].name[0])
                                        layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
-                                               gattribs->layer[b].name);
+                                                                                gattribs->layer[b].name);
                                else
                                        layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
 
@@ -2783,15 +2720,15 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                        a = attribs->tottface++;
 
                                        attribs->tface[a].array = tfdata->layers[layer].data;
-                                       attribs->tface[a].emOffset = tfdata->layers[layer].offset;
-                                       attribs->tface[a].glIndex = gattribs->layer[b].glindex;
-                                       attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
+                                       attribs->tface[a].em_offset = tfdata->layers[layer].offset;
+                                       attribs->tface[a].gl_index = gattribs->layer[b].glindex;
+                                       attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
                                }
                        }
                        else {
                                if (gattribs->layer[b].name[0])
                                        layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
-                                               gattribs->layer[b].name);
+                                                                                gattribs->layer[b].name);
                                else
                                        layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
 
@@ -2799,9 +2736,9 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                        a = attribs->tottface++;
 
                                        attribs->tface[a].array = tfdata->layers[layer].data;
-                                       attribs->tface[a].emOffset = tfdata->layers[layer].offset;
-                                       attribs->tface[a].glIndex = gattribs->layer[b].glindex;
-                                       attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
+                                       attribs->tface[a].em_offset = tfdata->layers[layer].offset;
+                                       attribs->tface[a].gl_index = gattribs->layer[b].glindex;
+                                       attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
                                }
                        }
                }
@@ -2812,7 +2749,7 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
 
                                if (gattribs->layer[b].name[0])
                                        layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
-                                               gattribs->layer[b].name);
+                                                                                gattribs->layer[b].name);
                                else
                                        layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
 
@@ -2820,15 +2757,15 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                        a = attribs->totmcol++;
 
                                        attribs->mcol[a].array = tfdata->layers[layer].data;
-                                       attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
-                                       attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
+                                       attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
+                                       attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
                                }
                        }
                        else {
                                /* vertex colors */
                                if (gattribs->layer[b].name[0])
                                        layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
-                                               gattribs->layer[b].name);
+                                                                                gattribs->layer[b].name);
                                else
                                        layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
 
@@ -2836,8 +2773,8 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                        a = attribs->totmcol++;
 
                                        attribs->mcol[a].array = tfdata->layers[layer].data;
-                                       attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
-                                       attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
+                                       attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
+                                       attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
                                }
                        }
                }
@@ -2849,8 +2786,8 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                attribs->tottang = 1;
 
                                attribs->tang.array = fdata->layers[layer].data;
-                               attribs->tang.emOffset = fdata->layers[layer].offset;
-                               attribs->tang.glIndex = gattribs->layer[b].glindex;
+                               attribs->tang.em_offset = fdata->layers[layer].offset;
+                               attribs->tang.gl_index = gattribs->layer[b].glindex;
                        }
                }
                else if (gattribs->layer[b].type == CD_ORCO) {
@@ -2861,9 +2798,9 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                attribs->totorco = 1;
 
                                attribs->orco.array = vdata->layers[layer].data;
-                               attribs->orco.emOffset = vdata->layers[layer].offset;
-                               attribs->orco.glIndex = gattribs->layer[b].glindex;
-                               attribs->orco.glTexco = gattribs->layer[b].gltexco;
+                               attribs->orco.em_offset = vdata->layers[layer].offset;
+                               attribs->orco.gl_index = gattribs->layer[b].glindex;
+                               attribs->orco.gl_texco = gattribs->layer[b].gltexco;
                        }
                }
        }
@@ -2879,9 +2816,9 @@ void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
        dm->getMinMax(dm, min, max);
 
        if (!ob->bb)
-               ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
+               ob->bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
 
-       boundbox_set_from_min_max(ob->bb, min, max);
+       BKE_boundbox_init_from_minmax(ob->bb, min, max);
 }
 
 /* --- NAVMESH (begin) --- */
@@ -2903,12 +2840,12 @@ BLI_INLINE int navmesh_bit(int a, int b)
 
 BLI_INLINE void navmesh_intToCol(int i, float col[3])
 {
-       int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
-       int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
-       int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
-       col[0] = 1 - r*63.0f/255.0f;
-       col[1] = 1 - g*63.0f/255.0f;
-       col[2] = 1 - b*63.0f/255.0f;
+       int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
+       int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
+       int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
+       col[0] = 1 - r * 63.0f / 255.0f;
+       col[1] = 1 - g * 63.0f / 255.0f;
+       col[2] = 1 - b * 63.0f / 255.0f;
 }
 
 static void navmesh_drawColored(DerivedMesh *dm)
@@ -2932,12 +2869,12 @@ static void navmesh_drawColored(DerivedMesh *dm)
 #endif
 
        glDisable(GL_LIGHTING);
-       /*  if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
-               DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
+       /* if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
+               DEBUG_VBO("Using legacy code. drawNavMeshColored\n");
                //glShadeModel(GL_SMOOTH);
                glBegin(glmode = GL_QUADS);
                for (a = 0; a < dm->numTessFaceData; a++, mface++) {
-                       int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
+                       int new_glmode = mface->v4 ? GL_QUADS : GL_TRIANGLES;
                        int pi = polygonIdx[a];
                        if (pi <= 0) {
                                zero_v3(col);
@@ -2964,9 +2901,9 @@ static void navmesh_drawColored(DerivedMesh *dm)
 }
 
 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
-                       DMSetDrawOptionsTex setDrawOptions,
-                       DMCompareDrawOptions compareDrawOptions,
-                       void *userData)
+                                    DMSetDrawOptionsTex setDrawOptions,
+                                    DMCompareDrawOptions compareDrawOptions,
+                                    void *userData)
 {
        (void) setDrawOptions;
        (void) compareDrawOptions;
@@ -2991,21 +2928,21 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
        DerivedMesh *result;
        int maxFaces = dm->getNumPolys(dm);
        int *recastData;
-       int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
-       float* verts=NULL;
-       unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
-       int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
+       int vertsPerPoly = 0, nverts = 0, ndtris = 0, npolys = 0;
+       float *verts = NULL;
+       unsigned short *dtris = NULL, *dmeshes = NULL, *polys = NULL;
+       int *dtrisToPolysMap = NULL, *dtrisToTrisMap = NULL, *trisToFacesMap = NULL;
        int res;
 
        result = CDDM_copy(dm);
        if (!CustomData_has_layer(&result->polyData, CD_RECAST)) {
-               int *sourceRecastData = (int*)CustomData_get_layer(&dm->polyData, CD_RECAST);
+               int *sourceRecastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
                if (sourceRecastData) {
                        CustomData_add_layer_named(&result->polyData, CD_RECAST, CD_DUPLICATE,
                                                   sourceRecastData, maxFaces, "recastData");
                }
        }
-       recastData = (int*)CustomData_get_layer(&result->polyData, CD_RECAST);
+       recastData = (int *)CustomData_get_layer(&result->polyData, CD_RECAST);
 
        /* note: This is not good design! - really should not be doing this */
        result->drawFacesTex =  navmesh_DM_drawFacesTex;
@@ -3020,17 +2957,17 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
                size_t polyIdx;
 
                /* invalidate concave polygon */
-               for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
-                       unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
+               for (polyIdx = 0; polyIdx < (size_t)npolys; polyIdx++) {
+                       unsigned short *poly = &polys[polyIdx * 2 * vertsPerPoly];
                        if (!polyIsConvex(poly, vertsPerPoly, verts)) {
                                /* set negative polygon idx to all faces */
-                               unsigned short *dmesh = &dmeshes[4*polyIdx];
+                               unsigned short *dmesh = &dmeshes[4 * polyIdx];
                                unsigned short tbase = dmesh[2];
                                unsigned short tnum = dmesh[3];
                                unsigned short ti;
 
-                               for (ti=0; ti<tnum; ti++) {
-                                       unsigned short triidx = dtrisToTrisMap[tbase+ti];
+                               for (ti = 0; ti < tnum; ti++) {
+                                       unsigned short triidx = dtrisToTrisMap[tbase + ti];
                                        unsigned short faceidx = trisToFacesMap[triidx];
                                        if (recastData[faceidx] > 0) {
                                                recastData[faceidx] = -recastData[faceidx];
@@ -3044,19 +2981,19 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
        }
 
        /* clean up */
-       if (verts!=NULL)
+       if (verts != NULL)
                MEM_freeN(verts);
-       if (dtris!=NULL)
+       if (dtris != NULL)
                MEM_freeN(dtris);
-       if (dmeshes!=NULL)
+       if (dmeshes != NULL)
                MEM_freeN(dmeshes);
-       if (polys!=NULL)
+       if (polys != NULL)
                MEM_freeN(polys);
-       if (dtrisToPolysMap!=NULL)
+       if (dtrisToPolysMap != NULL)
                MEM_freeN(dtrisToPolysMap);
-       if (dtrisToTrisMap!=NULL)
+       if (dtrisToTrisMap != NULL)
                MEM_freeN(dtrisToTrisMap);
-       if (trisToFacesMap!=NULL)
+       if (trisToFacesMap != NULL)
                MEM_freeN(trisToFacesMap);
 
        return result;
@@ -3114,14 +3051,14 @@ static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getEle
                        CustomData_file_write_info(type, &structname, &structnum);
                        BLI_dynstr_appendf(dynstr,
                                           "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
-                                                          name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
+                                          name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
                }
        }
 }
 
 char *DM_debug_info(DerivedMesh *dm)
 {
-       DynStr *dynstr= BLI_dynstr_new();
+       DynStr *dynstr = BLI_dynstr_new();
        char *ret;
        const char *tstr;
 
@@ -3175,4 +3112,25 @@ void DM_debug_print(DerivedMesh *dm)
        MEM_freeN(str);
 }
 
+void DM_debug_print_cdlayers(CustomData *data)
+{
+       int i;
+       CustomDataLayer *layer;
+
+       printf("{\n");
+
+       for (i = 0, layer = data->layers; i < data->totlayer; i++, layer++) {
+
+               const char *name = CustomData_layertype_name(layer->type);
+               const int size = CustomData_sizeof(layer->type);
+               const char *structname;
+               int structnum;
+               CustomData_file_write_info(layer->type, &structname, &structnum);
+               printf("        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
+                      name, structname, layer->type, (void *)layer->data, size, (int)(MEM_allocN_len(layer->data) / size));
+       }
+
+       printf("}\n");
+}
+
 #endif /* NDEBUG */