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