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