remove modifiers_indexInObject(), just call BLI_findindex directly.
[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_pbvh.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_linklist.h"
53
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)
861 {
862         BMIter iter;
863         BMVert *eve;
864         float *orco;
865         int a, totvert;
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         totvert = em->bm->totvert;
871         
872         orco = MEM_mallocN(sizeof(float) * 3 * totvert, "BMEditMesh Orco");
873
874         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
875         for (a = 0; eve; eve = BM_iter_step(&iter), a += 3) {
876                 copy_v3_v3(orco + a, eve->co);
877         }
878         
879         return orco;
880 }
881
882 /* orco custom data layer */
883 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
884 {
885         *free = 0;
886
887         if (layer == CD_ORCO) {
888                 /* get original coordinates */
889                 *free = 1;
890
891                 if (em)
892                         return (float(*)[3])get_editbmesh_orco_verts(em);
893                 else
894                         return (float(*)[3])BKE_mesh_orco_verts_get(ob);
895         }
896         else if (layer == CD_CLOTH_ORCO) {
897                 /* apply shape key for cloth, this should really be solved
898                  * by a more flexible customdata system, but not simple */
899                 if (!em) {
900                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
901                         KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
902
903                         if (kb->data)
904                                 return kb->data;
905                 }
906
907                 return NULL;
908         }
909
910         return NULL;
911 }
912
913 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
914 {
915         DerivedMesh *dm;
916         float (*orco)[3];
917         int free;
918
919         if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE);
920         else dm = CDDM_from_mesh(me, ob);
921
922         orco = get_orco_coords_dm(ob, em, layer, &free);
923
924         if (orco) {
925                 CDDM_apply_vert_coords(dm, orco);
926                 if (free) MEM_freeN(orco);
927         }
928
929         CDDM_calc_normals(dm);
930
931         return dm;
932 }
933
934 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
935                         DerivedMesh *orcodm, int layer)
936 {
937         float (*orco)[3], (*layerorco)[3];
938         int totvert, free;
939
940         totvert = dm->getNumVerts(dm);
941
942         if (orcodm) {
943                 orco = MEM_callocN(sizeof(float) * 3 * totvert, "dm orco");
944                 free = 1;
945
946                 if (orcodm->getNumVerts(orcodm) == totvert)
947                         orcodm->getVertCos(orcodm, orco);
948                 else
949                         dm->getVertCos(dm, orco);
950         }
951         else
952                 orco = get_orco_coords_dm(ob, em, layer, &free);
953
954         if (orco) {
955                 if (layer == CD_ORCO)
956                         BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
957
958                 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
959                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
960                         layerorco = DM_get_vert_data_layer(dm, layer);
961                 }
962
963                 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
964                 if (free) MEM_freeN(orco);
965         }
966 }
967
968 /* weight paint colors */
969
970 /* Something of a hack, at the moment deal with weightpaint
971  * by tucking into colors during modifier eval, only in
972  * wpaint mode. Works ok but need to make sure recalc
973  * happens on enter/exit wpaint.
974  */
975
976 void weight_to_rgb(float r_rgb[3], const float weight)
977 {
978         const float blend = ((weight / 2.0f) + 0.5f);
979
980         if (weight <= 0.25f) {    /* blue->cyan */
981                 r_rgb[0] = 0.0f;
982                 r_rgb[1] = blend * weight * 4.0f;
983                 r_rgb[2] = blend;
984         }
985         else if (weight <= 0.50f) {  /* cyan->green */
986                 r_rgb[0] = 0.0f;
987                 r_rgb[1] = blend;
988                 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
989         }
990         else if (weight <= 0.75f) {  /* green->yellow */
991                 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
992                 r_rgb[1] = blend;
993                 r_rgb[2] = 0.0f;
994         }
995         else if (weight <= 1.0f) {  /* yellow->red */
996                 r_rgb[0] = blend;
997                 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
998                 r_rgb[2] = 0.0f;
999         }
1000         else {
1001                 /* exceptional value, unclamped or nan,
1002                  * avoid uninitialized memory use */
1003                 r_rgb[0] = 1.0f;
1004                 r_rgb[1] = 0.0f;
1005                 r_rgb[2] = 1.0f;
1006         }
1007 }
1008
1009 /* draw_flag's for calc_weightpaint_vert_color */
1010 enum {
1011         CALC_WP_MULTIPAINT = (1 << 0),
1012         CALC_WP_AUTO_NORMALIZE = (1 << 1)
1013 };
1014
1015 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
1016 {
1017         float colf[4];
1018
1019         if (coba) {
1020                 do_colorband(coba, input, colf);
1021         }
1022         else {
1023                 weight_to_rgb(colf, input);
1024         }
1025
1026         /* don't use rgb_float_to_uchar() here because
1027          * the resulting float doesn't need 0-1 clamp check */
1028         r_col[0] = (unsigned char)(colf[0] * 255.0f);
1029         r_col[1] = (unsigned char)(colf[1] * 255.0f);
1030         r_col[2] = (unsigned char)(colf[2] * 255.0f);
1031         r_col[3] = 255;
1032 }
1033
1034
1035 static void calc_weightpaint_vert_color(
1036         unsigned char r_col[4],
1037         MDeformVert *dv, ColorBand *coba,
1038         const int defbase_tot, const int defbase_act,
1039         const char *defbase_sel, const int defbase_sel_tot,
1040         const int draw_flag)
1041 {
1042         float input = 0.0f;
1043         
1044         int make_black = FALSE;
1045
1046         if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1047                 int was_a_nonzero = FALSE;
1048                 unsigned int i;
1049
1050                 MDeformWeight *dw = dv->dw;
1051                 for (i = dv->totweight; i != 0; i--, dw++) {
1052                         /* in multipaint, get the average if auto normalize is inactive
1053                          * get the sum if it is active */
1054                         if (dw->def_nr < defbase_tot) {
1055                                 if (defbase_sel[dw->def_nr]) {
1056                                         if (dw->weight) {
1057                                                 input += dw->weight;
1058                                                 was_a_nonzero = TRUE;
1059                                         }
1060                                 }
1061                         }
1062                 }
1063
1064                 /* make it black if the selected groups have no weight on a vertex */
1065                 if (was_a_nonzero == FALSE) {
1066                         make_black = TRUE;
1067                 }
1068                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1069                         input /= defbase_sel_tot; /* get the average */
1070                 }
1071         }
1072         else {
1073                 /* default, non tricky behavior */
1074                 input = defvert_find_weight(dv, defbase_act);
1075         }
1076
1077         if (make_black) { /* TODO, theme color */
1078                 r_col[3] = 255;
1079                 r_col[2] = 0;
1080                 r_col[1] = 0;
1081                 r_col[0] = 0;
1082         }
1083         else {
1084                 CLAMP(input, 0.0f, 1.0f);
1085                 weightpaint_color(r_col, coba, input);
1086         }
1087 }
1088
1089 static ColorBand *stored_cb = NULL;
1090
1091 void vDM_ColorBand_store(ColorBand *coba)
1092 {
1093         stored_cb = coba;
1094 }
1095
1096 /* return an array of vertex weight colors, caller must free.
1097  *
1098  * note that we could save some memory and allocate RGB only but then we'd need to
1099  * re-arrange the colors when copying to the face since MCol has odd ordering,
1100  * so leave this as is - campbell */
1101 static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, ColorBand *coba)
1102 {
1103         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1104         int numVerts = dm->getNumVerts(dm);
1105         unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * numVerts * 4, "weightmap_v");
1106
1107         if (dv) {
1108                 unsigned char *wc = wtcol_v;
1109                 unsigned int i;
1110
1111                 /* variables for multipaint */
1112                 const int defbase_tot = BLI_countlist(&ob->defbase);
1113                 const int defbase_act = ob->actdef - 1;
1114
1115                 int defbase_sel_tot = 0;
1116                 char *defbase_sel = NULL;
1117
1118                 if (draw_flag & CALC_WP_MULTIPAINT) {
1119                         defbase_sel = BKE_objdef_selected_get(ob, defbase_tot, &defbase_sel_tot);
1120                 }
1121
1122                 for (i = numVerts; i != 0; i--, wc += 4, dv++) {
1123                         calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1124                 }
1125
1126                 if (defbase_sel) {
1127                         MEM_freeN(defbase_sel);
1128                 }
1129         }
1130         else {
1131                 int col_i;
1132                 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
1133                 fill_vn_i((int *)wtcol_v, numVerts, col_i);
1134         }
1135
1136         return wtcol_v;
1137 }
1138
1139 /* return an array of vertex weight colors from given weights, caller must free.
1140  *
1141  * note that we could save some memory and allocate RGB only but then we'd need to
1142  * re-arrange the colors when copying to the face since MCol has odd ordering,
1143  * so leave this as is - campbell */
1144 static unsigned char *calc_colors_from_weights_array(const int num, float *weights)
1145 {
1146         unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * num * 4, "weightmap_v");
1147         unsigned char *wc = wtcol_v;
1148         int i;
1149
1150         for (i = 0; i < num; i++, wc += 4, weights++)
1151                 weightpaint_color((unsigned char *) wc, NULL, *weights);
1152
1153         return wtcol_v;
1154 }
1155
1156 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1157                            float *weights, int num, const int *indices)
1158 {
1159         ColorBand *coba = stored_cb; /* warning, not a local var */
1160
1161         unsigned char *wtcol_v;
1162         unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1163         MLoop *mloop = dm->getLoopArray(dm), *ml;
1164         MPoly *mp = dm->getPolyArray(dm);
1165         int numVerts = dm->getNumVerts(dm);
1166         int totloop;
1167         int i, j;
1168
1169         /* Weights are given by caller. */
1170         if (weights) {
1171                 float *w = weights;
1172                 /* If indices is not NULL, it means we do not have weights for all vertices,
1173                  * so we must create them (and set them to zero)... */
1174                 if (indices) {
1175                         w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
1176                         i = num;
1177                         while (i--)
1178                                 w[indices[i]] = weights[i];
1179                 }
1180
1181                 /* Convert float weights to colors. */
1182                 wtcol_v = calc_colors_from_weights_array(numVerts, w);
1183
1184                 if (indices)
1185                         MEM_freeN(w);
1186         }
1187
1188         /* No weights given, take them from active vgroup(s). */
1189         else
1190                 wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
1191
1192         /* now add to loops, so the data can be passed through the modifier stack */
1193         /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1194         if (!wtcol_l) {
1195                 BLI_array_declare(wtcol_l);
1196                 totloop = 0;
1197                 for (i = 0; i < dm->numPolyData; i++, mp++) {
1198                         ml = mloop + mp->loopstart;
1199
1200                         BLI_array_grow_items(wtcol_l, mp->totloop);
1201                         for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
1202                                 copy_v4_v4_char((char *)&wtcol_l[totloop],
1203                                                 (char *)&wtcol_v[4 * ml->v]);
1204                         }
1205                 }
1206                 CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1207         }
1208         else {
1209                 totloop = 0;
1210                 for (i = 0; i < dm->numPolyData; i++, mp++) {
1211                         ml = mloop + mp->loopstart;
1212
1213                         for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
1214                                 copy_v4_v4_char((char *)&wtcol_l[totloop],
1215                                                 (char *)&wtcol_v[4 * ml->v]);
1216                         }
1217                 }
1218         }
1219         MEM_freeN(wtcol_v);
1220
1221         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1222 }
1223
1224
1225 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1226 {
1227         KeyBlock *kb;
1228         int i, j, tot;
1229         
1230         if (!me->key)
1231                 return;
1232         
1233         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1234         for (i = 0; i < tot; i++) {
1235                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1236                 float (*cos)[3], (*kbcos)[3];
1237                 
1238                 for (kb = me->key->block.first; kb; kb = kb->next) {
1239                         if (kb->uid == layer->uid)
1240                                 break;
1241                 }
1242                 
1243                 if (!kb) {
1244                         kb = BKE_keyblock_add(me->key, layer->name);
1245                         kb->uid = layer->uid;
1246                 }
1247                 
1248                 if (kb->data)
1249                         MEM_freeN(kb->data);
1250                 
1251                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1252                 kb->totelem = dm->numVertData;
1253
1254                 kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
1255                 if (kb->uid == actshape_uid) {
1256                         MVert *mvert = dm->getVertArray(dm);
1257                         
1258                         for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1259                                 copy_v3_v3(*kbcos, mvert->co);
1260                         }
1261                 }
1262                 else {
1263                         for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1264                                 copy_v3_v3(*kbcos, *cos);
1265                         }
1266                 }
1267         }
1268         
1269         for (kb = me->key->block.first; kb; kb = kb->next) {
1270                 if (kb->totelem != dm->numVertData) {
1271                         if (kb->data)
1272                                 MEM_freeN(kb->data);
1273                         
1274                         kb->totelem = dm->numVertData;
1275                         kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
1276                         fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1277                 }
1278         }
1279 }
1280
1281 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1282 {
1283         KeyBlock *kb;
1284         Key *key = me->key;
1285         int i;
1286         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1287
1288         if (!me->key)
1289                 return;
1290
1291         /* ensure we can use mesh vertex count for derived mesh custom data */
1292         if (me->totvert != dm->getNumVerts(dm)) {
1293                 fprintf(stderr,
1294                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1295                         __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1296                 return;
1297         }
1298
1299         for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1300                 int ci;
1301                 float *array;
1302
1303                 if (me->totvert != kb->totelem) {
1304                         fprintf(stderr,
1305                                 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1306                                 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1307                         array = MEM_callocN(shape_alloc_len, __func__);
1308                 }
1309                 else {
1310                         array = MEM_mallocN(shape_alloc_len, __func__);
1311                         memcpy(array, kb->data, shape_alloc_len);
1312                 }
1313
1314                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1315                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1316
1317                 dm->vertData.layers[ci].uid = kb->uid;
1318         }
1319 }
1320
1321 /* new value for useDeform -1  (hack for the gameengine):
1322  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1323  * - don't apply the key
1324  * - apply deform modifiers and input vertexco
1325  */
1326 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1327                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1328                                 int useRenderParams, int useDeform,
1329                                 int needMapping, CustomDataMask dataMask,
1330                                 int index, int useCache, int build_shapekey_layers)
1331 {
1332         Mesh *me = ob->data;
1333         ModifierData *firstmd, *md, *previewmd = NULL;
1334         CDMaskLink *datamasks, *curr;
1335         /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1336         CustomDataMask mask, nextmask, append_mask = CD_MASK_ORIGINDEX;
1337         float (*deformedVerts)[3] = NULL;
1338         DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1339         int numVerts = me->totvert;
1340         int required_mode;
1341         int isPrevDeform = FALSE;
1342         int skipVirtualArmature = (useDeform < 0);
1343         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1344         int has_multires = mmd != NULL, multires_applied = 0;
1345         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1346
1347         const int draw_flag = ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1348                                (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1349         /* Generic preview only in object mode! */
1350         const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1351 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1352         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1353 #endif
1354         const int do_final_wmcol = FALSE;
1355         int do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1356         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1357         const int do_mod_wmcol = do_init_wmcol;
1358
1359         ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1360         ModifierApplyFlag deform_app_flags = app_flags;
1361         if (useCache)
1362                 app_flags |= MOD_APPLY_USECACHE;
1363         if (useDeform)
1364                 deform_app_flags |= MOD_APPLY_USECACHE;
1365
1366         if (mmd && !mmd->sculptlvl)
1367                 has_multires = 0;
1368
1369         if (!skipVirtualArmature) {
1370                 firstmd = modifiers_getVirtualModifierList(ob);
1371         }
1372         else {
1373                 /* game engine exception */
1374                 firstmd = ob->modifiers.first;
1375                 if (firstmd && firstmd->type == eModifierType_Armature)
1376                         firstmd = firstmd->next;
1377         }
1378
1379         md = firstmd;
1380
1381         modifiers_clearErrors(ob);
1382
1383         if (useRenderParams) required_mode = eModifierMode_Render;
1384         else required_mode = eModifierMode_Realtime;
1385
1386         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1387         curr = datamasks;
1388
1389         if (do_mod_wmcol || do_mod_mcol) {
1390                 /* Find the last active modifier generating a preview, or NULL if none. */
1391                 /* XXX Currently, DPaint modifier just ignores this.
1392                  *     Needs a stupid hack...
1393                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1394                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1395         }
1396
1397         if (deform_r) *deform_r = NULL;
1398         *final_r = NULL;
1399
1400         if (useDeform) {
1401                 if (inputVertexCos)
1402                         deformedVerts = inputVertexCos;
1403                 
1404                 /* Apply all leading deforming modifiers */
1405                 for (; md; md = md->next, curr = curr->next) {
1406                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1407
1408                         md->scene = scene;
1409                         
1410                         if (!modifier_isEnabled(scene, md, required_mode)) continue;
1411                         if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1412
1413                         if (mti->type == eModifierTypeType_OnlyDeform) {
1414                                 if (!deformedVerts)
1415                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1416
1417                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1418                         }
1419                         else {
1420                                 break;
1421                         }
1422                         
1423                         /* grab modifiers until index i */
1424                         if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1425                                 break;
1426                 }
1427
1428                 /* Result of all leading deforming modifiers is cached for
1429                  * places that wish to use the original mesh but with deformed
1430                  * coordinates (vpaint, etc.)
1431                  */
1432                 if (deform_r) {
1433                         *deform_r = CDDM_from_mesh(me, ob);
1434                          
1435                         if (build_shapekey_layers)
1436                                 add_shapekey_layers(dm, me, ob);
1437                         
1438                         if (deformedVerts) {
1439                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1440                                 CDDM_calc_normals(*deform_r);
1441                         }
1442                 }
1443         }
1444         else {
1445                 /* default behavior for meshes */
1446                 if (inputVertexCos)
1447                         deformedVerts = inputVertexCos;
1448                 else
1449                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1450         }
1451
1452
1453         /* Now apply all remaining modifiers. If useDeform is off then skip
1454          * OnlyDeform ones. 
1455          */
1456         dm = NULL;
1457         orcodm = NULL;
1458         clothorcodm = NULL;
1459
1460         for (; md; md = md->next, curr = curr->next) {
1461                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1462
1463                 md->scene = scene;
1464
1465                 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1466                 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1467                 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1468                         modifier_setError(md, "Modifier requires original data, bad stack position");
1469                         continue;
1470                 }
1471                 if (sculpt_mode && (!has_multires || multires_applied)) {
1472                         int unsupported = 0;
1473
1474                         if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1475                                 unsupported |= mti->type != eModifierTypeType_OnlyDeform;
1476
1477                         unsupported |= md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0;
1478                         unsupported |= multires_applied;
1479
1480                         if (unsupported) {
1481                                 modifier_setError(md, "Not supported in sculpt mode");
1482                                 continue;
1483                         }
1484                 }
1485                 if (needMapping && !modifier_supportsMapping(md)) continue;
1486                 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1487
1488                 /* add an orco layer if needed by this modifier */
1489                 if (mti->requiredDataMask)
1490                         mask = mti->requiredDataMask(ob, md);
1491                 else
1492                         mask = 0;
1493
1494                 if (dm && (mask & CD_MASK_ORCO))
1495                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1496
1497                 /* How to apply modifier depends on (a) what we already have as
1498                  * a result of previous modifiers (could be a DerivedMesh or just
1499                  * deformed vertices) and (b) what type the modifier is.
1500                  */
1501
1502                 if (mti->type == eModifierTypeType_OnlyDeform) {
1503                         /* No existing verts to deform, need to build them. */
1504                         if (!deformedVerts) {
1505                                 if (dm) {
1506                                         /* Deforming a derived mesh, read the vertex locations
1507                                          * out of the mesh and deform them. Once done with this
1508                                          * run of deformers verts will be written back.
1509                                          */
1510                                         numVerts = dm->getNumVerts(dm);
1511                                         deformedVerts =
1512                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1513                                         dm->getVertCos(dm, deformedVerts);
1514                                 }
1515                                 else {
1516                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1517                                 }
1518                         }
1519
1520                         /* if this is not the last modifier in the stack then recalculate the normals
1521                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1522                         if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1523                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1524                                 if (dm && dm->type == DM_TYPE_CDDM) {
1525                                         CDDM_apply_vert_coords(dm, deformedVerts);
1526                                         CDDM_calc_normals(dm);
1527                                 }
1528                         }
1529
1530                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
1531                 }
1532                 else {
1533                         DerivedMesh *ndm;
1534
1535                         /* determine which data layers are needed by following modifiers */
1536                         if (curr->next)
1537                                 nextmask = curr->next->mask;
1538                         else
1539                                 nextmask = dataMask;
1540
1541                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1542                         if (dm) {
1543                                 if (deformedVerts) {
1544                                         DerivedMesh *tdm = CDDM_copy(dm);
1545                                         dm->release(dm);
1546                                         dm = tdm;
1547
1548                                         CDDM_apply_vert_coords(dm, deformedVerts);
1549                                         CDDM_calc_normals(dm);
1550                                 }
1551                         }
1552                         else {
1553                                 dm = CDDM_from_mesh(me, ob);
1554
1555                                 if (build_shapekey_layers)
1556                                         add_shapekey_layers(dm, me, ob);
1557
1558                                 if (deformedVerts) {
1559                                         CDDM_apply_vert_coords(dm, deformedVerts);
1560                                         CDDM_calc_normals(dm);
1561                                 }
1562
1563                                 if (do_init_wmcol)
1564                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1565
1566                                 /* Constructive modifiers need to have an origindex
1567                                  * otherwise they wont have anywhere to copy the data from.
1568                                  *
1569                                  * Also create ORIGINDEX data if any of the following modifiers
1570                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1571                                  * data by using generic DM_copy_vert_data() functions.
1572                                  */
1573                                 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1574                                         /* calc */
1575                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1576                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1577                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1578
1579                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1580                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1581                                         range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1582                                 }
1583                         }
1584
1585                         
1586                         /* set the DerivedMesh to only copy needed data */
1587                         mask = curr->mask;
1588                         /* needMapping check here fixes bug [#28112], otherwise its
1589                          * possible that it wont be copied */
1590                         mask |= append_mask;
1591                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1592                         
1593                         /* add cloth rest shape key if need */
1594                         if (mask & CD_MASK_CLOTH_ORCO)
1595                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1596
1597                         /* add an origspace layer if needed */
1598                         if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
1599                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1600                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1601                                         DM_init_origspace(dm);
1602                                 }
1603                         }
1604
1605                         ndm = mti->applyModifier(md, ob, dm, app_flags);
1606
1607                         if (ndm) {
1608                                 /* if the modifier returned a new dm, release the old one */
1609                                 if (dm && dm != ndm) dm->release(dm);
1610
1611                                 dm = ndm;
1612
1613                                 if (deformedVerts) {
1614                                         if (deformedVerts != inputVertexCos)
1615                                                 MEM_freeN(deformedVerts);
1616
1617                                         deformedVerts = NULL;
1618                                 }
1619                         }
1620
1621                         /* create an orco derivedmesh in parallel */
1622                         if (nextmask & CD_MASK_ORCO) {
1623                                 if (!orcodm)
1624                                         orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
1625
1626                                 nextmask &= ~CD_MASK_ORCO;
1627                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
1628                                                  (mti->requiredDataMask ?
1629                                                   mti->requiredDataMask(ob, md) : 0));
1630                                 ndm = mti->applyModifier(md, ob, orcodm, app_flags & ~MOD_APPLY_USECACHE);
1631
1632                                 if (ndm) {
1633                                         /* if the modifier returned a new dm, release the old one */
1634                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1635                                         orcodm = ndm;
1636                                 }
1637                         }
1638
1639                         /* create cloth orco derivedmesh in parallel */
1640                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1641                                 if (!clothorcodm)
1642                                         clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1643
1644                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1645                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1646                                 ndm = mti->applyModifier(md, ob, clothorcodm, app_flags & ~MOD_APPLY_USECACHE);
1647
1648                                 if (ndm) {
1649                                         /* if the modifier returned a new dm, release the old one */
1650                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1651                                         clothorcodm = ndm;
1652                                 }
1653                         }
1654
1655                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1656                         /* XXX Temp and hackish solution! */
1657                         if (md->type == eModifierType_DynamicPaint)
1658                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1659                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1660                         else if ((md == previewmd) && (do_mod_wmcol)) {
1661                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1662                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1663                         }
1664                 }
1665
1666                 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1667
1668                 /* grab modifiers until index i */
1669                 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1670                         break;
1671
1672                 if (sculpt_mode && md->type == eModifierType_Multires)
1673                         multires_applied = 1;
1674         }
1675
1676         for (md = firstmd; md; md = md->next)
1677                 modifier_freeTemporaryData(md);
1678
1679         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1680          * need to apply these back onto the DerivedMesh. If we have no
1681          * DerivedMesh then we need to build one.
1682          */
1683         if (dm && deformedVerts) {
1684                 finaldm = CDDM_copy(dm);
1685
1686                 dm->release(dm);
1687
1688                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1689                 CDDM_calc_normals(finaldm);
1690
1691 #if 0 /* For later nice mod preview! */
1692                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1693                 if (do_final_wmcol)
1694                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1695 #endif
1696         }
1697         else if (dm) {
1698                 finaldm = dm;
1699
1700 #if 0 /* For later nice mod preview! */
1701                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1702                 if (do_final_wmcol)
1703                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1704 #endif
1705         }
1706         else {
1707                 int recalc_normals = 0;
1708
1709                 finaldm = CDDM_from_mesh(me, ob);
1710                 
1711                 if (build_shapekey_layers) {
1712                         add_shapekey_layers(finaldm, me, ob);
1713                         recalc_normals = 1;
1714                 }
1715                 
1716                 if (deformedVerts) {
1717                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1718                         recalc_normals = 1;
1719                 }
1720
1721                 if (recalc_normals) {
1722                         CDDM_calc_normals(finaldm);
1723                 }
1724
1725                 /* In this case, we should never have weight-modifying modifiers in stack... */
1726                 if (do_init_wmcol)
1727                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1728         }
1729
1730         /* add an orco layer if needed */
1731         if (dataMask & CD_MASK_ORCO) {
1732                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1733
1734                 if (deform_r && *deform_r)
1735                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1736         }
1737
1738         {
1739                 /* calculating normals can re-calculate tessfaces in some cases */
1740 #if 0
1741                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1742 #endif
1743                 /* --------------------------------------------------------------------- */
1744                 /* First calculate the polygon and vertex normals, re-tessellation
1745                  * copies these into the tessface's normal layer */
1746
1747
1748                 /* comment because this causes a bug when deform is applied after a
1749                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1750                  * it also looks like this isn't even needed since code above recalc's
1751                  * normals - campbell */
1752 #if 0
1753                 finaldm->calcNormals(finaldm);
1754 #endif
1755
1756                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1757                  * from loops and polys onto the tessfaces. This may be currently be
1758                  * redundant in cases where the render mode doesn't use these inputs, but
1759                  * ideally eventually tessellation would happen on-demand, and this is one
1760                  * of the primary places it would be needed. */
1761 #if 0
1762                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
1763 #else
1764                 if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */
1765 #endif
1766                 {
1767                         finaldm->recalcTessellation(finaldm);
1768                 }
1769                 /* Even if tessellation is not needed, some modifiers might have modified CD layers
1770                  * (like mloopcol or mloopuv), hence we have to update those. */
1771                 else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
1772                         /* A tessellation already exists, it should always have a CD_ORIGINDEX. */
1773                         BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX));
1774                         DM_update_tessface_data(finaldm);
1775                 }
1776                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1777                 /* take care with this block, we really need testing frameworks          */
1778                 /* --------------------------------------------------------------------- */
1779
1780                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1781                  * normals and will also have to calculate normals on the fly, try avoid
1782                  * this where possible since calculating polygon normals isn't fast,
1783                  * note that this isn't a problem for subsurf (only quads) or editmode
1784                  * which deals with drawing differently.
1785                  *
1786                  * Never calc vertex normals because other code ensures these are up to date.
1787                  */
1788                 if ((finaldm->type == DM_TYPE_CDDM) && (CustomData_has_layer(&finaldm->faceData, CD_NORMAL) == FALSE)) {
1789                         CDDM_calc_normals_mapping_ex(finaldm, TRUE);
1790                 }
1791         }
1792
1793 #ifdef WITH_GAMEENGINE
1794         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1795         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1796                 DerivedMesh *tdm;
1797                 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1798                 if (finaldm != tdm) {
1799                         finaldm->release(finaldm);
1800                         finaldm = tdm;
1801                 }
1802         }
1803 #endif /* WITH_GAMEENGINE */
1804
1805         *final_r = finaldm;
1806
1807         if (orcodm)
1808                 orcodm->release(orcodm);
1809         if (clothorcodm)
1810                 clothorcodm->release(clothorcodm);
1811
1812         if (deformedVerts && deformedVerts != inputVertexCos)
1813                 MEM_freeN(deformedVerts);
1814
1815         BLI_linklist_free((LinkNode *)datamasks, NULL);
1816 }
1817
1818 float (*editbmesh_get_vertex_cos(BMEditMesh * em, int *numVerts_r))[3]
1819 {
1820         int i, numVerts = *numVerts_r = em->bm->totvert;
1821         float (*cos)[3];
1822         BMIter iter;
1823         BMVert *eve;
1824
1825         cos = MEM_mallocN(sizeof(float) * 3 * numVerts, "vertexcos");
1826
1827         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1828         for (i = 0; eve; eve = BM_iter_step(&iter), i++) {
1829                 copy_v3_v3(cos[i], eve->co);
1830         }
1831
1832         return cos;
1833 }
1834
1835 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1836 {
1837         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1838         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1839
1840         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1841         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1842                 modifier_setError(md, "Modifier requires original data, bad stack position");
1843                 return 0;
1844         }
1845         
1846         return 1;
1847 }
1848
1849 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1850                                      DerivedMesh **final_r,
1851                                      CustomDataMask dataMask)
1852 {
1853         ModifierData *md;
1854         float (*deformedVerts)[3] = NULL;
1855         CustomDataMask mask;
1856         DerivedMesh *dm, *orcodm = NULL;
1857         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1858         CDMaskLink *datamasks, *curr;
1859         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1860
1861         modifiers_clearErrors(ob);
1862
1863         if (cage_r && cageIndex == -1) {
1864                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1865         }
1866
1867         dm = NULL;
1868         md = modifiers_getVirtualModifierList(ob);
1869
1870         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1871
1872         curr = datamasks;
1873         for (i = 0; md; i++, md = md->next, curr = curr->next) {
1874                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1875
1876                 md->scene = scene;
1877                 
1878                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
1879                         continue;
1880
1881                 /* add an orco layer if needed by this modifier */
1882                 if (dm && mti->requiredDataMask) {
1883                         mask = mti->requiredDataMask(ob, md);
1884                         if (mask & CD_MASK_ORCO)
1885                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1886                 }
1887
1888                 /* How to apply modifier depends on (a) what we already have as
1889                  * a result of previous modifiers (could be a DerivedMesh or just
1890                  * deformed vertices) and (b) what type the modifier is.
1891                  */
1892
1893                 if (mti->type == eModifierTypeType_OnlyDeform) {
1894                         /* No existing verts to deform, need to build them. */
1895                         if (!deformedVerts) {
1896                                 if (dm) {
1897                                         /* Deforming a derived mesh, read the vertex locations
1898                                          * out of the mesh and deform them. Once done with this
1899                                          * run of deformers verts will be written back.
1900                                          */
1901                                         numVerts = dm->getNumVerts(dm);
1902                                         deformedVerts =
1903                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1904                                         dm->getVertCos(dm, deformedVerts);
1905                                 }
1906                                 else {
1907                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1908                                 }
1909                         }
1910
1911                         if (mti->deformVertsEM)
1912                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1913                         else
1914                                 mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
1915                 }
1916                 else {
1917                         DerivedMesh *ndm;
1918
1919                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1920                         if (dm) {
1921                                 if (deformedVerts) {
1922                                         DerivedMesh *tdm = CDDM_copy(dm);
1923                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
1924                                         dm = tdm;
1925
1926                                         CDDM_apply_vert_coords(dm, deformedVerts);
1927                                         CDDM_calc_normals(dm);
1928                                 }
1929                                 else if (cage_r && dm == *cage_r) {
1930                                         /* dm may be changed by this modifier, so we need to copy it
1931                                          */
1932                                         dm = CDDM_copy(dm);
1933                                 }
1934
1935                         }
1936                         else {
1937                                 dm = CDDM_from_editbmesh(em, FALSE, FALSE);
1938
1939                                 if (deformedVerts) {
1940                                         CDDM_apply_vert_coords(dm, deformedVerts);
1941                                         CDDM_calc_normals(dm);
1942                                 }
1943                         }
1944
1945                         /* create an orco derivedmesh in parallel */
1946                         mask = curr->mask;
1947                         if (mask & CD_MASK_ORCO) {
1948                                 if (!orcodm)
1949                                         orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
1950
1951                                 mask &= ~CD_MASK_ORCO;
1952                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1953
1954                                 if (mti->applyModifierEM)
1955                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1956                                 else
1957                                         ndm = mti->applyModifier(md, ob, orcodm, 0);
1958
1959                                 if (ndm) {
1960                                         /* if the modifier returned a new dm, release the old one */
1961                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1962                                         orcodm = ndm;
1963                                 }
1964                         }
1965
1966                         /* set the DerivedMesh to only copy needed data */
1967                         mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
1968
1969                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1970
1971                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
1972                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1973                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1974                                         DM_init_origspace(dm);
1975                                 }
1976                         }
1977                         
1978                         if (mti->applyModifierEM)
1979                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1980                         else
1981                                 ndm = mti->applyModifier(md, ob, dm, 0);
1982
1983                         if (ndm) {
1984                                 if (dm && dm != ndm)
1985                                         dm->release(dm);
1986
1987                                 dm = ndm;
1988
1989                                 if (deformedVerts) {
1990                                         MEM_freeN(deformedVerts);
1991                                         deformedVerts = NULL;
1992                                 }
1993                         }
1994                 }
1995
1996                 if (cage_r && i == cageIndex) {
1997                         if (dm && deformedVerts) {
1998                                 *cage_r = CDDM_copy(dm);
1999                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2000                         }
2001                         else if (dm) {
2002                                 *cage_r = dm;
2003                         }
2004                         else {
2005                                 *cage_r =
2006                                     getEditDerivedBMesh(em, ob,
2007                                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2008                         }
2009                 }
2010         }
2011
2012         BLI_linklist_free((LinkNode *)datamasks, NULL);
2013
2014         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2015          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2016          * then we need to build one.
2017          */
2018         if (dm && deformedVerts) {
2019                 *final_r = CDDM_copy(dm);
2020
2021                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2022
2023                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2024                 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
2025         }
2026         else if (dm) {
2027                 *final_r = dm;
2028
2029                 /* once we support skipping normal calculation with modifiers we may want to add this back */
2030 #if 0   // was added for bmesh but is not needed
2031                 (*final_r)->calcNormals(*final_r);
2032 #endif
2033         }
2034         else if (!deformedVerts && cage_r && *cage_r) {
2035                 /* cage should already have up to date normals */
2036                 *final_r = *cage_r;
2037 #if 0   // was added for bmesh but is not needed
2038                 (*final_r)->calcNormals(*final_r);
2039 #endif
2040         }
2041         else {
2042                 /* this is just a copy of the editmesh, no need to calc normals */
2043                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2044                 deformedVerts = NULL;
2045         }
2046
2047         /* --- */
2048         /* BMESH_ONLY, ensure tessface's used for drawing,
2049          * but don't recalculate if the last modifier in the stack gives us tessfaces
2050          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2051          * but quiets annoying error messages since tessfaces wont be created. */
2052         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2053                 DM_ensure_tessface(*final_r);
2054         }
2055         if (cage_r && *cage_r) {
2056                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2057                         if (*cage_r != *final_r) {
2058                                 DM_ensure_tessface(*cage_r);
2059                         }
2060                 }
2061         }
2062         /* --- */
2063
2064         /* add an orco layer if needed */
2065         if (dataMask & CD_MASK_ORCO)
2066                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2067
2068         if (orcodm)
2069                 orcodm->release(orcodm);
2070
2071         if (deformedVerts)
2072                 MEM_freeN(deformedVerts);
2073 }
2074
2075 static void clear_mesh_caches(Object *ob)
2076 {
2077         Mesh *me = ob->data;
2078
2079         /* also serves as signal to remake texspace */
2080         if (ob->bb) {
2081                 MEM_freeN(ob->bb);
2082                 ob->bb = NULL;
2083         }
2084         if (me->bb) {
2085                 MEM_freeN(me->bb);
2086                 me->bb = NULL;
2087         }
2088
2089         BKE_displist_free(&ob->disp);
2090
2091         if (ob->derivedFinal) {
2092                 ob->derivedFinal->needsFree = 1;
2093                 ob->derivedFinal->release(ob->derivedFinal);
2094                 ob->derivedFinal = NULL;
2095         }
2096         if (ob->derivedDeform) {
2097                 ob->derivedDeform->needsFree = 1;
2098                 ob->derivedDeform->release(ob->derivedDeform);
2099                 ob->derivedDeform = NULL;
2100         }
2101
2102         if (ob->sculpt) {
2103                 BKE_object_sculpt_modifiers_changed(ob);
2104         }
2105 }
2106
2107 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2108                             int build_shapekey_layers)
2109 {
2110         Object *obact = scene->basact ? scene->basact->object : NULL;
2111         int editing = paint_facesel_test(ob);
2112         /* weight paint and face select need original indices because of selection buffer drawing */
2113         int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2114
2115         BLI_assert(ob->type == OB_MESH);
2116
2117         clear_mesh_caches(ob);
2118
2119         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2120                             &ob->derivedFinal, 0, 1,
2121                             needMapping, dataMask, -1, 1, build_shapekey_layers);
2122
2123         DM_set_object_boundbox(ob, ob->derivedFinal);
2124
2125         ob->derivedFinal->needsFree = 0;
2126         ob->derivedDeform->needsFree = 0;
2127         ob->lastDataMask = dataMask;
2128
2129         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2130                 /* create PBVH immediately (would be created on the fly too,
2131                  * but this avoids waiting on first stroke) */
2132                 ob->sculpt->pbvh = ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2133         }
2134 }
2135
2136 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2137 {
2138         clear_mesh_caches(obedit);
2139
2140         if (em->derivedFinal) {
2141                 if (em->derivedFinal != em->derivedCage) {
2142                         em->derivedFinal->needsFree = 1;
2143                         em->derivedFinal->release(em->derivedFinal);
2144                 }
2145                 em->derivedFinal = NULL;
2146         }
2147         if (em->derivedCage) {
2148                 em->derivedCage->needsFree = 1;
2149                 em->derivedCage->release(em->derivedCage);
2150                 em->derivedCage = NULL;
2151         }
2152
2153         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2154         DM_set_object_boundbox(obedit, em->derivedFinal);
2155
2156         em->lastDataMask = dataMask;
2157         em->derivedFinal->needsFree = 0;
2158         em->derivedCage->needsFree = 0;
2159 }
2160
2161 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2162                      CustomDataMask dataMask, int build_shapekey_layers)
2163 {
2164         if (em) {
2165                 editbmesh_build_data(scene, ob, em, dataMask);
2166         }
2167         else {
2168                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2169         }
2170 }
2171
2172 /***/
2173
2174 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2175 {
2176         /* if there's no derived mesh or the last data mask used doesn't include
2177          * the data we need, rebuild the derived mesh
2178          */
2179         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2180                 mesh_build_data(scene, ob, dataMask, 0);
2181
2182         return ob->derivedFinal;
2183 }
2184
2185 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2186 {
2187         /* if there's no derived mesh or the last data mask used doesn't include
2188          * the data we need, rebuild the derived mesh
2189          */
2190         if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2191                 mesh_build_data(scene, ob, dataMask, 0);
2192
2193         return ob->derivedDeform;
2194 }
2195
2196 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2197 {
2198         DerivedMesh *final;
2199         
2200         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2201
2202         return final;
2203 }
2204
2205 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2206 {
2207         DerivedMesh *final;
2208         
2209         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2210
2211         return final;
2212 }
2213
2214 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2215 {
2216         DerivedMesh *final;
2217
2218         /* XXX hack
2219          * psys modifier updates particle state when called during dupli-list generation,
2220          * which can lead to wrong transforms. This disables particle system modifier execution.
2221          */
2222         ob->transflag |= OB_NO_PSYS_UPDATE;
2223
2224         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2225
2226         ob->transflag &= ~OB_NO_PSYS_UPDATE;
2227
2228         return final;
2229 }
2230
2231 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2232                                            CustomDataMask dataMask)
2233 {
2234         DerivedMesh *final;
2235         
2236         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2237
2238         return final;
2239 }
2240
2241 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2242                                             CustomDataMask dataMask)
2243 {
2244         DerivedMesh *final;
2245         
2246         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2247
2248         return final;
2249 }
2250
2251 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2252                                          CustomDataMask dataMask)
2253 {
2254         DerivedMesh *final;
2255         
2256         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2257
2258         return final;
2259 }
2260
2261 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2262                                                   float (*vertCos)[3],
2263                                                   CustomDataMask dataMask)
2264 {
2265         DerivedMesh *final;
2266
2267         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2268
2269         return final;
2270 }
2271
2272 /***/
2273
2274 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2275                                                   CustomDataMask dataMask)
2276 {
2277         /* if there's no derived mesh or the last data mask used doesn't include
2278          * the data we need, rebuild the derived mesh
2279          */
2280         if (!em->derivedCage ||
2281             (em->lastDataMask & dataMask) != dataMask)
2282         {
2283                 editbmesh_build_data(scene, obedit, em, dataMask);
2284         }
2285
2286         *final_r = em->derivedFinal;
2287         return em->derivedCage;
2288 }
2289
2290 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2291 {
2292         /* if there's no derived mesh or the last data mask used doesn't include
2293          * the data we need, rebuild the derived mesh
2294          */
2295         if (!em->derivedCage ||
2296             (em->lastDataMask & dataMask) != dataMask)
2297         {
2298                 editbmesh_build_data(scene, obedit, em, dataMask);
2299         }
2300
2301         return em->derivedCage;
2302 }
2303
2304 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2305 {
2306         return getEditDerivedBMesh(em, obedit, NULL);
2307 }
2308
2309
2310 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2311
2312 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2313                                        const float no_f[3], const short no_s[3])
2314 {
2315         float *vec = userData;
2316         
2317         vec += 6 * index;
2318
2319         /* check if we've been here before (normal should not be 0) */
2320         if (vec[3] || vec[4] || vec[5]) return;
2321
2322         copy_v3_v3(vec, co);
2323         vec += 3;
2324         if (no_f) {
2325                 copy_v3_v3(vec, no_f);
2326         }
2327         else {
2328                 normal_short_to_float_v3(vec, no_s);
2329         }
2330 }
2331
2332 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2333 /* this is needed for all code using vertexgroups (no subsurf support) */
2334 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2335 /* in use now by vertex/weight paint and particle generating */
2336
2337 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2338 {
2339         Mesh *me = ob->data;
2340         DerivedMesh *dm;
2341         float *vertexcosnos;
2342         
2343         /* lets prevent crashing... */
2344         if (ob->type != OB_MESH || me->totvert == 0)
2345                 return NULL;
2346         
2347         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2348         vertexcosnos = MEM_callocN(6 * sizeof(float) * me->totvert, "vertexcosnos map");
2349         
2350         if (dm->foreachMappedVert) {
2351                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2352         }
2353         else {
2354                 float *fp = vertexcosnos;
2355                 int a;
2356                 
2357                 for (a = 0; a < me->totvert; a++, fp += 6) {
2358                         dm->getVertCo(dm, a, fp);
2359                         dm->getVertNo(dm, a, fp + 3);
2360                 }
2361         }
2362         
2363         dm->release(dm);
2364         return vertexcosnos;
2365 }
2366
2367 /* ******************* GLSL ******************** */
2368
2369 typedef struct {
2370         float *precomputedFaceNormals;
2371         MTFace *mtface;     /* texture coordinates */
2372         MFace *mface;       /* indices */
2373         MVert *mvert;       /* vertices & normals */
2374         float (*orco)[3];
2375         float (*tangent)[4];    /* destination */
2376         int numTessFaces;
2377
2378 } SGLSLMeshToTangent;
2379
2380 /* interface */
2381 #include "mikktspace.h"
2382
2383 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2384 {
2385         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2386         return pMesh->numTessFaces;
2387 }
2388
2389 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2390 {
2391         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2392         return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2393 }
2394
2395 static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const int face_num, const int vert_index)
2396 {
2397         //assert(vert_index >= 0 && vert_index < 4);
2398         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2399         const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2400         copy_v3_v3(fPos, co);
2401 }
2402
2403 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[], const int face_num, const int vert_index)
2404 {
2405         //assert(vert_index >= 0 && vert_index < 4);
2406         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2407
2408         if (pMesh->mtface != NULL) {
2409                 float *uv = pMesh->mtface[face_num].uv[vert_index];
2410                 fUV[0] = uv[0]; fUV[1] = uv[1];
2411         }
2412         else {
2413                 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2414                 map_to_sphere(&fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2415         }
2416 }
2417
2418 static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const int face_num, const int vert_index)
2419 {
2420         //assert(vert_index >= 0 && vert_index < 4);
2421         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2422
2423         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2424         if (!smoothnormal) {    // flat
2425                 if (pMesh->precomputedFaceNormals) {
2426                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3 * face_num]);
2427                 }
2428                 else {
2429                         MFace *mf = &pMesh->mface[face_num];
2430                         float *p0 = pMesh->mvert[mf->v1].co;
2431                         float *p1 = pMesh->mvert[mf->v2].co;
2432                         float *p2 = pMesh->mvert[mf->v3].co;
2433
2434                         if (mf->v4) {
2435                                 float *p3 = pMesh->mvert[mf->v4].co;
2436                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2437                         }
2438                         else {
2439                                 normal_tri_v3(fNorm, p0, p1, p2);
2440                         }
2441                 }
2442         }
2443         else {
2444                 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2445                 normal_short_to_float_v3(fNorm, no);
2446         }
2447 }
2448 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2449 {
2450         //assert(vert_index >= 0 && vert_index < 4);
2451         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2452         float *pRes = pMesh->tangent[4 * face_num + iVert];
2453         copy_v3_v3(pRes, fvTangent);
2454         pRes[3] = fSign;
2455 }
2456
2457
2458 void DM_add_tangent_layer(DerivedMesh *dm)
2459 {
2460         /* mesh vars */
2461         MVert *mvert;
2462         MTFace *mtface;
2463         MFace *mface;
2464         float (*orco)[3] = NULL, (*tangent)[4];
2465         int /* totvert, */ totface;
2466         float *nors;
2467
2468         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2469                 return;
2470
2471         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2472
2473         /* check we have all the needed layers */
2474         /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
2475         totface = dm->getNumTessFaces(dm);
2476
2477         mvert = dm->getVertArray(dm);
2478         mface = dm->getTessFaceArray(dm);
2479         mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2480
2481         if (!mtface) {
2482                 orco = dm->getVertDataArray(dm, CD_ORCO);
2483                 if (!orco)
2484                         return;
2485         }
2486         
2487         /* create tangent layer */
2488         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2489         tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2490         
2491         /* new computation method */
2492         {
2493                 SGLSLMeshToTangent mesh2tangent = {0};
2494                 SMikkTSpaceContext sContext = {0};
2495                 SMikkTSpaceInterface sInterface = {0};
2496
2497                 mesh2tangent.precomputedFaceNormals = nors;
2498                 mesh2tangent.mtface = mtface;
2499                 mesh2tangent.mface = mface;
2500                 mesh2tangent.mvert = mvert;
2501                 mesh2tangent.orco = orco;
2502                 mesh2tangent.tangent = tangent;
2503                 mesh2tangent.numTessFaces = totface;
2504
2505                 sContext.m_pUserData = &mesh2tangent;
2506                 sContext.m_pInterface = &sInterface;
2507                 sInterface.m_getNumFaces = GetNumFaces;
2508                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2509                 sInterface.m_getPosition = GetPosition;
2510                 sInterface.m_getTexCoord = GetTextureCoordinate;
2511                 sInterface.m_getNormal = GetNormal;
2512                 sInterface.m_setTSpaceBasic = SetTSpace;
2513
2514                 /* 0 if failed */
2515                 genTangSpaceDefault(&sContext);
2516         }
2517 }
2518
2519 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2520 {
2521         /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
2522         int totface = dm->getNumTessFaces(dm);
2523
2524         MVert *mvert = dm->getVertArray(dm);
2525         MFace *mface = dm->getTessFaceArray(dm);
2526         MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2527
2528         if (mtface) {
2529                 double dsum = 0.0;
2530                 int nr_accumulated = 0;
2531                 int f;
2532
2533                 for (f = 0; f < totface; f++) {
2534                         {
2535                                 float *verts[4], *tex_coords[4];
2536                                 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2537                                 int i, is_degenerate;
2538
2539                                 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2540                                 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2541                                 if (nr_verts == 4) {
2542                                         verts[3] = mvert[mface[f].v4].co;
2543                                         tex_coords[3] = mtface[f].uv[3];
2544                                 }
2545
2546                                 /* discard degenerate faces */
2547                                 is_degenerate = 0;
2548                                 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2549                                     equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2550                                 {
2551                                         is_degenerate = 1;
2552                                 }
2553
2554                                 /* verify last vertex as well if this is a quad */
2555                                 if (is_degenerate == 0 && nr_verts == 4) {
2556                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2557                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2558                                         {
2559                                                 is_degenerate = 1;
2560                                         }
2561
2562                                         /* verify the winding is consistent */
2563                                         if (is_degenerate == 0) {
2564                                                 float prev_edge[2];
2565                                                 int is_signed = 0;
2566                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2567
2568                                                 i = 0;
2569                                                 while (is_degenerate == 0 && i < 4) {
2570                                                         float cur_edge[2], signed_area;
2571                                                         sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2572                                                         signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2573
2574                                                         if (i == 0) {
2575                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2576                                                         }
2577                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2578                                                                 is_degenerate = 1;
2579                                                         }
2580
2581                                                         if (is_degenerate == 0) {
2582                                                                 copy_v2_v2(prev_edge, cur_edge);
2583                                                                 i++;
2584                                                         }
2585                                                 }
2586                                         }
2587                                 }
2588
2589                                 /* proceed if not a degenerate face */
2590                                 if (is_degenerate == 0) {
2591                                         int nr_tris_to_pile = 0;
2592                                         /* quads split at shortest diagonal */
2593                                         int offs = 0;  /* initial triangulation is 0,1,2 and 0, 2, 3 */
2594                                         if (nr_verts == 4) {
2595                                                 float pos_len_diag0, pos_len_diag1;
2596                                                 float vtmp[3];
2597                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2598                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2599                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2600                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2601
2602                                                 if (pos_len_diag1 < pos_len_diag0) {
2603                                                         offs = 1;     // alter split
2604                                                 }
2605                                                 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2606                                                         float tex_len_diag0, tex_len_diag1;
2607
2608                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2609                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2610                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2611                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2612
2613                                                         if (tex_len_diag1 < tex_len_diag0) {
2614                                                                 offs = 1; /* alter split */
2615                                                         }
2616                                                 }
2617                                         }
2618                                         nr_tris_to_pile = nr_verts - 2;
2619                                         if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2620                                                 const int indices[] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2621                                                 int t;
2622                                                 for (t = 0; t < nr_tris_to_pile; t++) {
2623                                                         float f2x_area_uv;
2624                                                         float *p0 = verts[indices[t * 3 + 0]];
2625                                                         float *p1 = verts[indices[t * 3 + 1]];
2626                                                         float *p2 = verts[indices[t * 3 + 2]];
2627
2628                                                         float edge_t0[2], edge_t1[2];
2629                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2630                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2631
2632                                                         f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2633                                                         if (f2x_area_uv > FLT_EPSILON) {
2634                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2635                                                                 sub_v3_v3v3(v0, p1, p0);
2636                                                                 sub_v3_v3v3(v1, p2, p0);
2637                                                                 cross_v3_v3v3(norm, v0, v1);
2638
2639                                                                 f2x_surf_area = len_v3(norm);
2640                                                                 fsurf_ratio = f2x_surf_area / f2x_area_uv;    // tri area divided by texture area
2641
2642                                                                 nr_accumulated++;
2643                                                                 dsum += (double)(fsurf_ratio);
2644                                                         }
2645                                                 }
2646                                         }
2647                                 }
2648                         }
2649                 }
2650
2651                 /* finalize */
2652                 {
2653                         const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2654                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
2655                         dm->auto_bump_scale = use_as_render_bump_scale;
2656                 }
2657         }
2658         else {
2659                 dm->auto_bump_scale = 1.0f;
2660         }
2661 }
2662
2663 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2664 {
2665         CustomData *vdata, *fdata, *tfdata = NULL;
2666         int a, b, layer;
2667
2668         /* From the layers requested by the GLSL shader, figure out which ones are
2669          * actually available for this derivedmesh, and retrieve the pointers */
2670
2671         memset(attribs, 0, sizeof(DMVertexAttribs));
2672
2673         vdata = &dm->vertData;
2674         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2675         
2676         /* calc auto bump scale if necessary */
2677         if (dm->auto_bump_scale <= 0.0f)
2678                 DM_calc_auto_bump_scale(dm);
2679
2680         /* add a tangent layer if necessary */
2681         for (b = 0; b < gattribs->totlayer; b++)
2682                 if (gattribs->layer[b].type == CD_TANGENT)
2683                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2684                                 DM_add_tangent_layer(dm);
2685
2686         for (b = 0; b < gattribs->totlayer; b++) {
2687                 if (gattribs->layer[b].type == CD_MTFACE) {
2688                         /* uv coordinates */
2689                         if (dm->type == DM_TYPE_EDITBMESH) {
2690                                 /* exception .. */
2691                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2692
2693                                 if (gattribs->layer[b].name[0])
2694                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2695                                                                                  gattribs->layer[b].name);
2696                                 else
2697                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2698
2699                                 if (layer != -1) {
2700                                         a = attribs->tottface++;
2701
2702                                         attribs->tface[a].array = tfdata->layers[layer].data;
2703                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2704                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2705                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2706                                 }
2707                         }
2708                         else {
2709                                 if (gattribs->layer[b].name[0])
2710                                         layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2711                                                                                  gattribs->layer[b].name);
2712                                 else
2713                                         layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2714
2715                                 if (layer != -1) {
2716                                         a = attribs->tottface++;
2717
2718                                         attribs->tface[a].array = tfdata->layers[layer].data;
2719                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2720                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2721                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2722                                 }
2723                         }
2724                 }
2725                 else if (gattribs->layer[b].type == CD_MCOL) {
2726                         if (dm->type == DM_TYPE_EDITBMESH) {
2727                                 /* exception .. */
2728                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2729
2730                                 if (gattribs->layer[b].name[0])
2731                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
2732                                                                                  gattribs->layer[b].name);
2733                                 else
2734                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
2735
2736                                 if (layer != -1) {
2737                                         a = attribs->totmcol++;
2738
2739                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2740                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2741                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2742                                 }
2743                         }
2744                         else {
2745                                 /* vertex colors */
2746                                 if (gattribs->layer[b].name[0])
2747                                         layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2748                                                                                  gattribs->layer[b].name);
2749                                 else
2750                                         layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2751
2752                                 if (layer != -1) {
2753                                         a = attribs->totmcol++;
2754
2755                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2756                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2757                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2758                                 }
2759                         }
2760                 }
2761                 else if (gattribs->layer[b].type == CD_TANGENT) {
2762                         /* tangents */
2763                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2764
2765                         if (layer != -1) {
2766                                 attribs->tottang = 1;
2767
2768                                 attribs->tang.array = fdata->layers[layer].data;
2769                                 attribs->tang.em_offset = fdata->layers[layer].offset;
2770                                 attribs->tang.gl_index = gattribs->layer[b].glindex;
2771                         }
2772                 }
2773                 else if (gattribs->layer[b].type == CD_ORCO) {
2774                         /* original coordinates */
2775                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2776
2777                         if (layer != -1) {
2778                                 attribs->totorco = 1;
2779
2780                                 attribs->orco.array = vdata->layers[layer].data;
2781                                 attribs->orco.em_offset = vdata->layers[layer].offset;
2782                                 attribs->orco.gl_index = gattribs->layer[b].glindex;
2783                                 attribs->orco.gl_texco = gattribs->layer[b].gltexco;
2784                         }
2785                 }
2786         }
2787 }
2788
2789 /* Set object's bounding box based on DerivedMesh min/max data */
2790 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2791 {
2792         float min[3], max[3];
2793
2794         INIT_MINMAX(min, max);
2795
2796         dm->getMinMax(dm, min, max);
2797
2798         if (!ob->bb)
2799                 ob->bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2800
2801         BKE_boundbox_init_from_minmax(ob->bb, min, max);
2802 }
2803
2804 /* --- NAVMESH (begin) --- */
2805 #ifdef WITH_GAMEENGINE
2806
2807 /* BMESH_TODO, navmesh is not working right currently
2808  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2809  *
2810  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2811  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2812  * data from the original me->mpoly layer. - campbell
2813  */
2814
2815
2816 BLI_INLINE int navmesh_bit(int a, int b)
2817 {
2818         return (a & (1 << b)) >> b;
2819 }
2820
2821 BLI_INLINE void navmesh_intToCol(int i, float col[3])
2822 {
2823         int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2824         int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2825         int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2826         col[0] = 1 - r * 63.0f / 255.0f;
2827         col[1] = 1 - g * 63.0f / 255.0f;
2828         col[2] = 1 - b * 63.0f / 255.0f;
2829 }
2830
2831 static void navmesh_drawColored(DerivedMesh *dm)
2832 {
2833         int a, glmode;
2834         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2835         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2836         int *polygonIdx = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
2837         float col[3];
2838
2839         if (!polygonIdx)
2840                 return;
2841
2842 #if 0
2843         //UI_ThemeColor(TH_WIRE);
2844         glDisable(GL_LIGHTING);
2845         glLineWidth(2.0);
2846         dm->drawEdges(dm, 0, 1);
2847         glLineWidth(1.0);
2848         glEnable(GL_LIGHTING);
2849 #endif
2850
2851         glDisable(GL_LIGHTING);
2852         /* if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2853                 DEBUG_VBO("Using legacy code. drawNavMeshColored\n");
2854                 //glShadeModel(GL_SMOOTH);
2855                 glBegin(glmode = GL_QUADS);
2856                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
2857                         int new_glmode = mface->v4 ? GL_QUADS : GL_TRIANGLES;
2858                         int pi = polygonIdx[a];
2859                         if (pi <= 0) {
2860                                 zero_v3(col);
2861                         }
2862                         else {
2863                                 navmesh_intToCol(pi, col);
2864                         }
2865
2866                         if (new_glmode != glmode) {
2867                                 glEnd();
2868                                 glBegin(glmode = new_glmode);
2869                         }
2870                         glColor3fv(col);
2871                         glVertex3fv(mvert[mface->v1].co);
2872                         glVertex3fv(mvert[mface->v2].co);
2873                         glVertex3fv(mvert[mface->v3].co);
2874                         if (mface->v4) {
2875                                 glVertex3fv(mvert[mface->v4].co);
2876                         }
2877                 }
2878                 glEnd();
2879         }
2880         glEnable(GL_LIGHTING);
2881 }
2882
2883 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2884                                     DMSetDrawOptionsTex setDrawOptions,
2885                                     DMCompareDrawOptions compareDrawOptions,
2886                                     void *userData)
2887 {
2888         (void) setDrawOptions;
2889         (void) compareDrawOptions;
2890         (void) userData;
2891
2892         navmesh_drawColored(dm);
2893 }
2894
2895 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2896                                       float (*partial_redraw_planes)[4],
2897                                       int UNUSED(fast), DMSetMaterial setMaterial)
2898 {
2899         (void) partial_redraw_planes;
2900         (void) setMaterial;
2901
2902         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2903         navmesh_drawColored(dm);
2904 }
2905
2906 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2907 {
2908         DerivedMesh *result;
2909         int maxFaces = dm->getNumPolys(dm);
2910         int *recastData;
2911         int vertsPerPoly = 0, nverts = 0, ndtris = 0, npolys = 0;
2912         float *verts = NULL;
2913         unsigned short *dtris = NULL, *dmeshes = NULL, *polys = NULL;
2914         int *dtrisToPolysMap = NULL, *dtrisToTrisMap = NULL, *trisToFacesMap = NULL;
2915         int res;
2916
2917         result = CDDM_copy(dm);
2918         if (!CustomData_has_layer(&result->polyData, CD_RECAST)) {
2919                 int *sourceRecastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
2920                 if (sourceRecastData) {
2921                         CustomData_add_layer_named(&result->polyData, CD_RECAST, CD_DUPLICATE,
2922                                                    sourceRecastData, maxFaces, "recastData");
2923                 }
2924         }
2925         recastData = (int *)CustomData_get_layer(&result->polyData, CD_RECAST);
2926
2927         /* note: This is not good design! - really should not be doing this */
2928         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2929         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2930
2931
2932         /* process mesh */
2933         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2934                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2935                                              &trisToFacesMap);
2936         if (res) {
2937                 size_t polyIdx;
2938
2939                 /* invalidate concave polygon */
2940                 for (polyIdx = 0; polyIdx < (size_t)npolys; polyIdx++) {
2941                         unsigned short *poly = &polys[polyIdx * 2 * vertsPerPoly];
2942                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2943                                 /* set negative polygon idx to all faces */
2944                                 unsigned short *dmesh = &dmeshes[4 * polyIdx];
2945                                 unsigned short tbase = dmesh[2];
2946                                 unsigned short tnum = dmesh[3];
2947                                 unsigned short ti;
2948
2949                                 for (ti = 0; ti < tnum; ti++) {
2950                                         unsigned short triidx = dtrisToTrisMap[tbase + ti];
2951                                         unsigned short faceidx = trisToFacesMap[triidx];
2952                                         if (recastData[faceidx] > 0) {
2953                                                 recastData[faceidx] = -recastData[faceidx];
2954                                         }
2955                                 }
2956                         }
2957                 }
2958         }
2959         else {
2960                 printf("%s: Error during creation polygon infos\n", __func__);
2961         }
2962
2963         /* clean up */
2964         if (verts != NULL)
2965                 MEM_freeN(verts);
2966         if (dtris != NULL)
2967                 MEM_freeN(dtris);
2968         if (dmeshes != NULL)
2969                 MEM_freeN(dmeshes);
2970         if (polys != NULL)
2971                 MEM_freeN(polys);
2972         if (dtrisToPolysMap != NULL)
2973                 MEM_freeN(dtrisToPolysMap);
2974         if (dtrisToTrisMap != NULL)
2975                 MEM_freeN(dtrisToTrisMap);
2976         if (trisToFacesMap != NULL)
2977                 MEM_freeN(trisToFacesMap);
2978
2979         return result;
2980 }
2981
2982 #endif /* WITH_GAMEENGINE */
2983
2984 /* --- NAVMESH (end) --- */
2985
2986
2987 void DM_init_origspace(DerivedMesh *dm)
2988 {
2989         static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
2990
2991         OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
2992         OrigSpaceLoop *lof;
2993         const int numpoly = dm->getNumPolys(dm);
2994         // const int numloop = dm->getNumLoops(dm);
2995         MPoly *mp = dm->getPolyArray(dm);
2996         int i, j;
2997
2998         for (i = 0; i < numpoly; i++, mp++) {
2999                 /* only quads/tri's for now */
3000                 if (mp->totloop == 3 || mp->totloop == 4) {
3001                         lof = lof_array + mp->loopstart;
3002                         for (j = 0; j < mp->totloop; j++, lof++) {
3003                                 copy_v2_v2(lof->uv, default_osf[j]);
3004                         }
3005                 }
3006         }
3007
3008         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
3009 }
3010
3011
3012
3013 /* derivedmesh info printing function,
3014  * to help track down differences DM output */
3015
3016 #ifndef NDEBUG
3017 #include "BLI_dynstr.h"
3018
3019 static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
3020 {
3021         int type;
3022
3023         for (type = 0; type < CD_NUMTYPES; type++) {
3024                 /* note: doesnt account for multiple layers */
3025                 void *pt = getElemDataArray(dm, type);
3026                 if (pt) {
3027                         const char *name = CustomData_layertype_name(type);
3028                         const int size = CustomData_sizeof(type);
3029                         const char *structname;
3030                         int structnum;
3031                         CustomData_file_write_info(type, &structname, &structnum);
3032                         BLI_dynstr_appendf(dynstr,
3033                                            "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
3034                                            name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
3035                 }
3036         }
3037 }
3038
3039 char *DM_debug_info(DerivedMesh *dm)
3040 {
3041         DynStr *dynstr = BLI_dynstr_new();
3042         char *ret;
3043         const char *tstr;
3044
3045         BLI_dynstr_appendf(dynstr, "{\n");
3046         BLI_dynstr_appendf(dynstr, "    'ptr': '%p',\n", (void *)dm);
3047         switch (dm->type) {
3048                 case DM_TYPE_CDDM:     tstr = "DM_TYPE_CDDM";     break;
3049                 case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH";  break;
3050                 case DM_TYPE_CCGDM:    tstr = "DM_TYPE_CCGDM";     break;
3051                 default:               tstr = "UNKNOWN";           break;
3052         }
3053         BLI_dynstr_appendf(dynstr, "    'type': '%s',\n", tstr);
3054         BLI_dynstr_appendf(dynstr, "    'numVertData': %d,\n", dm->numVertData);
3055         BLI_dynstr_appendf(dynstr, "    'numEdgeData': %d,\n", dm->numEdgeData);
3056         BLI_dynstr_appendf(dynstr, "    'numTessFaceData': %d,\n", dm->numTessFaceData);
3057         BLI_dynstr_appendf(dynstr, "    'numPolyData': %d,\n", dm->numPolyData);
3058         BLI_dynstr_appendf(dynstr, "    'deformedOnly': %d,\n", dm->deformedOnly);
3059
3060         BLI_dynstr_appendf(dynstr, "    'vertexLayers': (\n");
3061         dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
3062         BLI_dynstr_appendf(dynstr, "    ),\n");
3063
3064         BLI_dynstr_appendf(dynstr, "    'loopLayers': (\n");
3065         dm_debug_info_layers(dynstr, dm, DM_get_loop_data_layer);
3066         BLI_dynstr_appendf(dynstr, "    ),\n");
3067
3068         BLI_dynstr_appendf(dynstr, "    'edgeLayers': (\n");
3069         dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
3070         BLI_dynstr_appendf(dynstr, "    ),\n");
3071
3072         BLI_dynstr_appendf(dynstr, "    'tessFaceLayers': (\n");
3073         dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
3074         BLI_dynstr_appendf(dynstr, "    ),\n");
3075
3076         BLI_dynstr_appendf(dynstr, "    'polyLayers': (\n");
3077         dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
3078         BLI_dynstr_appendf(dynstr, "    ),\n");