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