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