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