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