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