move modifier callback wrappers into modifier.c
[blender-staging.git] / source / blender / blenkernel / intern / DerivedMesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/DerivedMesh.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <limits.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_cloth_types.h"
39 #include "DNA_key_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h" // N_T
45
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_memarena.h"
49 #include "BLI_array.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_linklist.h"
52
53 #include "BKE_pbvh.h"
54 #include "BKE_cdderivedmesh.h"
55 #include "BKE_displist.h"
56 #include "BKE_editmesh.h"
57 #include "BKE_key.h"
58 #include "BKE_modifier.h"
59 #include "BKE_mesh.h"
60 #include "BKE_object.h"
61 #include "BKE_object_deform.h"
62 #include "BKE_paint.h"
63 #include "BKE_texture.h"
64 #include "BKE_multires.h"
65 #include "BKE_armature.h"
66 #include "BKE_particle.h"
67 #include "BKE_editmesh.h"
68 #include "BKE_bvhutils.h"
69 #include "BKE_deform.h"
70 #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */
71
72 #ifdef WITH_GAMEENGINE
73 #include "BKE_navmesh_conversion.h"
74 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
75 #endif
76
77 #include "BLI_sys_types.h" /* for intptr_t support */
78
79 #include "GL/glew.h"
80
81 #include "GPU_buffers.h"
82 #include "GPU_draw.h"
83 #include "GPU_extensions.h"
84 #include "GPU_material.h"
85
86 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
87 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
88
89 ///////////////////////////////////
90 ///////////////////////////////////
91
92 static MVert *dm_getVertArray(DerivedMesh *dm)
93 {
94         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
95
96         if (!mvert) {
97                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
98                                              dm->getNumVerts(dm));
99                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
100                 dm->copyVertArray(dm, mvert);
101         }
102
103         return mvert;
104 }
105
106 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
107 {
108         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
109
110         if (!medge) {
111                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
112                                              dm->getNumEdges(dm));
113                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
114                 dm->copyEdgeArray(dm, medge);
115         }
116
117         return medge;
118 }
119
120 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
121 {
122         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
123
124         if (!mface) {
125                 int numTessFaces = dm->getNumTessFaces(dm);
126                 
127                 if (!numTessFaces) {
128                         /* Do not add layer if there's no elements in it, this leads to issues later when
129                          * this layer is needed with non-zero size, but currently CD stuff does not check
130                          * for requested layer size on creation and just returns layer which was previously
131                          * added (sergey) */
132                         return NULL;
133                 }
134                 
135                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
136                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
137                 dm->copyTessFaceArray(dm, mface);
138         }
139
140         return mface;
141 }
142
143 static MLoop *dm_getLoopArray(DerivedMesh *dm)
144 {
145         MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
146
147         if (!mloop) {
148                 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
149                                              dm->getNumLoops(dm));
150                 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
151                 dm->copyLoopArray(dm, mloop);
152         }
153
154         return mloop;
155 }
156
157 static MPoly *dm_getPolyArray(DerivedMesh *dm)
158 {
159         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
160
161         if (!mpoly) {
162                 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
163                                              dm->getNumPolys(dm));
164                 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
165                 dm->copyPolyArray(dm, mpoly);
166         }
167
168         return mpoly;
169 }
170
171 static MVert *dm_dupVertArray(DerivedMesh *dm)
172 {
173         MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm),
174                                  "dm_dupVertArray tmp");
175
176         if (tmp) dm->copyVertArray(dm, tmp);
177
178         return tmp;
179 }
180
181 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
182 {
183         MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm),
184                                  "dm_dupEdgeArray tmp");
185
186         if (tmp) dm->copyEdgeArray(dm, tmp);
187
188         return tmp;
189 }
190
191 static MFace *dm_dupFaceArray(DerivedMesh *dm)
192 {
193         MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
194                                  "dm_dupFaceArray tmp");
195
196         if (tmp) dm->copyTessFaceArray(dm, tmp);
197
198         return tmp;
199 }
200
201 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
202 {
203         MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm),
204                                  "dm_dupLoopArray tmp");
205
206         if (tmp) dm->copyLoopArray(dm, tmp);
207
208         return tmp;
209 }
210
211 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
212 {
213         MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm),
214                                  "dm_dupPolyArray tmp");
215
216         if (tmp) dm->copyPolyArray(dm, tmp);
217
218         return tmp;
219 }
220
221 static CustomData *dm_getVertCData(DerivedMesh *dm)
222 {
223         return &dm->vertData;
224 }
225
226 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
227 {
228         return &dm->edgeData;
229 }
230
231 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
232 {
233         return &dm->faceData;
234 }
235
236 static CustomData *dm_getLoopCData(DerivedMesh *dm)
237 {
238         return &dm->loopData;
239 }
240
241 static CustomData *dm_getPolyCData(DerivedMesh *dm)
242 {
243         return &dm->polyData;
244 }
245
246 void DM_init_funcs(DerivedMesh *dm)
247 {
248         /* default function implementations */
249         dm->getVertArray = dm_getVertArray;
250         dm->getEdgeArray = dm_getEdgeArray;
251         dm->getTessFaceArray = dm_getTessFaceArray;
252         dm->getLoopArray = dm_getLoopArray;
253         dm->getPolyArray = dm_getPolyArray;
254         dm->dupVertArray = dm_dupVertArray;
255         dm->dupEdgeArray = dm_dupEdgeArray;
256         dm->dupTessFaceArray = dm_dupFaceArray;
257         dm->dupLoopArray = dm_dupLoopArray;
258         dm->dupPolyArray = dm_dupPolyArray;
259
260         dm->getVertDataLayout = dm_getVertCData;
261         dm->getEdgeDataLayout = dm_getEdgeCData;
262         dm->getTessFaceDataLayout = dm_getTessFaceCData;
263         dm->getLoopDataLayout = dm_getLoopCData;
264         dm->getPolyDataLayout = dm_getPolyCData;
265
266         dm->getVertData = DM_get_vert_data;
267         dm->getEdgeData = DM_get_edge_data;
268         dm->getTessFaceData = DM_get_tessface_data;
269         dm->getPolyData = DM_get_poly_data;
270         dm->getVertDataArray = DM_get_vert_data_layer;
271         dm->getEdgeDataArray = DM_get_edge_data_layer;
272         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
273         dm->getPolyDataArray = DM_get_poly_data_layer;
274         dm->getLoopDataArray = DM_get_loop_data_layer;
275
276         bvhcache_init(&dm->bvhCache);
277 }
278
279 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
280              int numTessFaces, int numLoops, int numPolys)
281 {
282         dm->type = type;
283         dm->numVertData = numVerts;
284         dm->numEdgeData = numEdges;
285         dm->numTessFaceData = numTessFaces;
286         dm->numLoopData = numLoops;
287         dm->numPolyData = numPolys;
288
289         DM_init_funcs(dm);
290         
291         dm->needsFree = 1;
292         dm->auto_bump_scale = -1.0f;
293         dm->dirty = 0;
294
295         /* don't use CustomData_reset(...); because we dont want to touch customdata */
296         fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
297         fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
298         fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
299         fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
300         fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
301 }
302
303 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
304                       int numVerts, int numEdges, int numTessFaces,
305                       int numLoops, int numPolys)
306 {
307         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
308                         CD_CALLOC, numVerts);
309         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
310                         CD_CALLOC, numEdges);
311         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
312                         CD_CALLOC, numTessFaces);
313         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
314                         CD_CALLOC, numLoops);
315         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
316                         CD_CALLOC, numPolys);
317
318         dm->cd_flag = source->cd_flag;
319
320         dm->type = type;
321         dm->numVertData = numVerts;
322         dm->numEdgeData = numEdges;
323         dm->numTessFaceData = numTessFaces;
324         dm->numLoopData = numLoops;
325         dm->numPolyData = numPolys;
326
327         DM_init_funcs(dm);
328
329         dm->needsFree = 1;
330         dm->dirty = 0;
331 }
332
333 int DM_release(DerivedMesh *dm)
334 {
335         if (dm->needsFree) {
336                 bvhcache_free(&dm->bvhCache);
337                 GPU_drawobject_free(dm);
338                 CustomData_free(&dm->vertData, dm->numVertData);
339                 CustomData_free(&dm->edgeData, dm->numEdgeData);
340                 CustomData_free(&dm->faceData, dm->numTessFaceData);
341                 CustomData_free(&dm->loopData, dm->numLoopData);
342                 CustomData_free(&dm->polyData, dm->numPolyData);
343
344                 return 1;
345         }
346         else {
347                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
348                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
349                 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
350                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
351                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
352
353                 return 0;
354         }
355 }
356
357 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
358 {
359         CustomData_free(&target->loopData, source->numLoopData);
360         CustomData_free(&target->polyData, source->numPolyData);
361
362         CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
363         CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
364
365         target->numLoopData = source->numLoopData;
366         target->numPolyData = source->numPolyData;
367
368         if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
369                 MPoly *mpoly;
370                 MLoop *mloop;
371
372                 mloop = source->dupLoopArray(source);
373                 mpoly = source->dupPolyArray(source);
374                 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
375                 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
376         }
377 }
378
379 void DM_ensure_normals(DerivedMesh *dm)
380 {
381         if (dm->dirty & DM_DIRTY_NORMALS) {
382                 dm->calcNormals(dm);
383         }
384         BLI_assert((dm->dirty & DM_DIRTY_NORMALS) == 0);
385 }
386
387 /* note: until all modifiers can take MPoly's as input,
388  * use this at the start of modifiers  */
389 void DM_ensure_tessface(DerivedMesh *dm)
390 {
391         const int numTessFaces = dm->getNumTessFaces(dm);
392         const int numPolys =     dm->getNumPolys(dm);
393
394         if ((numTessFaces == 0) && (numPolys != 0)) {
395                 dm->recalcTessellation(dm);
396
397                 if (dm->getNumTessFaces(dm) != 0) {
398                         /* printf("info %s: polys -> ngons calculated\n", __func__); */
399                 }
400                 else {
401                         printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
402                                __func__, numPolys, dm->type);
403                 }
404         }
405
406         else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
407                 BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX) || numTessFaces == 0);
408                 DM_update_tessface_data(dm);
409         }
410
411         dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
412 }
413
414 /* Update tessface CD data from loop/poly ones. Needed when not retessellating after modstack evaluation. */
415 /* NOTE: Assumes dm has valid tessellated data! */
416 void DM_update_tessface_data(DerivedMesh *dm)
417 {
418         MFace *mf = dm->getTessFaceArray(dm);
419         MPoly *mp = dm->getPolyArray(dm);
420         MLoop *ml = dm->getLoopArray(dm);
421
422         CustomData *fdata = dm->getTessFaceDataLayout(dm);
423         CustomData *pdata = dm->getPolyDataLayout(dm);
424         CustomData *ldata = dm->getLoopDataLayout(dm);
425
426         const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY);
427         const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL);
428         const int hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
429         const int hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
430
431         int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
432
433         int mf_idx,
434             totface = dm->getNumTessFaces(dm),
435             ml_idx[4];
436
437         /* Should never occure, but better abort than segfault! */
438         if (!polyindex)
439                 return;
440
441         CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
442
443         for (mf_idx = 0; mf_idx < totface; mf_idx++, mf++) {
444                 const int mf_len = mf->v4 ? 4 : 3;
445                 int i, not_done;
446
447                 /* Find out loop indices. */
448                 /* XXX Is there a better way to do this? */
449                 /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
450                 for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
451                         MLoop *tml = &ml[i];
452                         if (tml->v == mf->v1) {
453                                 ml_idx[0] = i;
454                                 not_done--;
455                         }
456                         else if (tml->v == mf->v2) {
457                                 ml_idx[1] = i;
458                                 not_done--;
459                         }
460                         else if (tml->v == mf->v3) {
461                                 ml_idx[2] = i;
462                                 not_done--;
463                         }
464                         else if (mf_len == 4 && tml->v == mf->v4) {
465                                 ml_idx[3] = i;
466                                 not_done--;
467                         }
468                 }
469                 BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata,
470                                                 ml_idx, mf_idx, polyindex[mf_idx],
471                                                 mf_len,
472                                                 numTex, numCol, hasPCol, hasOrigSpace);
473         }
474
475         if (G.debug & G_DEBUG)
476                 printf("%s: Updated tessellated customdata of dm %p\n", __func__, dm);
477
478         dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
479 }
480
481 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask)
482 {
483         /* dm might depend on me, so we need to do everything with a local copy */
484         Mesh tmp = *me;
485         int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
486         int did_shapekeys = 0;
487         float *texloc, *texrot, *texsize;
488         short *texflag;
489         
490         CustomData_reset(&tmp.vdata);
491         CustomData_reset(&tmp.edata);
492         CustomData_reset(&tmp.fdata);
493         CustomData_reset(&tmp.ldata);
494         CustomData_reset(&tmp.pdata);
495
496         DM_ensure_normals(dm);
497
498         totvert = tmp.totvert = dm->getNumVerts(dm);
499         totedge = tmp.totedge = dm->getNumEdges(dm);
500         totloop = tmp.totloop = dm->getNumLoops(dm);
501         totpoly = tmp.totpoly = dm->getNumPolys(dm);
502         tmp.totface = 0;
503
504         CustomData_copy(&dm->vertData, &tmp.vdata, mask, CD_DUPLICATE, totvert);
505         CustomData_copy(&dm->edgeData, &tmp.edata, mask, CD_DUPLICATE, totedge);
506         CustomData_copy(&dm->loopData, &tmp.ldata, mask, CD_DUPLICATE, totloop);
507         CustomData_copy(&dm->polyData, &tmp.pdata, mask, CD_DUPLICATE, totpoly);
508         tmp.cd_flag = dm->cd_flag;
509
510         if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
511                 KeyBlock *kb;
512                 int uid;
513                 
514                 if (ob) {
515                         kb = BLI_findlink(&me->key->block, ob->shapenr - 1);
516                         if (kb) {
517                                 uid = kb->uid;
518                         }
519                         else {
520                                 printf("%s: error - could not find active shapekey %d!\n",
521                                        __func__, ob->shapenr - 1);
522
523                                 uid = INT_MAX;
524                         }
525                 }
526                 else {
527                         /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
528                         uid = INT_MAX;
529                 }
530
531                 shapekey_layers_to_keyblocks(dm, me, uid);
532                 did_shapekeys = 1;
533         }
534
535         /* copy texture space */
536         if (BKE_object_obdata_texspace_get(ob, &texflag, &texloc, &texsize, &texrot)) {
537                 tmp.texflag = *texflag;
538                 copy_v3_v3(tmp.loc, texloc);
539                 copy_v3_v3(tmp.size, texsize);
540                 copy_v3_v3(tmp.rot, texrot);
541         }
542         
543         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
544          * we set them here in case they are missing */
545         if (!CustomData_has_layer(&tmp.vdata, CD_MVERT))
546                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
547         if (!CustomData_has_layer(&tmp.edata, CD_MEDGE))
548                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
549         if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
550                 tmp.mloop = dm->dupLoopArray(dm);
551                 tmp.mpoly = dm->dupPolyArray(dm);
552
553                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
554                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
555         }
556
557         /* object had got displacement layer, should copy this layer to save sculpted data */
558         /* NOTE: maybe some other layers should be copied? nazgul */
559         if (CustomData_has_layer(&me->ldata, CD_MDISPS)) {
560                 if (totloop == me->totloop) {
561                         MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
562                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
563                 }
564         }
565
566         /* yes, must be before _and_ after tessellate */
567         BKE_mesh_update_customdata_pointers(&tmp, false);
568
569         /* since 2.65 caller must do! */
570         // BKE_mesh_tessface_calc(&tmp);
571
572         CustomData_free(&me->vdata, me->totvert);
573         CustomData_free(&me->edata, me->totedge);
574         CustomData_free(&me->fdata, me->totface);
575         CustomData_free(&me->ldata, me->totloop);
576         CustomData_free(&me->pdata, me->totpoly);
577
578         /* ok, this should now use new CD shapekey data,
579          * which should be fed through the modifier
580          * stack*/
581         if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
582                 printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
583                 if (tmp.key) tmp.key->id.us--;
584                 tmp.key = NULL;
585         }
586
587         /* Clear selection history */
588         tmp.mselect = NULL;
589         tmp.totselect = 0;
590         if (me->mselect) {
591                 MEM_freeN(me->mselect);
592         }
593
594         *me = tmp;
595 }
596
597 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
598 {
599         int a, totvert = dm->getNumVerts(dm);
600         float *fp;
601         MVert *mvert;
602         
603         if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) return;
604         
605         if (kb->data) MEM_freeN(kb->data);
606         kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data");
607         kb->totelem = totvert;
608         
609         fp = kb->data;
610         mvert = dm->getVertDataArray(dm, CD_MVERT);
611         
612         for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
613                 copy_v3_v3(fp, mvert->co);
614         }
615 }
616
617 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
618 {
619         CustomData_set_only_copy(&dm->vertData, mask);
620         CustomData_set_only_copy(&dm->edgeData, mask);
621         CustomData_set_only_copy(&dm->faceData, mask);
622         /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
623          * weight paint mode when there are modifiers applied, needs further investigation,
624          * see replies to r50969, Campbell */
625 #if 0
626         CustomData_set_only_copy(&dm->loopData, mask);
627         CustomData_set_only_copy(&dm->polyData, mask);
628 #endif
629 }
630
631 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
632 {
633         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
634 }
635
636 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
637 {
638         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
639 }
640
641 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
642 {
643         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
644 }
645
646 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
647 {
648         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
649 }
650
651 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
652 {
653         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
654 }
655
656 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
657 {
658         return CustomData_get(&dm->vertData, index, type);
659 }
660
661 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
662 {
663         return CustomData_get(&dm->edgeData, index, type);
664 }
665
666 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
667 {
668         return CustomData_get(&dm->faceData, index, type);
669 }
670
671 void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
672 {
673         return CustomData_get(&dm->polyData, index, type);
674 }
675
676
677 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
678 {
679         if (type == CD_MVERT)
680                 return dm->getVertArray(dm);
681
682         return CustomData_get_layer(&dm->vertData, type);
683 }
684
685 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
686 {
687         if (type == CD_MEDGE)
688                 return dm->getEdgeArray(dm);
689
690         return CustomData_get_layer(&dm->edgeData, type);
691 }
692
693 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
694 {
695         if (type == CD_MFACE)
696                 return dm->getTessFaceArray(dm);
697
698         return CustomData_get_layer(&dm->faceData, type);
699 }
700
701 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
702 {
703         return CustomData_get_layer(&dm->polyData, type);
704 }
705
706 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
707 {
708         return CustomData_get_layer(&dm->loopData, type);
709 }
710
711 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
712 {
713         CustomData_set(&dm->vertData, index, type, data);
714 }
715
716 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
717 {
718         CustomData_set(&dm->edgeData, index, type, data);
719 }
720
721 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
722 {
723         CustomData_set(&dm->faceData, index, type, data);
724 }
725
726 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
727                        int source_index, int dest_index, int count)
728 {
729         CustomData_copy_data(&source->vertData, &dest->vertData,
730                              source_index, dest_index, count);
731 }
732
733 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
734                        int source_index, int dest_index, int count)
735 {
736         CustomData_copy_data(&source->edgeData, &dest->edgeData,
737                              source_index, dest_index, count);
738 }
739
740 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
741                            int source_index, int dest_index, int count)
742 {
743         CustomData_copy_data(&source->faceData, &dest->faceData,
744                              source_index, dest_index, count);
745 }
746
747 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
748                        int source_index, int dest_index, int count)
749 {
750         CustomData_copy_data(&source->loopData, &dest->loopData,
751                              source_index, dest_index, count);
752 }
753
754 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
755                        int source_index, int dest_index, int count)
756 {
757         CustomData_copy_data(&source->polyData, &dest->polyData,
758                              source_index, dest_index, count);
759 }
760
761 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
762 {
763         CustomData_free_elem(&dm->vertData, index, count);
764 }
765
766 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
767 {
768         CustomData_free_elem(&dm->edgeData, index, count);
769 }
770
771 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
772 {
773         CustomData_free_elem(&dm->faceData, index, count);
774 }
775
776 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
777 {
778         CustomData_free_elem(&dm->loopData, index, count);
779 }
780
781 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
782 {
783         CustomData_free_elem(&dm->polyData, index, count);
784 }
785
786 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
787                          int *src_indices, float *weights,
788                          int count, int dest_index)
789 {
790         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
791                           weights, NULL, count, dest_index);
792 }
793
794 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
795                          int *src_indices,
796                          float *weights, EdgeVertWeight *vert_weights,
797                          int count, int dest_index)
798 {
799         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
800                           weights, (float *)vert_weights, count, dest_index);
801 }
802
803 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
804                              int *src_indices,
805                              float *weights, FaceVertWeight *vert_weights,
806                              int count, int dest_index)
807 {
808         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
809                           weights, (float *)vert_weights, count, dest_index);
810 }
811
812 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
813 {
814         CustomData_swap(&dm->faceData, index, corner_indices);
815 }
816
817 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
818                          int *src_indices,
819                          float *weights, int count, int dest_index)
820 {
821         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
822                           weights, NULL, count, dest_index);
823 }
824
825 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
826                          int *src_indices,
827                          float *weights, int count, int dest_index)
828 {
829         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
830                           weights, NULL, count, dest_index);
831 }
832
833 ///
834 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
835 {
836         DerivedMesh *dm = CDDM_from_mesh(me, ob);
837         
838         if (!dm)
839                 return NULL;
840         
841         if (vertCos) {
842                 CDDM_apply_vert_coords(dm, vertCos);
843         }
844
845         return dm;
846 }
847
848 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
849                                               ModifierData *md, int build_shapekey_layers)
850 {
851         Mesh *me = ob->data;
852         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
853         DerivedMesh *dm;
854         KeyBlock *kb;
855
856         md->scene = scene;
857         
858         if (!(md->mode & eModifierMode_Realtime)) return NULL;
859         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
860         
861         if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
862                 BKE_key_convert_to_mesh(kb, me);
863         }
864         
865         if (mti->type == eModifierTypeType_OnlyDeform) {
866                 int numVerts;
867                 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
868
869                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
870                 dm = mesh_create_derived(me, ob, deformedVerts);
871
872                 if (build_shapekey_layers)
873                         add_shapekey_layers(dm, me, ob);
874                 
875                 MEM_freeN(deformedVerts);
876         }
877         else {
878                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
879
880                 if (build_shapekey_layers)
881                         add_shapekey_layers(tdm, me, ob);
882                 
883                 dm = modwrap_applyModifier(md, ob, tdm, 0);
884
885                 if (tdm != dm) tdm->release(tdm);
886         }
887
888         return dm;
889 }
890
891 static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
892 {
893         BMIter iter;
894         BMVert *eve;
895         float (*orco)[3];
896         int i;
897
898         /* these may not really be the orco's, but it's only for preview.
899          * could be solver better once, but isn't simple */
900         
901         orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
902
903         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
904                 copy_v3_v3(orco[i], eve->co);
905         }
906         
907         return orco;
908 }
909
910 /* orco custom data layer */
911 static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
912 {
913         *free = 0;
914
915         if (layer == CD_ORCO) {
916                 /* get original coordinates */
917                 *free = 1;
918
919                 if (em)
920                         return get_editbmesh_orco_verts(em);
921                 else
922                         return BKE_mesh_orco_verts_get(ob);
923         }
924         else if (layer == CD_CLOTH_ORCO) {
925                 /* apply shape key for cloth, this should really be solved
926                  * by a more flexible customdata system, but not simple */
927                 if (!em) {
928                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
929                         KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
930
931                         if (kb->data)
932                                 return kb->data;
933                 }
934
935                 return NULL;
936         }
937
938         return NULL;
939 }
940
941 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
942 {
943         DerivedMesh *dm;
944         float (*orco)[3];
945         int free;
946
947         if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
948         else dm = CDDM_from_mesh(me, ob);
949
950         orco = get_orco_coords_dm(ob, em, layer, &free);
951
952         if (orco) {
953                 CDDM_apply_vert_coords(dm, orco);
954                 if (free) MEM_freeN(orco);
955         }
956
957         return dm;
958 }
959
960 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
961                         DerivedMesh *orcodm, int layer)
962 {
963         float (*orco)[3], (*layerorco)[3];
964         int totvert, free;
965
966         totvert = dm->getNumVerts(dm);
967
968         if (orcodm) {
969                 orco = MEM_callocN(sizeof(float) * 3 * totvert, "dm orco");
970                 free = 1;
971
972                 if (orcodm->getNumVerts(orcodm) == totvert)
973                         orcodm->getVertCos(orcodm, orco);
974                 else
975                         dm->getVertCos(dm, orco);
976         }
977         else
978                 orco = get_orco_coords_dm(ob, em, layer, &free);
979
980         if (orco) {
981                 if (layer == CD_ORCO)
982                         BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
983
984                 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
985                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
986                         layerorco = DM_get_vert_data_layer(dm, layer);
987                 }
988
989                 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
990                 if (free) MEM_freeN(orco);
991         }
992 }
993
994 /* weight paint colors */
995
996 /* Something of a hack, at the moment deal with weightpaint
997  * by tucking into colors during modifier eval, only in
998  * wpaint mode. Works ok but need to make sure recalc
999  * happens on enter/exit wpaint.
1000  */
1001
1002 void weight_to_rgb(float r_rgb[3], const float weight)
1003 {
1004         const float blend = ((weight / 2.0f) + 0.5f);
1005
1006         if (weight <= 0.25f) {    /* blue->cyan */
1007                 r_rgb[0] = 0.0f;
1008                 r_rgb[1] = blend * weight * 4.0f;
1009                 r_rgb[2] = blend;
1010         }
1011         else if (weight <= 0.50f) {  /* cyan->green */
1012                 r_rgb[0] = 0.0f;
1013                 r_rgb[1] = blend;
1014                 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
1015         }
1016         else if (weight <= 0.75f) {  /* green->yellow */
1017                 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
1018                 r_rgb[1] = blend;
1019                 r_rgb[2] = 0.0f;
1020         }
1021         else if (weight <= 1.0f) {  /* yellow->red */
1022                 r_rgb[0] = blend;
1023                 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
1024                 r_rgb[2] = 0.0f;
1025         }
1026         else {
1027                 /* exceptional value, unclamped or nan,
1028                  * avoid uninitialized memory use */
1029                 r_rgb[0] = 1.0f;
1030                 r_rgb[1] = 0.0f;
1031                 r_rgb[2] = 1.0f;
1032         }
1033 }
1034
1035 /* draw_flag's for calc_weightpaint_vert_color */
1036 enum {
1037         /* only one of these should be set, keep first (for easy bit-shifting) */
1038         CALC_WP_GROUP_USER_ACTIVE   = (1 << 1),
1039         CALC_WP_GROUP_USER_ALL      = (1 << 2),
1040
1041         CALC_WP_MULTIPAINT          = (1 << 3),
1042         CALC_WP_AUTO_NORMALIZE      = (1 << 4)
1043 };
1044
1045 typedef struct DMWeightColorInfo {
1046         const ColorBand *coba;
1047         const char *alert_color;
1048 } DMWeightColorInfo;
1049
1050
1051 static int dm_drawflag_calc(ToolSettings *ts)
1052 {
1053         return ((ts->multipaint ? CALC_WP_MULTIPAINT :
1054                                   /* CALC_WP_GROUP_USER_ACTIVE or CALC_WP_GROUP_USER_ALL*/
1055                                   (1 << ts->weightuser)) |
1056                 (ts->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1057 }
1058
1059 static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcinfo, const float input)
1060 {
1061         float colf[4];
1062
1063         if (dm_wcinfo && dm_wcinfo->coba) {
1064                 do_colorband(dm_wcinfo->coba, input, colf);
1065         }
1066         else {
1067                 weight_to_rgb(colf, input);
1068         }
1069
1070         /* don't use rgb_float_to_uchar() here because
1071          * the resulting float doesn't need 0-1 clamp check */
1072         r_col[0] = (unsigned char)(colf[0] * 255.0f);
1073         r_col[1] = (unsigned char)(colf[1] * 255.0f);
1074         r_col[2] = (unsigned char)(colf[2] * 255.0f);
1075         r_col[3] = 255;
1076 }
1077
1078
1079 static void calc_weightpaint_vert_color(
1080         unsigned char r_col[4],
1081         MDeformVert *dv, 
1082         DMWeightColorInfo *dm_wcinfo,
1083         const int defbase_tot, const int defbase_act,
1084         const bool *defbase_sel, const int defbase_sel_tot,
1085         const int draw_flag)
1086 {
1087         float input = 0.0f;
1088         
1089         bool show_alert_color = false;
1090
1091         if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1092                 /* Multi-Paint feature */
1093                 bool was_a_nonzero = false;
1094                 unsigned int i;
1095
1096                 MDeformWeight *dw = dv->dw;
1097                 for (i = dv->totweight; i != 0; i--, dw++) {
1098                         /* in multipaint, get the average if auto normalize is inactive
1099                          * get the sum if it is active */
1100                         if (dw->def_nr < defbase_tot) {
1101                                 if (defbase_sel[dw->def_nr]) {
1102                                         if (dw->weight) {
1103                                                 input += dw->weight;
1104                                                 was_a_nonzero = true;
1105                                         }
1106                                 }
1107                         }
1108                 }
1109
1110                 /* make it black if the selected groups have no weight on a vertex */
1111                 if (was_a_nonzero == false) {
1112                         show_alert_color = true;
1113                 }
1114                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1115                         input /= defbase_sel_tot; /* get the average */
1116                 }
1117         }
1118         else {
1119                 /* default, non tricky behavior */
1120                 input = defvert_find_weight(dv, defbase_act);
1121
1122                 if (draw_flag & CALC_WP_GROUP_USER_ACTIVE) {
1123                         if (input == 0.0f) {
1124                                 show_alert_color = true;
1125                         }
1126                 }
1127                 else if (draw_flag & CALC_WP_GROUP_USER_ALL) {
1128                         if (input == 0.0f) {
1129                                 show_alert_color = defvert_is_weight_zero(dv, defbase_tot);
1130                         }
1131                 }
1132         }
1133
1134         if (show_alert_color == false) {
1135                 CLAMP(input, 0.0f, 1.0f);
1136                 weightpaint_color(r_col, dm_wcinfo, input);
1137         }
1138         else {
1139                 copy_v3_v3_char((char *)r_col, dm_wcinfo->alert_color);
1140                 r_col[3] = 255;
1141         }
1142 }
1143
1144 static DMWeightColorInfo G_dm_wcinfo;
1145
1146 void vDM_ColorBand_store(const ColorBand *coba, const char alert_color[4])
1147 {
1148         G_dm_wcinfo.coba        = coba;
1149         G_dm_wcinfo.alert_color = alert_color;
1150 }
1151
1152 /* return an array of vertex weight colors, caller must free.
1153  *
1154  * note that we could save some memory and allocate RGB only but then we'd need to
1155  * re-arrange the colors when copying to the face since MCol has odd ordering,
1156  * so leave this as is - campbell */
1157 static void calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, DMWeightColorInfo *dm_wcinfo,
1158                                         unsigned char (*r_wtcol_v)[4])
1159 {
1160         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1161         int numVerts = dm->getNumVerts(dm);
1162
1163         if (dv) {
1164                 unsigned char (*wc)[4] = r_wtcol_v;
1165                 unsigned int i;
1166
1167                 /* variables for multipaint */
1168                 const int defbase_tot = BLI_countlist(&ob->defbase);
1169                 const int defbase_act = ob->actdef - 1;
1170
1171                 int defbase_sel_tot = 0;
1172                 bool *defbase_sel = NULL;
1173
1174                 if (draw_flag & CALC_WP_MULTIPAINT) {
1175                         defbase_sel = BKE_objdef_selected_get(ob, defbase_tot, &defbase_sel_tot);
1176                 }
1177
1178                 for (i = numVerts; i != 0; i--, wc++, dv++) {
1179                         calc_weightpaint_vert_color((unsigned char *)wc, dv, dm_wcinfo, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1180                 }
1181
1182                 if (defbase_sel) {
1183                         MEM_freeN(defbase_sel);
1184                 }
1185         }
1186         else {
1187                 int col_i;
1188                 if (draw_flag & (CALC_WP_GROUP_USER_ACTIVE | CALC_WP_GROUP_USER_ALL)) {
1189                         col_i = 0;
1190                 }
1191                 else {
1192                         weightpaint_color((unsigned char *)&col_i, dm_wcinfo, 0.0f);
1193                 }
1194                 fill_vn_i((int *)r_wtcol_v, numVerts, col_i);
1195         }
1196 }
1197
1198 /* return an array of vertex weight colors from given weights, caller must free.
1199  *
1200  * note that we could save some memory and allocate RGB only but then we'd need to
1201  * re-arrange the colors when copying to the face since MCol has odd ordering,
1202  * so leave this as is - campbell */
1203 static void calc_colors_from_weights_array(const int num, const float *weights,
1204                                            unsigned char (*r_wtcol_v)[4])
1205 {
1206         unsigned char (*wc)[4] = r_wtcol_v;
1207         int i;
1208
1209         for (i = 0; i < num; i++, wc++, weights++) {
1210                 weightpaint_color((unsigned char *)wc, NULL, *weights);
1211         }
1212 }
1213
1214 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1215                            float *weights, int num, const int *indices)
1216 {
1217         BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1218         unsigned char (*wtcol_v)[4];
1219         int numVerts = dm->getNumVerts(dm);
1220         int i;
1221
1222         if (em) {
1223                 BKE_editmesh_color_ensure(em, BM_VERT);
1224                 wtcol_v = em->derivedVertColor;
1225         }
1226         else {
1227                 wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__);
1228         }
1229
1230         /* Weights are given by caller. */
1231         if (weights) {
1232                 float *w = weights;
1233                 /* If indices is not NULL, it means we do not have weights for all vertices,
1234                  * so we must create them (and set them to zero)... */
1235                 if (indices) {
1236                         w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
1237                         i = num;
1238                         while (i--)
1239                                 w[indices[i]] = weights[i];
1240                 }
1241
1242                 /* Convert float weights to colors. */
1243                 calc_colors_from_weights_array(numVerts, w, wtcol_v);
1244
1245                 if (indices)
1246                         MEM_freeN(w);
1247         }
1248         else {
1249                 /* No weights given, take them from active vgroup(s). */
1250                 calc_weightpaint_vert_array(ob, dm, draw_flag, &G_dm_wcinfo, wtcol_v);
1251         }
1252
1253         if (dm->type == DM_TYPE_EDITBMESH) {
1254                 /* editmesh draw function checks spesifically for this */
1255         }
1256         else {
1257                 const int dm_totpoly = dm->getNumPolys(dm);
1258                 const int dm_totloop = dm->getNumLoops(dm);
1259                 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1260                 MLoop *mloop = dm->getLoopArray(dm), *ml;
1261                 MPoly *mp = dm->getPolyArray(dm);
1262                 int l_index;
1263                 int j;
1264
1265                 /* now add to loops, so the data can be passed through the modifier stack */
1266                 /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1267                 if (!wtcol_l) {
1268                         wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__);
1269                         CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
1270                 }
1271
1272                 l_index = 0;
1273                 for (i = 0; i < dm_totpoly; i++, mp++) {
1274                         ml = mloop + mp->loopstart;
1275
1276                         for (j = 0; j < mp->totloop; j++, ml++, l_index++) {
1277                                 copy_v4_v4_char((char *)&wtcol_l[l_index],
1278                                                 (char *)&wtcol_v[ml->v]);
1279                         }
1280                 }
1281                 MEM_freeN(wtcol_v);
1282
1283                 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1284         }
1285 }
1286
1287 static void DM_update_statvis_color(Scene *scene, Object *ob, DerivedMesh *dm)
1288 {
1289         BMEditMesh *em = BKE_editmesh_from_object(ob);
1290
1291         BKE_editmesh_statvis_calc(em, dm, &scene->toolsettings->statvis);
1292 }
1293
1294 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1295 {
1296         KeyBlock *kb;
1297         int i, j, tot;
1298         
1299         if (!me->key)
1300                 return;
1301         
1302         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1303         for (i = 0; i < tot; i++) {
1304                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1305                 float (*cos)[3], (*kbcos)[3];
1306                 
1307                 for (kb = me->key->block.first; kb; kb = kb->next) {
1308                         if (kb->uid == layer->uid)
1309                                 break;
1310                 }
1311                 
1312                 if (!kb) {
1313                         kb = BKE_keyblock_add(me->key, layer->name);
1314                         kb->uid = layer->uid;
1315                 }
1316                 
1317                 if (kb->data)
1318                         MEM_freeN(kb->data);
1319                 
1320                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1321                 kb->totelem = dm->numVertData;
1322
1323                 kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
1324                 if (kb->uid == actshape_uid) {
1325                         MVert *mvert = dm->getVertArray(dm);
1326                         
1327                         for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1328                                 copy_v3_v3(*kbcos, mvert->co);
1329                         }
1330                 }
1331                 else {
1332                         for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1333                                 copy_v3_v3(*kbcos, *cos);
1334                         }
1335                 }
1336         }
1337         
1338         for (kb = me->key->block.first; kb; kb = kb->next) {
1339                 if (kb->totelem != dm->numVertData) {
1340                         if (kb->data)
1341                                 MEM_freeN(kb->data);
1342                         
1343                         kb->totelem = dm->numVertData;
1344                         kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
1345                         fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1346                 }
1347         }
1348 }
1349
1350 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1351 {
1352         KeyBlock *kb;
1353         Key *key = me->key;
1354         int i;
1355         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1356
1357         if (!me->key)
1358                 return;
1359
1360         /* ensure we can use mesh vertex count for derived mesh custom data */
1361         if (me->totvert != dm->getNumVerts(dm)) {
1362                 fprintf(stderr,
1363                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1364                         __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1365                 return;
1366         }
1367
1368         for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1369                 int ci;
1370                 float *array;
1371
1372                 if (me->totvert != kb->totelem) {
1373                         fprintf(stderr,
1374                                 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1375                                 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1376                         array = MEM_callocN(shape_alloc_len, __func__);
1377                 }
1378                 else {
1379                         array = MEM_mallocN(shape_alloc_len, __func__);
1380                         memcpy(array, kb->data, shape_alloc_len);
1381                 }
1382
1383                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1384                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1385
1386                 dm->vertData.layers[ci].uid = kb->uid;
1387         }
1388 }
1389
1390 /**
1391  * Called after calculating all modifiers.
1392  *
1393  * \note tessfaces should already be calculated.
1394  */
1395 static void dm_ensure_display_normals(DerivedMesh *dm)
1396 {
1397         /* this is for final output only, up until now this layer should be missing */
1398         BLI_assert(CustomData_has_layer(&dm->polyData, CD_NORMAL) == false);
1399
1400         if ((dm->type == DM_TYPE_CDDM) &&
1401             ((dm->dirty & DM_DIRTY_NORMALS) || CustomData_has_layer(&dm->faceData, CD_NORMAL) == FALSE))
1402         {
1403                 /* if normals are dirty we want to calculate vertex normals too */
1404                 CDDM_calc_normals_mapping_ex(dm, (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
1405         }
1406 }
1407 /* new value for useDeform -1  (hack for the gameengine):
1408  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1409  * - don't apply the key
1410  * - apply deform modifiers and input vertexco
1411  */
1412 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1413                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1414                                 int useRenderParams, int useDeform,
1415                                 int needMapping, CustomDataMask dataMask,
1416                                 int index, int useCache, int build_shapekey_layers)
1417 {
1418         Mesh *me = ob->data;
1419         ModifierData *firstmd, *md, *previewmd = NULL;
1420         CDMaskLink *datamasks, *curr;
1421         /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1422         CustomDataMask mask, nextmask, previewmask = 0, append_mask = CD_MASK_ORIGINDEX;
1423         float (*deformedVerts)[3] = NULL;
1424         DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1425         int numVerts = me->totvert;
1426         int required_mode;
1427         int isPrevDeform = FALSE;
1428         int skipVirtualArmature = (useDeform < 0);
1429         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1430         int has_multires = mmd != NULL, multires_applied = 0;
1431         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1432         int sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm);
1433         int draw_flag = dm_drawflag_calc(scene->toolsettings);
1434
1435         /* Generic preview only in object mode! */
1436         const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1437 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1438         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1439 #endif
1440         const int do_final_wmcol = FALSE;
1441         int do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1442         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1443         const int do_mod_wmcol = do_init_wmcol;
1444
1445         ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1446         ModifierApplyFlag deform_app_flags = app_flags;
1447         if (useCache)
1448                 app_flags |= MOD_APPLY_USECACHE;
1449         if (useDeform)
1450                 deform_app_flags |= MOD_APPLY_USECACHE;
1451
1452         if (mmd && !mmd->sculptlvl)
1453                 has_multires = 0;
1454
1455         if (!skipVirtualArmature) {
1456                 firstmd = modifiers_getVirtualModifierList(ob);
1457         }
1458         else {
1459                 /* game engine exception */
1460                 firstmd = ob->modifiers.first;
1461                 if (firstmd && firstmd->type == eModifierType_Armature)
1462                         firstmd = firstmd->next;
1463         }
1464
1465         md = firstmd;
1466
1467         modifiers_clearErrors(ob);
1468
1469         if (useRenderParams) required_mode = eModifierMode_Render;
1470         else required_mode = eModifierMode_Realtime;
1471
1472         if (do_mod_wmcol || do_mod_mcol) {
1473                 /* Find the last active modifier generating a preview, or NULL if none. */
1474                 /* XXX Currently, DPaint modifier just ignores this.
1475                  *     Needs a stupid hack...
1476                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1477                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1478
1479                 /* even if the modifier doesn't need the data, to make a preview it may */
1480                 if (previewmd) {
1481                         if (do_mod_wmcol) {
1482                                 previewmask = CD_MASK_MDEFORMVERT;
1483                         }
1484                 }
1485         }
1486
1487         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1488         curr = datamasks;
1489
1490         if (deform_r) *deform_r = NULL;
1491         *final_r = NULL;
1492
1493         if (useDeform) {
1494                 if (inputVertexCos)
1495                         deformedVerts = inputVertexCos;
1496                 
1497                 /* Apply all leading deforming modifiers */
1498                 for (; md; md = md->next, curr = curr->next) {
1499                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1500
1501                         md->scene = scene;
1502                         
1503                         if (!modifier_isEnabled(scene, md, required_mode)) continue;
1504                         if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1505
1506                         if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
1507                                 if (!deformedVerts)
1508                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1509
1510                                 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1511                         }
1512                         else {
1513                                 break;
1514                         }
1515                         
1516                         /* grab modifiers until index i */
1517                         if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1518                                 break;
1519                 }
1520
1521                 /* Result of all leading deforming modifiers is cached for
1522                  * places that wish to use the original mesh but with deformed
1523                  * coordinates (vpaint, etc.)
1524                  */
1525                 if (deform_r) {
1526                         *deform_r = CDDM_from_mesh(me, ob);
1527                          
1528                         if (build_shapekey_layers)
1529                                 add_shapekey_layers(dm, me, ob);
1530                         
1531                         if (deformedVerts) {
1532                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1533                         }
1534                 }
1535         }
1536         else {
1537                 /* default behavior for meshes */
1538                 if (inputVertexCos)
1539                         deformedVerts = inputVertexCos;
1540                 else
1541                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1542         }
1543
1544
1545         /* Now apply all remaining modifiers. If useDeform is off then skip
1546          * OnlyDeform ones. 
1547          */
1548         dm = NULL;
1549         orcodm = NULL;
1550         clothorcodm = NULL;
1551
1552         for (; md; md = md->next, curr = curr->next) {
1553                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1554
1555                 md->scene = scene;
1556
1557                 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1558                 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1559                 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1560                         modifier_setError(md, "Modifier requires original data, bad stack position");
1561                         continue;
1562                 }
1563                 if (sculpt_mode &&
1564                         (!has_multires || multires_applied || ob->sculpt->bm))
1565                 {
1566                         int unsupported = 0;
1567
1568                         if (md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0) {
1569                                 /* If multires is on level 0 skip it silently without warning message. */
1570                                 continue;
1571                         }
1572
1573                         if (sculpt_dyntopo && !useRenderParams)
1574                                 unsupported = TRUE;
1575
1576                         if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1577                                 unsupported |= mti->type != eModifierTypeType_OnlyDeform;
1578
1579                         unsupported |= multires_applied;
1580
1581                         if (unsupported) {
1582                                 modifier_setError(md, "Not supported in sculpt mode");
1583                                 continue;
1584                         }
1585                 }
1586                 if (needMapping && !modifier_supportsMapping(md)) continue;
1587                 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1588
1589                 /* add an orco layer if needed by this modifier */
1590                 if (mti->requiredDataMask)
1591                         mask = mti->requiredDataMask(ob, md);
1592                 else
1593                         mask = 0;
1594
1595                 if (dm && (mask & CD_MASK_ORCO))
1596                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1597
1598                 /* How to apply modifier depends on (a) what we already have as
1599                  * a result of previous modifiers (could be a DerivedMesh or just
1600                  * deformed vertices) and (b) what type the modifier is.
1601                  */
1602
1603                 if (mti->type == eModifierTypeType_OnlyDeform) {
1604                         /* No existing verts to deform, need to build them. */
1605                         if (!deformedVerts) {
1606                                 if (dm) {
1607                                         /* Deforming a derived mesh, read the vertex locations
1608                                          * out of the mesh and deform them. Once done with this
1609                                          * run of deformers verts will be written back.
1610                                          */
1611                                         numVerts = dm->getNumVerts(dm);
1612                                         deformedVerts =
1613                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1614                                         dm->getVertCos(dm, deformedVerts);
1615                                 }
1616                                 else {
1617                                         deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1618                                 }
1619                         }
1620
1621                         /* if this is not the last modifier in the stack then recalculate the normals
1622                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1623                         if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1624                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1625                                 if (dm && dm->type == DM_TYPE_CDDM) {
1626                                         CDDM_apply_vert_coords(dm, deformedVerts);
1627                                 }
1628                         }
1629
1630                         modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
1631                 }
1632                 else {
1633                         DerivedMesh *ndm;
1634
1635                         /* determine which data layers are needed by following modifiers */
1636                         if (curr->next)
1637                                 nextmask = curr->next->mask;
1638                         else
1639                                 nextmask = dataMask;
1640
1641                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1642                         if (dm) {
1643                                 if (deformedVerts) {
1644                                         DerivedMesh *tdm = CDDM_copy(dm);
1645                                         dm->release(dm);
1646                                         dm = tdm;
1647
1648                                         CDDM_apply_vert_coords(dm, deformedVerts);
1649                                 }
1650                         }
1651                         else {
1652                                 dm = CDDM_from_mesh(me, ob);
1653
1654                                 if (build_shapekey_layers)
1655                                         add_shapekey_layers(dm, me, ob);
1656
1657                                 if (deformedVerts) {
1658                                         CDDM_apply_vert_coords(dm, deformedVerts);
1659                                 }
1660
1661                                 if (do_init_wmcol)
1662                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1663
1664                                 /* Constructive modifiers need to have an origindex
1665                                  * otherwise they wont have anywhere to copy the data from.
1666                                  *
1667                                  * Also create ORIGINDEX data if any of the following modifiers
1668                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1669                                  * data by using generic DM_copy_vert_data() functions.
1670                                  */
1671                                 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1672                                         /* calc */
1673                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1674                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1675                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1676
1677 #pragma omp parallel sections if (dm->numVertData + dm->numEdgeData + dm->numPolyData >= DM_OMP_LIMIT)
1678                                         {
1679 #pragma omp section
1680                                                 { range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0); }
1681 #pragma omp section
1682                                                 { range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0); }
1683 #pragma omp section
1684                                                 { range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0); }
1685                                         }
1686                                 }
1687                         }
1688
1689                         
1690                         /* set the DerivedMesh to only copy needed data */
1691                         mask = curr->mask;
1692                         /* needMapping check here fixes bug [#28112], otherwise its
1693                          * possible that it wont be copied */
1694                         mask |= append_mask;
1695                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1696                         
1697                         /* add cloth rest shape key if need */
1698                         if (mask & CD_MASK_CLOTH_ORCO)
1699                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1700
1701                         /* add an origspace layer if needed */
1702                         if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
1703                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1704                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1705                                         DM_init_origspace(dm);
1706                                 }
1707                         }
1708
1709                         ndm = modwrap_applyModifier(md, ob, dm, app_flags);
1710
1711                         if (ndm) {
1712                                 /* if the modifier returned a new dm, release the old one */
1713                                 if (dm && dm != ndm) dm->release(dm);
1714
1715                                 dm = ndm;
1716
1717                                 if (deformedVerts) {
1718                                         if (deformedVerts != inputVertexCos)
1719                                                 MEM_freeN(deformedVerts);
1720
1721                                         deformedVerts = NULL;
1722                                 }
1723                         }
1724
1725                         /* create an orco derivedmesh in parallel */
1726                         if (nextmask & CD_MASK_ORCO) {
1727                                 if (!orcodm)
1728                                         orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
1729
1730                                 nextmask &= ~CD_MASK_ORCO;
1731                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
1732                                                  (mti->requiredDataMask ?
1733                                                   mti->requiredDataMask(ob, md) : 0));
1734
1735                                 ndm = modwrap_applyModifier(md, ob, orcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1736
1737                                 if (ndm) {
1738                                         /* if the modifier returned a new dm, release the old one */
1739                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1740                                         orcodm = ndm;
1741                                 }
1742                         }
1743
1744                         /* create cloth orco derivedmesh in parallel */
1745                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1746                                 if (!clothorcodm)
1747                                         clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1748
1749                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1750                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1751
1752                                 ndm = modwrap_applyModifier(md, ob, clothorcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1753
1754                                 if (ndm) {
1755                                         /* if the modifier returned a new dm, release the old one */
1756                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1757                                         clothorcodm = ndm;
1758                                 }
1759                         }
1760
1761                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1762                         /* XXX Temp and hackish solution! */
1763                         if (md->type == eModifierType_DynamicPaint)
1764                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1765                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1766                         else if ((md == previewmd) && (do_mod_wmcol)) {
1767                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1768                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1769                         }
1770                 }
1771
1772                 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1773
1774                 /* grab modifiers until index i */
1775                 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1776                         break;
1777
1778                 if (sculpt_mode && md->type == eModifierType_Multires)
1779                         multires_applied = 1;
1780         }
1781
1782         for (md = firstmd; md; md = md->next)
1783                 modifier_freeTemporaryData(md);
1784
1785         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1786          * need to apply these back onto the DerivedMesh. If we have no
1787          * DerivedMesh then we need to build one.
1788          */
1789         if (dm && deformedVerts) {
1790                 finaldm = CDDM_copy(dm);
1791
1792                 dm->release(dm);
1793
1794                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1795
1796 #if 0 /* For later nice mod preview! */
1797                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1798                 if (do_final_wmcol)
1799                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1800 #endif
1801         }
1802         else if (dm) {
1803                 finaldm = dm;
1804
1805 #if 0 /* For later nice mod preview! */
1806                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1807                 if (do_final_wmcol)
1808                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1809 #endif
1810         }
1811         else {
1812                 finaldm = CDDM_from_mesh(me, ob);
1813                 
1814                 if (build_shapekey_layers) {
1815                         add_shapekey_layers(finaldm, me, ob);
1816                 }
1817                 
1818                 if (deformedVerts) {
1819                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1820                 }
1821
1822                 /* In this case, we should never have weight-modifying modifiers in stack... */
1823                 if (do_init_wmcol)
1824                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1825         }
1826
1827         /* add an orco layer if needed */
1828         if (dataMask & CD_MASK_ORCO) {
1829                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1830
1831                 if (deform_r && *deform_r)
1832                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1833         }
1834
1835         {
1836                 /* calculating normals can re-calculate tessfaces in some cases */
1837 #if 0
1838                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1839 #endif
1840                 /* --------------------------------------------------------------------- */
1841                 /* First calculate the polygon and vertex normals, re-tessellation
1842                  * copies these into the tessface's normal layer */
1843
1844
1845                 /* comment because this causes a bug when deform is applied after a
1846                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1847                  * it also looks like this isn't even needed since code above recalc's
1848                  * normals - campbell */
1849 #if 0
1850                 finaldm->calcNormals(finaldm);
1851 #endif
1852
1853                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1854                  * from loops and polys onto the tessfaces. This may be currently be
1855                  * redundant in cases where the render mode doesn't use these inputs, but
1856                  * ideally eventually tessellation would happen on-demand, and this is one
1857                  * of the primary places it would be needed. */
1858 #if 0
1859                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
1860 #else
1861                 if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */
1862 #endif
1863                 {
1864                         finaldm->recalcTessellation(finaldm);
1865                 }
1866                 /* Even if tessellation is not needed, some modifiers might have modified CD layers
1867                  * (like mloopcol or mloopuv), hence we have to update those. */
1868                 else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
1869                         /* A tessellation already exists, it should always have a CD_ORIGINDEX. */
1870                         BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX));
1871                         DM_update_tessface_data(finaldm);
1872                 }
1873                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1874                 /* take care with this block, we really need testing frameworks          */
1875                 /* --------------------------------------------------------------------- */
1876
1877                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1878                  * normals and will also have to calculate normals on the fly, try avoid
1879                  * this where possible since calculating polygon normals isn't fast,
1880                  * note that this isn't a problem for subsurf (only quads) or editmode
1881                  * which deals with drawing differently.
1882                  *
1883                  * Only calc vertex normals if they are flagged as dirty.
1884                  */
1885                 dm_ensure_display_normals(finaldm);
1886         }
1887
1888 #ifdef WITH_GAMEENGINE
1889         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1890         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1891                 DerivedMesh *tdm;
1892                 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1893                 if (finaldm != tdm) {
1894                         finaldm->release(finaldm);
1895                         finaldm = tdm;
1896                 }
1897         }
1898 #endif /* WITH_GAMEENGINE */
1899
1900         *final_r = finaldm;
1901
1902         if (orcodm)
1903                 orcodm->release(orcodm);
1904         if (clothorcodm)
1905                 clothorcodm->release(clothorcodm);
1906
1907         if (deformedVerts && deformedVerts != inputVertexCos)
1908                 MEM_freeN(deformedVerts);
1909
1910         BLI_linklist_free((LinkNode *)datamasks, NULL);
1911 }
1912
1913 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1914 {
1915         BMIter iter;
1916         BMVert *eve;
1917         float (*cos)[3];
1918         int i;
1919
1920         *numVerts_r = em->bm->totvert;
1921
1922         cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
1923
1924         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1925                 copy_v3_v3(cos[i], eve->co);
1926         }
1927
1928         return cos;
1929 }
1930
1931 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1932 {
1933         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1934         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1935
1936         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1937         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1938                 modifier_setError(md, "Modifier requires original data, bad stack position");
1939                 return 0;
1940         }
1941         
1942         return 1;
1943 }
1944
1945 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1946                                      DerivedMesh **final_r,
1947                                      CustomDataMask dataMask)
1948 {
1949         ModifierData *md;
1950         float (*deformedVerts)[3] = NULL;
1951         CustomDataMask mask;
1952         DerivedMesh *dm, *orcodm = NULL;
1953         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1954         CDMaskLink *datamasks, *curr;
1955         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1956         int draw_flag = dm_drawflag_calc(scene->toolsettings);
1957
1958         // const int do_mod_mcol = true; // (ob->mode == OB_MODE_OBJECT);
1959 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1960         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1961 #endif
1962         const int do_final_wmcol = FALSE;
1963         int do_init_wmcol = ((((Mesh *)ob->data)->drawflag & ME_DRAWEIGHT) && !do_final_wmcol);
1964         int do_init_statvis = ((((Mesh *)ob->data)->drawflag & ME_DRAW_STATVIS) && !do_init_wmcol);
1965
1966         modifiers_clearErrors(ob);
1967
1968         if (cage_r && cageIndex == -1) {
1969                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1970         }
1971
1972         dm = NULL;
1973         md = modifiers_getVirtualModifierList(ob);
1974
1975         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, NULL, 0);
1976
1977         curr = datamasks;
1978         for (i = 0; md; i++, md = md->next, curr = curr->next) {
1979                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1980
1981                 md->scene = scene;
1982                 
1983                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
1984                         continue;
1985
1986                 /* add an orco layer if needed by this modifier */
1987                 if (dm && mti->requiredDataMask) {
1988                         mask = mti->requiredDataMask(ob, md);
1989                         if (mask & CD_MASK_ORCO)
1990                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1991                 }
1992
1993                 /* How to apply modifier depends on (a) what we already have as
1994                  * a result of previous modifiers (could be a DerivedMesh or just
1995                  * deformed vertices) and (b) what type the modifier is.
1996                  */
1997
1998                 if (mti->type == eModifierTypeType_OnlyDeform) {
1999                         /* No existing verts to deform, need to build them. */
2000                         if (!deformedVerts) {
2001                                 if (dm) {
2002                                         /* Deforming a derived mesh, read the vertex locations
2003                                          * out of the mesh and deform them. Once done with this
2004                                          * run of deformers verts will be written back.
2005                                          */
2006                                         numVerts = dm->getNumVerts(dm);
2007                                         deformedVerts =
2008                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2009                                         dm->getVertCos(dm, deformedVerts);
2010                                 }
2011                                 else {
2012                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
2013                                 }
2014                         }
2015
2016                         if (mti->deformVertsEM)
2017                                 modwrap_deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2018                         else
2019                                 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
2020                 }
2021                 else {
2022                         DerivedMesh *ndm;
2023
2024                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2025                         if (dm) {
2026                                 if (deformedVerts) {
2027                                         DerivedMesh *tdm = CDDM_copy(dm);
2028                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
2029                                         dm = tdm;
2030
2031                                         CDDM_apply_vert_coords(dm, deformedVerts);
2032                                 }
2033                                 else if (cage_r && dm == *cage_r) {
2034                                         /* dm may be changed by this modifier, so we need to copy it
2035                                          */
2036                                         dm = CDDM_copy(dm);
2037                                 }
2038
2039                         }
2040                         else {
2041                                 dm = CDDM_from_editbmesh(em, FALSE, FALSE);
2042
2043                                 if (deformedVerts) {
2044                                         CDDM_apply_vert_coords(dm, deformedVerts);
2045                                 }
2046
2047                                 if (do_init_wmcol) {
2048                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2049                                 }
2050                         }
2051
2052                         /* create an orco derivedmesh in parallel */
2053                         mask = curr->mask;
2054                         if (mask & CD_MASK_ORCO) {
2055                                 if (!orcodm)
2056                                         orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
2057
2058                                 mask &= ~CD_MASK_ORCO;
2059                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2060
2061                                 if (mti->applyModifierEM)
2062                                         ndm = modwrap_applyModifierEM(md, ob, em, orcodm, MOD_APPLY_ORCO);
2063                                 else
2064                                         ndm = modwrap_applyModifier(md, ob, orcodm, MOD_APPLY_ORCO);
2065
2066                                 if (ndm) {
2067                                         /* if the modifier returned a new dm, release the old one */
2068                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2069                                         orcodm = ndm;
2070                                 }
2071                         }
2072
2073                         /* set the DerivedMesh to only copy needed data */
2074                         mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
2075
2076                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2077
2078                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
2079                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2080                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2081                                         DM_init_origspace(dm);
2082                                 }
2083                         }
2084
2085                         if (mti->applyModifierEM)
2086                                 ndm = modwrap_applyModifierEM(md, ob, em, dm, MOD_APPLY_USECACHE);
2087                         else
2088                                 ndm = mti->applyModifier(md, ob, dm, MOD_APPLY_USECACHE);
2089
2090                         if (ndm) {
2091                                 if (dm && dm != ndm)
2092                                         dm->release(dm);
2093
2094                                 dm = ndm;
2095
2096                                 if (deformedVerts) {
2097                                         MEM_freeN(deformedVerts);
2098                                         deformedVerts = NULL;
2099                                 }
2100                         }
2101                 }
2102
2103                 if (cage_r && i == cageIndex) {
2104                         if (dm && deformedVerts) {
2105                                 *cage_r = CDDM_copy(dm);
2106                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2107                         }
2108                         else if (dm) {
2109                                 *cage_r = dm;
2110                         }
2111                         else {
2112                                 *cage_r =
2113                                     getEditDerivedBMesh(em, ob,
2114                                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2115                         }
2116                 }
2117         }
2118
2119         BLI_linklist_free((LinkNode *)datamasks, NULL);
2120
2121         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2122          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2123          * then we need to build one.
2124          */
2125         if (dm && deformedVerts) {
2126                 *final_r = CDDM_copy(dm);
2127
2128                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2129
2130                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2131         }
2132         else if (dm) {
2133                 *final_r = dm;
2134         }
2135         else if (!deformedVerts && cage_r && *cage_r) {
2136                 /* cage should already have up to date normals */
2137                 *final_r = *cage_r;
2138
2139                 /* In this case, we should never have weight-modifying modifiers in stack... */
2140                 if (do_init_wmcol)
2141                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2142                 if (do_init_statvis)
2143                         DM_update_statvis_color(scene, ob, *final_r);
2144         }
2145         else {
2146                 /* this is just a copy of the editmesh, no need to calc normals */
2147                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2148                 deformedVerts = NULL;
2149
2150                 /* In this case, we should never have weight-modifying modifiers in stack... */
2151                 if (do_init_wmcol)
2152                         DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2153                 if (do_init_statvis)
2154                         DM_update_statvis_color(scene, ob, *final_r);
2155         }
2156
2157         /* --- */
2158         /* BMESH_ONLY, ensure tessface's used for drawing,
2159          * but don't recalculate if the last modifier in the stack gives us tessfaces
2160          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2161          * but quiets annoying error messages since tessfaces wont be created. */
2162         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2163                 DM_ensure_tessface(*final_r);
2164         }
2165         if (cage_r && *cage_r) {
2166                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2167                         if (*cage_r != *final_r) {
2168                                 DM_ensure_tessface(*cage_r);
2169                         }
2170                 }
2171         }
2172         /* --- */
2173
2174         /* same as mesh_calc_modifiers */
2175         dm_ensure_display_normals(*final_r);
2176
2177         /* add an orco layer if needed */
2178         if (dataMask & CD_MASK_ORCO)
2179                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2180
2181         if (orcodm)
2182                 orcodm->release(orcodm);
2183
2184         if (deformedVerts)
2185                 MEM_freeN(deformedVerts);
2186 }
2187
2188 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2189                             int build_shapekey_layers)
2190 {
2191         Object *obact = scene->basact ? scene->basact->object : NULL;
2192         int editing = paint_facesel_test(ob);
2193         /* weight paint and face select need original indices because of selection buffer drawing */
2194         int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2195
2196         BLI_assert(ob->type == OB_MESH);
2197
2198         BKE_object_free_derived_caches(ob);
2199         BKE_object_sculpt_modifiers_changed(ob);
2200
2201         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2202                             &ob->derivedFinal, 0, 1,
2203                             needMapping, dataMask, -1, 1, build_shapekey_layers);
2204
2205         DM_set_object_boundbox(ob, ob->derivedFinal);
2206
2207         ob->derivedFinal->needsFree = 0;
2208         ob->derivedDeform->needsFree = 0;
2209         ob->lastDataMask = dataMask;
2210
2211         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2212                 /* create PBVH immediately (would be created on the fly too,
2213                  * but this avoids waiting on first stroke) */
2214                 ob->sculpt->pbvh = ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2215         }
2216
2217         BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS));
2218 }
2219
2220 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2221 {
2222         BKE_object_free_derived_caches(obedit);
2223         BKE_object_sculpt_modifiers_changed(obedit);
2224
2225         if (em->derivedFinal) {
2226                 if (em->derivedFinal != em->derivedCage) {
2227                         em->derivedFinal->needsFree = 1;
2228                         em->derivedFinal->release(em->derivedFinal);
2229                 }
2230                 em->derivedFinal = NULL;
2231         }
2232         if (em->derivedCage) {
2233                 em->derivedCage->needsFree = 1;
2234                 em->derivedCage->release(em->derivedCage);
2235                 em->derivedCage = NULL;
2236         }
2237
2238         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2239         DM_set_object_boundbox(obedit, em->derivedFinal);
2240
2241         em->lastDataMask = dataMask;
2242         em->derivedFinal->needsFree = 0;
2243         em->derivedCage->needsFree = 0;
2244
2245         BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS));
2246 }
2247
2248 static CustomDataMask object_get_datamask(Scene *scene, Object *ob)
2249 {
2250         Object *actob = scene->basact ? scene->basact->object : NULL;
2251         CustomDataMask mask = ob->customdata_mask;
2252
2253         if (ob == actob) {
2254                 /* check if we need tfaces & mcols due to face select or texture paint */
2255                 if (paint_facesel_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2256                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2257                 }
2258
2259                 /* check if we need mcols due to vertex paint or weightpaint */
2260                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2261                         mask |= CD_MASK_MCOL;
2262                 }
2263
2264                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2265                         mask |= CD_MASK_PREVIEW_MCOL;
2266                 }
2267
2268                 if (ob->mode & OB_MODE_EDIT)
2269                         mask |= CD_MASK_MVERT_SKIN;
2270         }
2271
2272         return mask;
2273 }
2274
2275 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2276                      CustomDataMask dataMask, int build_shapekey_layers)
2277 {
2278         dataMask |= object_get_datamask(scene, ob);
2279
2280         if (em) {
2281                 editbmesh_build_data(scene, ob, em, dataMask);
2282         }
2283         else {
2284                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2285         }
2286 }
2287
2288 /***/
2289
2290 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2291 {
2292         /* if there's no derived mesh or the last data mask used doesn't include
2293          * the data we need, rebuild the derived mesh
2294          */
2295         dataMask |= object_get_datamask(scene, ob);
2296
2297         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2298                 mesh_build_data(scene, ob, dataMask, 0);
2299
2300         if (ob->derivedFinal) { BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2301         return ob->derivedFinal;
2302 }
2303
2304 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2305 {
2306         /* if there's no derived mesh or the last data mask used doesn't include
2307          * the data we need, rebuild the derived mesh
2308          */
2309         dataMask |= object_get_datamask(scene, ob);
2310
2311         if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2312                 mesh_build_data(scene, ob, dataMask, 0);
2313
2314         return ob->derivedDeform;
2315 }
2316
2317 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2318 {
2319         DerivedMesh *final;
2320         
2321         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2322
2323         return final;
2324 }
2325
2326 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2327 {
2328         DerivedMesh *final;
2329         
2330         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2331
2332         return final;
2333 }
2334
2335 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2336 {
2337         DerivedMesh *final;
2338
2339         /* XXX hack
2340          * psys modifier updates particle state when called during dupli-list generation,
2341          * which can lead to wrong transforms. This disables particle system modifier execution.
2342          */
2343         ob->transflag |= OB_NO_PSYS_UPDATE;
2344
2345         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2346
2347         ob->transflag &= ~OB_NO_PSYS_UPDATE;
2348
2349         return final;
2350 }
2351
2352 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2353                                            CustomDataMask dataMask)
2354 {
2355         DerivedMesh *final;
2356         
2357         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2358
2359         return final;
2360 }
2361
2362 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2363                                             CustomDataMask dataMask)
2364 {
2365         DerivedMesh *final;
2366         
2367         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2368
2369         return final;
2370 }
2371
2372 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2373                                          CustomDataMask dataMask)
2374 {
2375         DerivedMesh *final;
2376         
2377         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2378
2379         return final;
2380 }
2381
2382 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2383                                                   float (*vertCos)[3],
2384                                                   CustomDataMask dataMask)
2385 {
2386         DerivedMesh *final;
2387
2388         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2389
2390         return final;
2391 }
2392
2393 /***/
2394
2395 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2396                                                   CustomDataMask dataMask)
2397 {
2398         /* if there's no derived mesh or the last data mask used doesn't include
2399          * the data we need, rebuild the derived mesh
2400          */
2401         dataMask |= object_get_datamask(scene, obedit);
2402
2403         if (!em->derivedCage ||
2404             (em->lastDataMask & dataMask) != dataMask)
2405         {
2406                 editbmesh_build_data(scene, obedit, em, dataMask);
2407         }
2408
2409         *final_r = em->derivedFinal;
2410         if (em->derivedFinal) { BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2411         return em->derivedCage;
2412 }
2413
2414 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2415 {
2416         /* if there's no derived mesh or the last data mask used doesn't include
2417          * the data we need, rebuild the derived mesh
2418          */
2419         dataMask |= object_get_datamask(scene, obedit);
2420
2421         if (!em->derivedCage ||
2422             (em->lastDataMask & dataMask) != dataMask)
2423         {
2424                 editbmesh_build_data(scene, obedit, em, dataMask);
2425         }
2426
2427         return em->derivedCage;
2428 }
2429
2430 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2431 {
2432         return getEditDerivedBMesh(em, obedit, NULL);
2433 }
2434
2435
2436 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2437
2438 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2439                                        const float no_f[3], const short no_s[3])
2440 {
2441         DMCoNo *co_no = &((DMCoNo *)userData)[index];
2442
2443         /* check if we've been here before (normal should not be 0) */
2444         if (!is_zero_v3(co_no->no)) {
2445                 return;
2446         }
2447
2448         copy_v3_v3(co_no->co, co);
2449         if (no_f) {
2450                 copy_v3_v3(co_no->no, no_f);
2451         }
2452         else {
2453                 normal_short_to_float_v3(co_no->no, no_s);
2454         }
2455 }
2456
2457 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2458 /* this is needed for all code using vertexgroups (no subsurf support) */
2459 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2460 /* in use now by vertex/weight paint and particle generating */
2461
2462 DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2463 {
2464         Mesh *me = ob->data;
2465         DerivedMesh *dm;
2466         DMCoNo *vertexcosnos;
2467         
2468         /* lets prevent crashing... */
2469         if (ob->type != OB_MESH || me->totvert == 0)
2470                 return NULL;
2471         
2472         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2473         
2474         if (dm->foreachMappedVert) {
2475                 vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2476                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2477         }
2478         else {
2479                 DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2480                 int a;
2481                 for (a = 0; a < me->totvert; a++, v_co_no++) {
2482                         dm->getVertCo(dm, a, v_co_no->co);
2483                         dm->getVertNo(dm, a, v_co_no->no);
2484                 }
2485         }
2486         
2487         dm->release(dm);
2488         return vertexcosnos;
2489 }
2490
2491 /* ******************* GLSL ******************** */
2492
2493 typedef struct {
2494         float *precomputedFaceNormals;
2495         MTFace *mtface;     /* texture coordinates */
2496         MFace *mface;       /* indices */
2497         MVert *mvert;       /* vertices & normals */
2498         float (*orco)[3];
2499         float (*tangent)[4];    /* destination */
2500         int numTessFaces;
2501
2502 } SGLSLMeshToTangent;
2503
2504 /* interface */
2505 #include "mikktspace.h"
2506
2507 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2508 {
2509         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2510         return pMesh->numTessFaces;
2511 }
2512
2513 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2514 {
2515         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2516         return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2517 }
2518
2519 static void GetPosition(const SMikkTSpaceContext *pContext, float r_co[3], const int face_num, const int vert_index)
2520 {
2521         //assert(vert_index >= 0 && vert_index < 4);
2522         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2523         const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2524         copy_v3_v3(r_co, co);
2525 }
2526
2527 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_num, const int vert_index)
2528 {
2529         //assert(vert_index >= 0 && vert_index < 4);
2530         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2531
2532         if (pMesh->mtface != NULL) {
2533                 const float *uv = pMesh->mtface[face_num].uv[vert_index];
2534                 copy_v2_v2(r_uv, uv);
2535         }
2536         else {
2537                 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2538                 map_to_sphere(&r_uv[0], &r_uv[1], orco[0], orco[1], orco[2]);
2539         }
2540 }
2541
2542 static void GetNormal(const SMikkTSpaceContext *pContext, float r_no[3], const int face_num, const int vert_index)
2543 {
2544         //assert(vert_index >= 0 && vert_index < 4);
2545         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2546
2547         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2548         if (!smoothnormal) {    // flat
2549                 if (pMesh->precomputedFaceNormals) {
2550                         copy_v3_v3(r_no, &pMesh->precomputedFaceNormals[3 * face_num]);
2551                 }
2552                 else {
2553                         MFace *mf = &pMesh->mface[face_num];
2554                         const float *p0 = pMesh->mvert[mf->v1].co;
2555                         const float *p1 = pMesh->mvert[mf->v2].co;
2556                         const float *p2 = pMesh->mvert[mf->v3].co;
2557
2558                         if (mf->v4) {
2559                                 const float *p3 = pMesh->mvert[mf->v4].co;
2560                                 normal_quad_v3(r_no, p0, p1, p2, p3);
2561                         }
2562                         else {
2563                                 normal_tri_v3(r_no, p0, p1, p2);
2564                         }
2565                 }
2566         }
2567         else {
2568                 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2569                 normal_short_to_float_v3(r_no, no);
2570         }
2571 }
2572 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[3], const float fSign, const int face_num, const int iVert)
2573 {
2574         //assert(vert_index >= 0 && vert_index < 4);
2575         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2576         float *pRes = pMesh->tangent[4 * face_num + iVert];
2577         copy_v3_v3(pRes, fvTangent);
2578         pRes[3] = fSign;
2579 }
2580
2581
2582 void DM_add_tangent_layer(DerivedMesh *dm)
2583 {
2584         /* mesh vars */
2585         MVert *mvert;
2586         MTFace *mtface;
2587         MFace *mface;
2588         float (*orco)[3] = NULL, (*tangent)[4];
2589         int /* totvert, */ totface;
2590         float *nors;
2591
2592         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2593                 return;
2594
2595         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2596
2597         /* check we have all the needed layers */
2598         /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
2599         totface = dm->getNumTessFaces(dm);
2600
2601         mvert = dm->getVertArray(dm);
2602         mface = dm->getTessFaceArray(dm);
2603         mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2604
2605         if (!mtface) {
2606                 orco = dm->getVertDataArray(dm, CD_ORCO);
2607                 if (!orco)
2608                         return;
2609         }
2610         
2611         /* create tangent layer */
2612         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2613         tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2614         
2615         /* new computation method */
2616         {
2617                 SGLSLMeshToTangent mesh2tangent = {0};
2618                 SMikkTSpaceContext sContext = {0};
2619                 SMikkTSpaceInterface sInterface = {0};
2620
2621                 mesh2tangent.precomputedFaceNormals = nors;
2622                 mesh2tangent.mtface = mtface;
2623                 mesh2tangent.mface = mface;
2624                 mesh2tangent.mvert = mvert;
2625                 mesh2tangent.orco = orco;
2626                 mesh2tangent.tangent = tangent;
2627                 mesh2tangent.numTessFaces = totface;
2628
2629                 sContext.m_pUserData = &mesh2tangent;
2630                 sContext.m_pInterface = &sInterface;
2631                 sInterface.m_getNumFaces = GetNumFaces;
2632                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2633                 sInterface.m_getPosition = GetPosition;
2634                 sInterface.m_getTexCoord = GetTextureCoordinate;
2635                 sInterface.m_getNormal = GetNormal;
2636                 sInterface.m_setTSpaceBasic = SetTSpace;
2637
2638                 /* 0 if failed */
2639                 genTangSpaceDefault(&sContext);
2640         }
2641 }
2642
2643 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2644 {
2645         /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
2646         int totface = dm->getNumTessFaces(dm);
2647
2648         MVert *mvert = dm->getVertArray(dm);
2649         MFace *mface = dm->getTessFaceArray(dm);
2650         MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2651
2652         if (mtface) {
2653                 double dsum = 0.0;
2654                 int nr_accumulated = 0;
2655                 int f;
2656
2657                 for (f = 0; f < totface; f++) {
2658                         {
2659                                 float *verts[4], *tex_coords[4];
2660                                 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2661                                 int i, is_degenerate;
2662
2663                                 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2664                                 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2665                                 if (nr_verts == 4) {
2666                                         verts[3] = mvert[mface[f].v4].co;
2667                                         tex_coords[3] = mtface[f].uv[3];
2668                                 }
2669
2670                                 /* discard degenerate faces */
2671                                 is_degenerate = 0;
2672                                 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2673                                     equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2674                                 {
2675                                         is_degenerate = 1;
2676                                 }
2677
2678                                 /* verify last vertex as well if this is a quad */
2679                                 if (is_degenerate == 0 && nr_verts == 4) {
2680                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2681                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2682                                         {
2683                                                 is_degenerate = 1;
2684                                         }
2685
2686                                         /* verify the winding is consistent */
2687                                         if (is_degenerate == 0) {
2688                                                 float prev_edge[2];
2689                                                 int is_signed = 0;
2690                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2691
2692                                                 i = 0;
2693                                                 while (is_degenerate == 0 && i < 4) {
2694                                                         float cur_edge[2], signed_area;
2695                                                         sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2696                                                         signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2697
2698                                                         if (i == 0) {
2699                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2700                                                         }
2701                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2702                                                                 is_degenerate = 1;
2703                                                         }
2704
2705                                                         if (is_degenerate == 0) {
2706                                                                 copy_v2_v2(prev_edge, cur_edge);
2707                                                                 i++;
2708                                                         }
2709                                                 }
2710                                         }
2711                                 }
2712
2713                                 /* proceed if not a degenerate face */
2714                                 if (is_degenerate == 0) {
2715                                         int nr_tris_to_pile = 0;
2716                                         /* quads split at shortest diagonal */
2717                                         int offs = 0;  /* initial triangulation is 0,1,2 and 0, 2, 3 */
2718                                         if (nr_verts == 4) {
2719                                                 float pos_len_diag0, pos_len_diag1;
2720                                                 float vtmp[3];
2721                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2722                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2723                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2724                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2725
2726                                                 if (pos_len_diag1 < pos_len_diag0) {
2727                                                         offs = 1;     // alter split
2728                                                 }
2729                                                 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2730                                                         float tex_len_diag0, tex_len_diag1;
2731
2732                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2733                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2734                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2735                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2736
2737                                                         if (tex_len_diag1 < tex_len_diag0) {
2738                                                                 offs = 1; /* alter split */
2739                                                         }
2740                                                 }
2741                                         }
2742                                         nr_tris_to_pile = nr_verts - 2;
2743                                         if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2744                                                 const int indices[] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2745                                                 int t;
2746                                                 for (t = 0; t < nr_tris_to_pile; t++) {
2747                                                         float f2x_area_uv;
2748                                                         float *p0 = verts[indices[t * 3 + 0]];
2749                                                         float *p1 = verts[indices[t * 3 + 1]];
2750                                                         float *p2 = verts[indices[t * 3 + 2]];
2751
2752                                                         float edge_t0[2], edge_t1[2];
2753                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2754                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2755
2756                                                         f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2757                                                         if (f2x_area_uv > FLT_EPSILON) {
2758                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2759                                                                 sub_v3_v3v3(v0, p1, p0);
2760                                                                 sub_v3_v3v3(v1, p2, p0);
2761                                                                 cross_v3_v3v3(norm, v0, v1);
2762
2763                                                                 f2x_surf_area = len_v3(norm);
2764                                                                 fsurf_ratio = f2x_surf_area / f2x_area_uv;    // tri area divided by texture area
2765
2766                                                                 nr_accumulated++;
2767                                                                 dsum += (double)(fsurf_ratio);
2768                                                         }
2769                                                 }
2770                                         }
2771                                 }
2772                         }
2773                 }
2774
2775                 /* finalize */
2776                 {
2777                         const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2778                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
2779                         dm->auto_bump_scale = use_as_render_bump_scale;
2780                 }
2781         }
2782         else {
2783                 dm->auto_bump_scale = 1.0f;
2784         }
2785 }
2786
2787 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2788 {
2789         CustomData *vdata, *fdata, *tfdata = NULL;
2790         int a, b, layer;
2791
2792         /* From the layers requested by the GLSL shader, figure out which ones are
2793          * actually available for this derivedmesh, and retrieve the pointers */
2794
2795         memset(attribs, 0, sizeof(DMVertexAttribs));
2796
2797         vdata = &dm->vertData;
2798         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2799         
2800         /* calc auto bump scale if necessary */
2801         if (dm->auto_bump_scale <= 0.0f)
2802                 DM_calc_auto_bump_scale(dm);
2803
2804         /* add a tangent layer if necessary */
2805         for (b = 0; b < gattribs->totlayer; b++)
2806                 if (gattribs->layer[b].type == CD_TANGENT)
2807                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2808                                 DM_add_tangent_layer(dm);
2809
2810         for (b = 0; b < gattribs->totlayer; b++) {
2811                 if (gattribs->layer[b].type == CD_MTFACE) {
2812                         /* uv coordinates */
2813                         if (dm->type == DM_TYPE_EDITBMESH) {
2814                                 /* exception .. */
2815                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2816
2817                                 if (gattribs->layer[b].name[0])
2818                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2819                                                                                  gattribs->layer[b].name);
2820                                 else
2821                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2822
2823                                 if (layer != -1) {
2824                                         a = attribs->tottface++;
2825
2826                                         attribs->tface[a].array = tfdata->layers[layer].data;
2827                                         attribs->tface[a].em_offset = ldata->layers[layer].offset;
2828                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2829                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2830                                 }
2831                         }
2832                         else {
2833                                 if (gattribs->layer[b].name[0])
2834                                         layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2835                                                                                  gattribs->layer[b].name);
2836                                 else
2837                                         layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2838
2839                                 if (layer != -1) {
2840                                         a = attribs->tottface++;
2841
2842                                         attribs->tface[a].array = tfdata->layers[layer].data;
2843                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2844                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2845                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2846                                 }
2847                         }
2848                 }
2849                 else if (gattribs->layer[b].type == CD_MCOL) {
2850                         if (dm->type == DM_TYPE_EDITBMESH) {
2851                                 /* exception .. */
2852                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2853
2854                                 if (gattribs->layer[b].name[0])
2855                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
2856                                                                                  gattribs->layer[b].name);
2857                                 else
2858                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
2859
2860                                 if (layer != -1) {
2861                                         a = attribs->totmcol++;
2862
2863                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2864                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
2865                                         attribs->mcol[a].em_offset = ldata->layers[layer].offset;
2866                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2867                                 }
2868                         }
2869                         else {
2870                                 /* vertex colors */
2871                                 if (gattribs->layer[b].name[0])
2872                                         layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2873                                                                                  gattribs->layer[b].name);
2874                                 else
2875                                         layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2876
2877                                 if (layer != -1) {
2878                                         a = attribs->totmcol++;
2879
2880                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2881                                         /* odd, store the offset for a different layer type here, but editmode draw code expects it */
2882                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2883                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2884                                 }
2885                         }
2886                 }
2887                 else if (gattribs->layer[b].type == CD_TANGENT) {
2888                         /* tangents */
2889                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2890
2891                         if (layer != -1) {
2892                                 attribs->tottang = 1;
2893
2894                                 attribs->tang.array = fdata->layers[layer].data;
2895                                 attribs->tang.em_offset = fdata->layers[layer].offset;
2896                                 attribs->tang.gl_index = gattribs->layer[b].glindex;
2897                         }
2898                 }
2899                 else if (gattribs->layer[b].type == CD_ORCO) {
2900                         /* original coordinates */
2901                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2902
2903                         if (layer != -1) {
2904                                 attribs->totorco = 1;
2905
2906                                 attribs->orco.array = vdata->layers[layer].data;
2907                                 attribs->orco.em_offset = vdata->layers[layer].offset;
2908                                 attribs->orco.gl_index = gattribs->layer[b].glindex;
2909                                 attribs->orco.gl_texco = gattribs->layer[b].gltexco;
2910                         }
2911                 }
2912         }
2913 }
2914
2915 /* Set object's bounding box based on DerivedMesh min/max data */
2916 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2917 {
2918         float min[3], max[3];
2919
2920         INIT_MINMAX(min, max);
2921
2922         dm->getMinMax(dm, min, max);
2923
2924         if (!ob->bb)
2925                 ob->bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2926
2927         BKE_boundbox_init_from_minmax(ob->bb, min, max);
2928 }
2929
2930 /* --- NAVMESH (begin) --- */
2931 #ifdef WITH_GAMEENGINE
2932
2933 /* BMESH_TODO, navmesh is not working right currently
2934  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2935  *
2936  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2937  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2938  * data from the original me->mpoly layer. - campbell
2939  */
2940
2941
2942 BLI_INLINE int navmesh_bit(int a, int b)
2943 {
2944         return (a & (1 << b)) >> b;
2945 }
2946
2947 BLI_INLINE void navmesh_intToCol(int i, float col[3])
2948 {
2949         int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2950         int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2951         int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2952         col[0] = 1 - r * 63.0f / 255.0f;
2953         col[1] = 1 - g * 63.0f / 255.0f;
2954         col[2] = 1 - b * 63.0f / 255.0f;
2955 }
2956
2957 static void navmesh_drawColored(DerivedMesh *dm)
2958 {
2959         int a, glmode;
2960         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2961         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2962         int *polygonIdx = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
2963         float col[3];
2964
2965         if (!polygonIdx)
2966                 return;
2967
2968 #if 0
2969         //UI_ThemeColor(TH_WIRE);
2970         glDisable(GL_LIGHTING);
2971         glLineWidth(2.0);
2972         dm->drawEdges(dm, 0, 1);
2973         glLineWidth(1.0);
2974         glEnable(GL_LIGHTING);
2975 #endif
2976
2977         glDisable(GL_LIGHTING);
2978         /* if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2979                 DEBUG_VBO("Using legacy code. drawNavMeshColored\n");
2980                 //glShadeModel(GL_SMOOTH);
2981                 glBegin(glmode = GL_QUADS);
2982                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
2983                         int new_glmode = mface->v4 ? GL_QUADS : GL_TRIANGLES;
2984                         int pi = polygonIdx[a];
2985                         if (pi <= 0) {
2986                                 zero_v3(col);
2987                         }
2988                         else {
2989                                 navmesh_intToCol(pi, col);
2990                         }
2991
2992                         if (new_glmode != glmode) {
2993                                 glEnd();
2994                                 glBegin(glmode = new_glmode);
2995                         }
2996                         glColor3fv(col);
2997                         glVertex3fv(mvert[mface->v1].co);
2998                         glVertex3fv(mvert[mface->v2].co);
2999                         glVertex3fv(mvert[mface->v3].co);
3000                         if (mface->v4) {
3001                                 glVertex3fv(mvert[mface->v4].co);
3002                         }
3003                 }
3004                 glEnd();
3005         }
3006         glEnable(G