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