support for 'origspace' data layer - used for hair on subsurf mesh.
[blender-staging.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         /* First calculate the polygon and vertex normals, re-tesselation
1662          * copies these into the tessface's normal layer */
1663         finaldm->calcNormals(finaldm);
1664         /* Re-tesselation is necessary to push render data (uvs, textures, colors)
1665          * from loops and polys onto the tessfaces. This may be currently be
1666          * redundantin cases where the render mode doesn't use these inputs, but
1667          * ideally eventually tesselation would happen on-demand, and this is one
1668          * of the primary places it would be needed. */
1669         finaldm->recalcTesselation(finaldm);
1670         /* Need to watch this, it can cause issues, see bug [#29338]             */
1671         /* take care with this block, we really need testing frameworks          */
1672         /* --------------------------------------------------------------------- */
1673
1674
1675         *final_r = finaldm;
1676
1677         if(orcodm)
1678                 orcodm->release(orcodm);
1679         if(clothorcodm)
1680                 clothorcodm->release(clothorcodm);
1681
1682         if(deformedVerts && deformedVerts != inputVertexCos)
1683                 MEM_freeN(deformedVerts);
1684
1685         BLI_linklist_free(datamasks, NULL);
1686 }
1687
1688 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1689 {
1690         int i, numVerts = *numVerts_r = em->bm->totvert;
1691         float (*cos)[3];
1692         BMIter iter;
1693         BMVert *eve;
1694
1695         cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1696
1697         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1698         for (i=0; eve; eve=BMIter_Step(&iter), i++) {
1699                 copy_v3_v3(cos[i], eve->co);
1700         }
1701
1702         return cos;
1703 }
1704
1705 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1706 {
1707         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1708         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1709
1710         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1711         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1712                 modifier_setError(md, "Modifier requires original data, bad stack position.");
1713                 return 0;
1714         }
1715         
1716         return 1;
1717 }
1718
1719 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1720                                                                         DerivedMesh **final_r,
1721                                                                         CustomDataMask dataMask)
1722 {
1723         ModifierData *md;
1724         float (*deformedVerts)[3] = NULL;
1725         CustomDataMask mask;
1726         DerivedMesh *dm, *orcodm = NULL;
1727         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1728         LinkNode *datamasks, *curr;
1729         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1730
1731         modifiers_clearErrors(ob);
1732
1733         if(cage_r && cageIndex == -1) {
1734                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1735         }
1736
1737         dm = NULL;
1738         md = modifiers_getVirtualModifierList(ob);
1739
1740         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1741
1742         curr = datamasks;
1743         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1744                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1745
1746                 md->scene= scene;
1747                 
1748                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1749                         continue;
1750
1751                 /* add an orco layer if needed by this modifier */
1752                 if(dm && mti->requiredDataMask) {
1753                         mask = mti->requiredDataMask(ob, md);
1754                         if(mask & CD_MASK_ORCO)
1755                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1756                 }
1757
1758                 /* How to apply modifier depends on (a) what we already have as
1759                  * a result of previous modifiers (could be a DerivedMesh or just
1760                  * deformed vertices) and (b) what type the modifier is.
1761                  */
1762
1763                 if(mti->type == eModifierTypeType_OnlyDeform) {
1764                         /* No existing verts to deform, need to build them. */
1765                         if(!deformedVerts) {
1766                                 if(dm) {
1767                                         /* Deforming a derived mesh, read the vertex locations
1768                                          * out of the mesh and deform them. Once done with this
1769                                          * run of deformers verts will be written back.
1770                                          */
1771                                         numVerts = dm->getNumVerts(dm);
1772                                         deformedVerts =
1773                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1774                                         dm->getVertCos(dm, deformedVerts);
1775                                 } else {
1776                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1777                                 }
1778                         }
1779
1780                         if (mti->deformVertsEM)
1781                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1782                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1783                 } else {
1784                         DerivedMesh *ndm;
1785
1786                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1787                         if(dm) {
1788                                 if(deformedVerts) {
1789                                         DerivedMesh *tdm = CDDM_copy(dm);
1790                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1791                                         dm = tdm;
1792
1793                                         CDDM_apply_vert_coords(dm, deformedVerts);
1794                                         CDDM_calc_normals(dm);
1795                                 } else if(cage_r && dm == *cage_r) {
1796                                         /* dm may be changed by this modifier, so we need to copy it
1797                                          */
1798                                         dm = CDDM_copy(dm);
1799                                 }
1800
1801                         } else {
1802                                 dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
1803
1804                                 if(deformedVerts) {
1805                                         CDDM_apply_vert_coords(dm, deformedVerts);
1806                                         CDDM_calc_normals(dm);
1807                                 }
1808                         }
1809
1810                         /* create an orco derivedmesh in parallel */
1811                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1812                         if(mask & CD_MASK_ORCO) {
1813                                 if(!orcodm)
1814                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1815
1816                                 mask &= ~CD_MASK_ORCO;
1817                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1818
1819                                 if (mti->applyModifierEM)
1820                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1821                                 else
1822                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1823
1824                                 if(ndm) {
1825                                         /* if the modifier returned a new dm, release the old one */
1826                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1827                                         orcodm = ndm;
1828                                 }
1829                         }
1830
1831                         /* set the DerivedMesh to only copy needed data */
1832                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1833
1834                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1835
1836                         if(mask & CD_MASK_ORIGSPACE_MLOOP) {
1837                                 if(!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1838                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1839                                         DM_init_origspace(dm);
1840                                 }
1841                         }
1842                         
1843                         if (mti->applyModifierEM)
1844                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1845                         else
1846                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1847
1848                         if (ndm) {
1849                                 if(dm && dm != ndm)
1850                                         dm->release(dm);
1851
1852                                 dm = ndm;
1853
1854                                 if (deformedVerts) {
1855                                         MEM_freeN(deformedVerts);
1856                                         deformedVerts = NULL;
1857                                 }
1858                         }
1859                 }
1860
1861                 if(cage_r && i == cageIndex) {
1862                         if(dm && deformedVerts) {
1863                                 *cage_r = CDDM_copy(dm);
1864                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1865                         } else if(dm) {
1866                                 *cage_r = dm;
1867                         } else {
1868                                 *cage_r =
1869                                         getEditDerivedBMesh(em, ob,
1870                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1871                         }
1872                 }
1873         }
1874
1875         BLI_linklist_free(datamasks, NULL);
1876
1877         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1878          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1879          * then we need to build one.
1880          */
1881         if(dm && deformedVerts) {
1882                 *final_r = CDDM_copy(dm);
1883
1884                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1885
1886                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1887                 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
1888         } else if (dm) {
1889                 *final_r = dm;
1890                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1891         } else if (!deformedVerts && cage_r && *cage_r) {
1892                 *final_r = *cage_r;
1893                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1894         } else {
1895                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1896                 deformedVerts = NULL;
1897                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1898         }
1899
1900         /* --- */
1901         /* BMESH_ONLY, ensure tessface's used for drawing,
1902          * but dont recalculate if the last modifier in the stack gives us tessfaces  */
1903         DM_ensure_tessface(*final_r);
1904         if (cage_r && (*cage_r != *final_r)) DM_ensure_tessface(*cage_r);
1905         /* --- */
1906
1907         /* add an orco layer if needed */
1908         if(dataMask & CD_MASK_ORCO)
1909                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1910
1911         if(orcodm)
1912                 orcodm->release(orcodm);
1913
1914         if(deformedVerts)
1915                 MEM_freeN(deformedVerts);
1916 }
1917
1918 static void clear_mesh_caches(Object *ob)
1919 {
1920         Mesh *me= ob->data;
1921
1922                 /* also serves as signal to remake texspace */
1923         if (ob->bb) {
1924                 MEM_freeN(ob->bb);
1925                 ob->bb = NULL;
1926         }
1927         if (me->bb) {
1928                 MEM_freeN(me->bb);
1929                 me->bb = NULL;
1930         }
1931
1932         freedisplist(&ob->disp);
1933
1934         if (ob->derivedFinal) {
1935                 ob->derivedFinal->needsFree = 1;
1936                 ob->derivedFinal->release(ob->derivedFinal);
1937                 ob->derivedFinal= NULL;
1938         }
1939         if (ob->derivedDeform) {
1940                 ob->derivedDeform->needsFree = 1;
1941                 ob->derivedDeform->release(ob->derivedDeform);
1942                 ob->derivedDeform= NULL;
1943         }
1944
1945         if(ob->sculpt) {
1946                 object_sculpt_modifiers_changed(ob);
1947         }
1948 }
1949
1950 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1951                             int build_shapekey_layers)
1952 {
1953         Object *obact = scene->basact?scene->basact->object:NULL;
1954         int editing = paint_facesel_test(ob);
1955         /* weight paint and face select need original indices because of selection buffer drawing */
1956         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1957
1958         clear_mesh_caches(ob);
1959
1960         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1961                                                 &ob->derivedFinal, 0, 1,
1962                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
1963
1964         DM_set_object_boundbox (ob, ob->derivedFinal);
1965
1966         ob->derivedFinal->needsFree = 0;
1967         ob->derivedDeform->needsFree = 0;
1968         ob->lastDataMask = dataMask;
1969 }
1970
1971 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1972 {
1973         clear_mesh_caches(obedit);
1974
1975         if (em->derivedFinal) {
1976                 if (em->derivedFinal!=em->derivedCage) {
1977                         em->derivedFinal->needsFree = 1;
1978                         em->derivedFinal->release(em->derivedFinal);
1979                 }
1980                 em->derivedFinal = NULL;
1981         }
1982         if (em->derivedCage) {
1983                 em->derivedCage->needsFree = 1;
1984                 em->derivedCage->release(em->derivedCage);
1985                 em->derivedCage = NULL;
1986         }
1987
1988         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1989         DM_set_object_boundbox (obedit, em->derivedFinal);
1990
1991         em->lastDataMask = dataMask;
1992         em->derivedFinal->needsFree = 0;
1993         em->derivedCage->needsFree = 0;
1994 }
1995
1996 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
1997                      CustomDataMask dataMask, int build_shapekey_layers)
1998 {
1999         if (em) {
2000                 editbmesh_build_data(scene, ob, em, dataMask);
2001         } else {
2002                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2003         }
2004 }
2005
2006 /***/
2007
2008 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2009 {
2010         /* if there's no derived mesh or the last data mask used doesn't include
2011          * the data we need, rebuild the derived mesh
2012          */
2013         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2014                 mesh_build_data(scene, ob, dataMask, 0);
2015
2016         return ob->derivedFinal;
2017 }
2018
2019 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2020 {
2021         /* if there's no derived mesh or the last data mask used doesn't include
2022          * the data we need, rebuild the derived mesh
2023          */
2024         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2025                 mesh_build_data(scene, ob, dataMask, 0);
2026
2027         return ob->derivedDeform;
2028 }
2029
2030 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2031 {
2032         DerivedMesh *final;
2033         
2034         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2035
2036         return final;
2037 }
2038
2039 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2040 {
2041         DerivedMesh *final;
2042         
2043         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2044
2045         return final;
2046 }
2047
2048 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2049 {
2050         DerivedMesh *final;
2051
2052         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2053
2054         return final;
2055 }
2056
2057 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2058                                                                                    CustomDataMask dataMask)
2059 {
2060         DerivedMesh *final;
2061         
2062         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2063
2064         return final;
2065 }
2066
2067 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2068                                                                                         CustomDataMask dataMask)
2069 {
2070         DerivedMesh *final;
2071         
2072         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2073
2074         return final;
2075 }
2076
2077 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2078                                                                                         CustomDataMask dataMask)
2079 {
2080         DerivedMesh *final;
2081         
2082         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2083
2084         return final;
2085 }
2086
2087 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2088                                                                                                   float (*vertCos)[3],
2089                                                                                                   CustomDataMask dataMask)
2090 {
2091         DerivedMesh *final;
2092
2093         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2094
2095         return final;
2096 }
2097
2098 /***/
2099
2100 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2101                                                                                                  CustomDataMask dataMask)
2102 {
2103         /* if there's no derived mesh or the last data mask used doesn't include
2104          * the data we need, rebuild the derived mesh
2105          */
2106         if(!em->derivedCage ||
2107            (em->lastDataMask & dataMask) != dataMask)
2108                 editbmesh_build_data(scene, obedit, em, dataMask);
2109
2110         *final_r = em->derivedFinal;
2111         return em->derivedCage;
2112 }
2113
2114 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2115 {
2116         /* if there's no derived mesh or the last data mask used doesn't include
2117          * the data we need, rebuild the derived mesh
2118          */
2119         if(!em->derivedCage ||
2120            (em->lastDataMask & dataMask) != dataMask)
2121                 editbmesh_build_data(scene, obedit, em, dataMask);
2122
2123         return em->derivedCage;
2124 }
2125
2126 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2127 {
2128         return getEditDerivedBMesh(em, obedit, NULL);
2129 }
2130
2131
2132 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2133
2134 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2135 {
2136         float *vec = userData;
2137         
2138         vec+= 6*index;
2139
2140         /* check if we've been here before (normal should not be 0) */
2141         if(vec[3] || vec[4] || vec[5]) return;
2142
2143         copy_v3_v3(vec, co);
2144         vec+= 3;
2145         if(no_f) {
2146                 copy_v3_v3(vec, no_f);
2147         }
2148         else {
2149                 normal_short_to_float_v3(vec, no_s);
2150         }
2151 }
2152
2153 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2154 /* this is needed for all code using vertexgroups (no subsurf support) */
2155 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2156 /* in use now by vertex/weight paint and particle generating */
2157
2158 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2159 {
2160         Mesh *me= ob->data;
2161         DerivedMesh *dm;
2162         float *vertexcosnos;
2163         
2164         /* lets prevent crashing... */
2165         if(ob->type!=OB_MESH || me->totvert==0)
2166                 return NULL;
2167         
2168         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2169         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2170         
2171         if(dm->foreachMappedVert) {
2172                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2173         }
2174         else {
2175                 float *fp= vertexcosnos;
2176                 int a;
2177                 
2178                 for(a=0; a< me->totvert; a++, fp+=6) {
2179                         dm->getVertCo(dm, a, fp);
2180                         dm->getVertNo(dm, a, fp+3);
2181                 }
2182         }
2183         
2184         dm->release(dm);
2185         return vertexcosnos;
2186 }
2187
2188 /* ******************* GLSL ******************** */
2189
2190 typedef struct
2191 {
2192         float * precomputedFaceNormals;
2193         MTFace * mtface;        // texture coordinates
2194         MFace * mface;          // indices
2195         MVert * mvert;          // vertices & normals
2196         float (*orco)[3];
2197         float (*tangent)[4];    // destination
2198         int numTessFaces;
2199
2200 } SGLSLMeshToTangent;
2201
2202 // interface
2203 #include "mikktspace.h"
2204
2205 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2206 {
2207         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2208         return pMesh->numTessFaces;
2209 }
2210
2211 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2212 {
2213         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2214         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2215 }
2216
2217 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2218 {
2219         //assert(vert_index>=0 && vert_index<4);
2220         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2221         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2222         copy_v3_v3(fPos, co);
2223 }
2224
2225 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2226 {
2227         //assert(vert_index>=0 && vert_index<4);
2228         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2229
2230         if(pMesh->mtface!=NULL) {
2231                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2232                 fUV[0]=uv[0]; fUV[1]=uv[1];
2233         }
2234         else {
2235                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2236                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2237         }
2238 }
2239
2240 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2241 {
2242         //assert(vert_index>=0 && vert_index<4);
2243         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2244
2245         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2246         if(!smoothnormal) {     // flat
2247                 if(pMesh->precomputedFaceNormals) {
2248                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2249                 }
2250                 else {
2251                         MFace *mf= &pMesh->mface[face_num];
2252                         float *p0= pMesh->mvert[mf->v1].co;
2253                         float *p1= pMesh->mvert[mf->v2].co;
2254                         float *p2= pMesh->mvert[mf->v3].co;
2255
2256                         if(mf->v4) {
2257                                 float *p3 = pMesh->mvert[mf->v4].co;
2258                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2259                         }
2260                         else {
2261                                 normal_tri_v3(fNorm, p0, p1, p2);
2262                         }
2263                 }
2264         }
2265         else {
2266                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2267                 normal_short_to_float_v3(fNorm, no);
2268         }
2269 }
2270 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2271 {
2272         //assert(vert_index>=0 && vert_index<4);
2273         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2274         float * pRes = pMesh->tangent[4*face_num+iVert];
2275         copy_v3_v3(pRes, fvTangent);
2276         pRes[3]=fSign;
2277 }
2278
2279
2280 void DM_add_tangent_layer(DerivedMesh *dm)
2281 {
2282         /* mesh vars */
2283         MTFace *mtface, *tf;
2284         MFace *mface, *mf;
2285         MVert *mvert, *v1, *v2, *v3, *v4;
2286         MemArena *arena= NULL;
2287         VertexTangent **vtangents= NULL;
2288         float (*orco)[3]= NULL, (*tangent)[4];
2289         float *uv1, *uv2, *uv3, *uv4, *vtang;
2290         float fno[3], tang[3], uv[4][2];
2291         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2292         float *nors;
2293
2294         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2295                 return;
2296
2297         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2298
2299         /* check we have all the needed layers */
2300         totvert= dm->getNumVerts(dm);
2301         totface= dm->getNumTessFaces(dm);
2302
2303         mvert= dm->getVertArray(dm);
2304         mface= dm->getTessFaceArray(dm);
2305         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2306
2307         if(!mtface) {
2308                 orco= dm->getVertDataArray(dm, CD_ORCO);
2309                 if(!orco)
2310                         return;
2311         }
2312         
2313         /* create tangent layer */
2314         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2315         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2316         
2317         /* allocate some space */
2318         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2319         BLI_memarena_use_calloc(arena);
2320         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2321
2322         // new computation method
2323         iCalcNewMethod = 1;
2324         if(iCalcNewMethod != 0) {
2325                 SGLSLMeshToTangent mesh2tangent= {0};
2326                 SMikkTSpaceContext sContext= {0};
2327                 SMikkTSpaceInterface sInterface= {0};
2328
2329                 mesh2tangent.precomputedFaceNormals = nors;
2330                 mesh2tangent.mtface = mtface;
2331                 mesh2tangent.mface = mface;
2332                 mesh2tangent.mvert = mvert;
2333                 mesh2tangent.orco = orco;
2334                 mesh2tangent.tangent = tangent;
2335                 mesh2tangent.numTessFaces = totface;
2336
2337                 sContext.m_pUserData = &mesh2tangent;
2338                 sContext.m_pInterface = &sInterface;
2339                 sInterface.m_getNumFaces = GetNumFaces;
2340                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2341                 sInterface.m_getPosition = GetPosition;
2342                 sInterface.m_getTexCoord = GetTextureCoordinate;
2343                 sInterface.m_getNormal = GetNormal;
2344                 sInterface.m_setTSpaceBasic = SetTSpace;
2345
2346                 // 0 if failed
2347                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2348         }
2349
2350         if(!iCalcNewMethod) {
2351                 /* sum tangents at connected vertices */
2352                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2353                         v1= &mvert[mf->v1];
2354                         v2= &mvert[mf->v2];
2355                         v3= &mvert[mf->v3];
2356
2357                         if (mf->v4) {
2358                                 v4= &mvert[mf->v4];
2359                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2360                         }
2361                         else {
2362                                 v4= NULL;
2363                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2364                         }
2365                 
2366                         if(mtface) {
2367                                 uv1= tf->uv[0];
2368                                 uv2= tf->uv[1];
2369                                 uv3= tf->uv[2];
2370                                 uv4= tf->uv[3];
2371                         }
2372                         else {
2373                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2374                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2375                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2376                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2377                                 if(v4)
2378                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2379                         }
2380                 
2381                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2382                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2383                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2384                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2385                 
2386                         if(mf->v4) {
2387                                 v4= &mvert[mf->v4];
2388                         
2389                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2390                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2391                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2392                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2393                         }
2394                 }
2395         
2396                 /* write tangent to layer */
2397                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2398                         len= (mf->v4)? 4 : 3; 
2399
2400                         if(mtface == NULL) {
2401                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2402                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2403                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2404                                 if(len==4)
2405                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2406                         }
2407                 
2408                         mf_vi[0]= mf->v1;
2409                         mf_vi[1]= mf->v2;
2410                         mf_vi[2]= mf->v3;
2411                         mf_vi[3]= mf->v4;
2412                 
2413                         for(j=0; j<len; j++) {
2414                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2415                                 normalize_v3_v3(tangent[j], vtang);
2416                                 ((float *) tangent[j])[3]=1.0f;
2417                         }
2418                 }
2419         }
2420         
2421         BLI_memarena_free(arena);
2422         MEM_freeN(vtangents);
2423 }
2424
2425 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2426 {
2427         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2428         int totface= dm->getNumTessFaces(dm);
2429
2430         MVert * mvert = dm->getVertArray(dm);
2431         MFace * mface = dm->getTessFaceArray(dm);
2432         MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2433
2434         if(mtface)
2435         {
2436                 double dsum = 0.0;
2437                 int nr_accumulated = 0;
2438                 int f;
2439
2440                 for ( f=0; f<totface; f++ )
2441                 {
2442                         {
2443                                 float * verts[4], * tex_coords[4];
2444                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2445                                 int i, is_degenerate;
2446
2447                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2448                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2449                                 if(nr_verts==4)
2450                                 {
2451                                         verts[3]=mvert[mface[f].v4].co;
2452                                         tex_coords[3]=mtface[f].uv[3];
2453                                 }
2454
2455                                 // discard degenerate faces
2456                                 is_degenerate = 0;
2457                                 if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2458                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2459                                 {
2460                                         is_degenerate = 1;
2461                                 }
2462
2463                                 // verify last vertex as well if this is a quad
2464                                 if ( is_degenerate==0 && nr_verts==4 )
2465                                 {
2466                                         if(     equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2467                                                 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2468                                         {
2469                                                 is_degenerate = 1;
2470                                         }
2471
2472                                         // verify the winding is consistent
2473                                         if ( is_degenerate==0 )
2474                                         {
2475                                                 float prev_edge[2];
2476                                                 int is_signed = 0;
2477                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2478
2479                                                 i = 0;
2480                                                 while ( is_degenerate==0 && i<4 )
2481                                                 {
2482                                                         float cur_edge[2], signed_area;
2483                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2484                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2485                                                         if ( i==0 ) is_signed = signed_area<0.0f ? 1 : 0;
2486                                                         else if((is_signed!=0)!=(signed_area<0.0f)) is_degenerate=1;
2487
2488                                                         if ( is_degenerate==0 )
2489                                                         {
2490                                                                 copy_v2_v2(prev_edge, cur_edge);
2491                                                                 ++i;
2492                                                         }
2493                                                 }
2494                                         }
2495                                 }
2496
2497                                 // proceed if not a degenerate face
2498                                 if ( is_degenerate==0 )
2499                                 {
2500                                         int nr_tris_to_pile=0;
2501                                         // quads split at shortest diagonal
2502                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
2503                                         if ( nr_verts==4 )
2504                                         {
2505                                                 float pos_len_diag0, pos_len_diag1;
2506                                                 float vtmp[3];
2507                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2508                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2509                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2510                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2511
2512                                                 if(pos_len_diag1<pos_len_diag0)
2513                                                         offs=1;         // alter split
2514                                                 else if(pos_len_diag0==pos_len_diag1)           // do UV check instead
2515                                                 {
2516                                                         float tex_len_diag0, tex_len_diag1;
2517
2518                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2519                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2520                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2521                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2522
2523                                                         if(tex_len_diag1<tex_len_diag0)
2524                                                         {
2525                                                                 offs=1;         // alter split
2526                                                         }
2527                                                 }
2528                                         }
2529                                         nr_tris_to_pile = nr_verts-2 ;
2530                                         if ( nr_tris_to_pile==1 || nr_tris_to_pile==2 )
2531                                         {
2532                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2533                                                 int t;
2534                                                 for ( t=0; t<nr_tris_to_pile; t++ )
2535                                                 {
2536                                                         float f2x_area_uv;
2537                                                         float * p0 = verts[indices[t*3+0]];
2538                                                         float * p1 = verts[indices[t*3+1]];
2539                                                         float * p2 = verts[indices[t*3+2]];
2540
2541                                                         float edge_t0[2], edge_t1[2];
2542                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2543                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2544
2545                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2546                                                         if ( f2x_area_uv>FLT_EPSILON )
2547                                                         {
2548                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2549                                                                 sub_v3_v3v3(v0, p1, p0);
2550                                                                 sub_v3_v3v3(v1, p2, p0);
2551                                                                 cross_v3_v3v3(norm, v0, v1);
2552
2553                                                                 f2x_surf_area = len_v3(norm);
2554                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
2555
2556                                                                 ++nr_accumulated;
2557                                                                 dsum += (double)(fsurf_ratio);
2558                                                         }
2559                                                 }
2560                                         }
2561                                 }
2562                         }
2563                 }
2564
2565                 // finalize
2566                 {
2567                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2568                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2569                         dm->auto_bump_scale = use_as_render_bump_scale;
2570                 }
2571         }
2572         else
2573         {
2574                 dm->auto_bump_scale = 1.0f;
2575         }
2576 }
2577
2578 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2579 {
2580         CustomData *vdata, *fdata, *tfdata = NULL;
2581         int a, b, layer;
2582
2583         /* From the layers requested by the GLSL shader, figure out which ones are
2584          * actually available for this derivedmesh, and retrieve the pointers */
2585
2586         memset(attribs, 0, sizeof(DMVertexAttribs));
2587
2588         vdata = &dm->vertData;
2589         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2590         
2591         /* calc auto bump scale if necessary */
2592         if(dm->auto_bump_scale<=0.0f)
2593                 DM_calc_auto_bump_scale(dm);
2594
2595         /* add a tangent layer if necessary */
2596         for(b = 0; b < gattribs->totlayer; b++)
2597                 if(gattribs->layer[b].type == CD_TANGENT)
2598                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2599                                 DM_add_tangent_layer(dm);
2600
2601         for(b = 0; b < gattribs->totlayer; b++) {
2602                 if(gattribs->layer[b].type == CD_MTFACE) {
2603                         /* uv coordinates */
2604                         if(gattribs->layer[b].name[0])
2605                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2606                                         gattribs->layer[b].name);
2607                         else
2608                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2609
2610                         if(layer != -1) {
2611                                 a = attribs->tottface++;
2612
2613                                 attribs->tface[a].array = tfdata->layers[layer].data;
2614                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2615                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2616                                 /* attribs->tface[a].glTexco = gattribs->layer[b].gltexco; */ /* BMESH_TODO, trunk has this but not bmesh, need to investigate whats going on here - campbell */
2617                         }
2618                         /* BMESH ONLY, may need to get this working?, otherwise remove */
2619                         /* else {
2620                                 int player;
2621                                 CustomData *pdata = dm->getPolyDataLayout(dm);
2622                                 
2623                                 if(gattribs->layer[b].name[0])
2624                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2625                                                 gattribs->layer[b].name);
2626                                 else
2627                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2628                                 
2629                                 if (player != -1) {
2630                                         a = attribs->tottface++;
2631         
2632                                         attribs->tface[a].array = NULL;
2633                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2634                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2635                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2636                                         
2637                                 }
2638                         }
2639                         */
2640                 }
2641                 else if(gattribs->layer[b].type == CD_MCOL) {
2642                         /* vertex colors */
2643                         if(gattribs->layer[b].name[0])
2644                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2645                                         gattribs->layer[b].name);
2646                         else
2647                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2648
2649                         if(layer != -1) {
2650                                 a = attribs->totmcol++;
2651
2652                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2653                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2654                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2655                         }
2656                 }
2657                 else if(gattribs->layer[b].type == CD_TANGENT) {
2658                         /* tangents */
2659                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2660
2661                         if(layer != -1) {
2662                                 attribs->tottang = 1;
2663
2664                                 attribs->tang.array = fdata->layers[layer].data;
2665                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2666                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2667                         }
2668                 }
2669                 else if(gattribs->layer[b].type == CD_ORCO) {
2670                         /* original coordinates */
2671                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2672
2673                         if(layer != -1) {
2674                                 attribs->totorco = 1;
2675
2676                                 attribs->orco.array = vdata->layers[layer].data;
2677                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2678                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2679                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2680                         }
2681                 }
2682         }
2683 }
2684
2685 /* Set object's bounding box based on DerivedMesh min/max data */
2686 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2687 {
2688         float min[3], max[3];
2689
2690         INIT_MINMAX(min, max);
2691
2692         dm->getMinMax(dm, min, max);
2693
2694         if(!ob->bb)
2695                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2696
2697         boundbox_set_from_min_max(ob->bb, min, max);
2698 }
2699
2700 /* --- NAVMESH (begin) --- */
2701 #ifdef WITH_GAMEENGINE
2702
2703 BM_INLINE int navmesh_bit(int a, int b)
2704 {
2705         return (a & (1 << b)) >> b;
2706 }
2707
2708 BM_INLINE void navmesh_intToCol(int i, float col[3])
2709 {
2710         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2711         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2712         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2713         col[0] = 1 - r*63.0f/255.0f;
2714         col[1] = 1 - g*63.0f/255.0f;
2715         col[2] = 1 - b*63.0f/255.0f;
2716 }
2717
2718 static void navmesh_drawColored(DerivedMesh *dm)
2719 {
2720         int a, glmode;
2721         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2722         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2723         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2724         float col[3];
2725
2726         if (!polygonIdx)
2727                 return;
2728
2729         /*
2730         //UI_ThemeColor(TH_WIRE);
2731         glDisable(GL_LIGHTING);
2732         glLineWidth(2.0);
2733         dm->drawEdges(dm, 0, 1);
2734         glLineWidth(1.0);
2735         glEnable(GL_LIGHTING);*/
2736
2737         glDisable(GL_LIGHTING);
2738         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2739                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2740                 //glShadeModel(GL_SMOOTH);
2741                 glBegin(glmode = GL_QUADS);
2742                 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2743                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2744                         int pi = polygonIdx[a];
2745                         if (pi <= 0) {
2746                                 zero_v3(col);
2747                         }
2748                         else {
2749                                 navmesh_intToCol(pi, col);
2750                         }
2751
2752                         if(new_glmode != glmode) {
2753                                 glEnd();
2754                                 glBegin(glmode = new_glmode);
2755                         }
2756                         glColor3fv(col);
2757                         glVertex3fv(mvert[mface->v1].co);
2758                         glVertex3fv(mvert[mface->v2].co);
2759                         glVertex3fv(mvert[mface->v3].co);
2760                         if(mface->v4) {
2761                                 glVertex3fv(mvert[mface->v4].co);
2762                         }
2763                 }
2764                 glEnd();
2765         }
2766         glEnable(GL_LIGHTING);
2767 }
2768
2769 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2770                         int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
2771                         int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
2772                         void *userData)
2773 {
2774         (void) setDrawOptions;
2775         (void) compareDrawOptions;
2776         (void) userData;
2777
2778         navmesh_drawColored(dm);
2779 }
2780
2781 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2782                                       float (*partial_redraw_planes)[4],
2783                                       int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2784 {
2785         (void) partial_redraw_planes;
2786         (void) setMaterial;
2787
2788         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2789         navmesh_drawColored(dm);
2790 }
2791
2792 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2793 {
2794         DerivedMesh *result;
2795         int maxFaces = dm->getNumPolys(dm);
2796         int *recastData;
2797         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2798         float* verts=NULL;
2799         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2800         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2801         int res;
2802
2803         result = CDDM_copy(dm);
2804         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2805                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2806                 if (sourceRecastData) {
2807                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2808                                                    sourceRecastData, maxFaces, "recastData");
2809                 }
2810         }
2811         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2812
2813         /* note: This is not good design! - really should not be doing this */
2814         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2815         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2816
2817
2818         /* process mesh */
2819         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2820                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2821                                              &trisToFacesMap);
2822         if (res) {
2823                 size_t polyIdx;
2824
2825                 /* invalidate concave polygon */
2826                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2827                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2828                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2829                                 /* set negative polygon idx to all faces */
2830                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2831                                 unsigned short tbase = dmesh[2];
2832                                 unsigned short tnum = dmesh[3];
2833                                 unsigned short ti;
2834
2835                                 for (ti=0; ti<tnum; ti++) {
2836                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2837                                         unsigned short faceidx = trisToFacesMap[triidx];
2838                                         if (recastData[faceidx] > 0) {
2839                                                 recastData[faceidx] = -recastData[faceidx];
2840                                         }
2841                                 }
2842                         }
2843                 }
2844         }
2845         else {
2846                 printf("Error during creation polygon infos\n");
2847         }
2848
2849         /* clean up */
2850         if (verts!=NULL)
2851                 MEM_freeN(verts);
2852         if (dtris!=NULL)
2853                 MEM_freeN(dtris);
2854         if (dmeshes!=NULL)
2855                 MEM_freeN(dmeshes);
2856         if (polys!=NULL)
2857                 MEM_freeN(polys);
2858         if (dtrisToPolysMap!=NULL)
2859                 MEM_freeN(dtrisToPolysMap);
2860         if (dtrisToTrisMap!=NULL)
2861                 MEM_freeN(dtrisToTrisMap);
2862         if (trisToFacesMap!=NULL)
2863                 MEM_freeN(trisToFacesMap);
2864
2865         return result;
2866 }
2867
2868 #endif /* WITH_GAMEENGINE */
2869
2870 /* --- NAVMESH (end) --- */
2871
2872
2873 void DM_init_origspace(DerivedMesh *dm)
2874 {
2875         static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
2876
2877         OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
2878         OrigSpaceLoop *lof;
2879         const int numpoly = dm->getNumPolys(dm);
2880         // const int numloop = dm->getNumLoops(dm);
2881         MPoly *mp = dm->getPolyArray(dm);
2882         int i, j;
2883
2884         for (i = 0; i < numpoly; i++, mp++) {
2885                 /* only quads/tri's for now */
2886                 if (mp->totloop == 3 || mp->totloop == 4) {
2887                         lof = lof_array + mp->loopstart;
2888                         for (j = 0; j < mp->totloop; j++, lof++) {
2889                                 copy_v2_v2(lof->uv, default_osf[j]);
2890                         }
2891                 }
2892         }
2893 }
2894
2895
2896
2897 /* derivedmesh info printing function,
2898  * to help track down differences DM output */
2899
2900 #ifndef NDEBUG
2901 #include "BLI_dynstr.h"
2902
2903 static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
2904 {
2905         int type;
2906
2907         for (type = 0; type < CD_NUMTYPES; type++) {
2908                 /* note: doesnt account for multiple layers */
2909                 void *pt = getElemDataArray(dm, type);
2910                 if (pt) {
2911                         const char *name = CustomData_layertype_name(type);
2912                         const int size = CustomData_sizeof(type);
2913                         const char *structname;
2914                         int structnum;
2915                         CustomData_file_write_info(type, &structname, &structnum);
2916                         BLI_dynstr_appendf(dynstr,
2917                                            "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
2918                                                            name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
2919                 }
2920         }
2921 }
2922
2923 char *DM_debug_info(DerivedMesh *dm)
2924 {
2925         DynStr *dynstr= BLI_dynstr_new();
2926         char *ret;
2927         const char *tstr;
2928
2929         BLI_dynstr_appendf(dynstr, "{\n");
2930         BLI_dynstr_appendf(dynstr, "    'ptr': '%p',\n", (void *)dm);
2931         switch (dm->type) {
2932                 case DM_TYPE_CDDM:     tstr = "DM_TYPE_CDDM";     break;
2933                 case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH";  break;
2934                 case DM_TYPE_CCGDM:    tstr = "DM_TYPE_CCGDM";     break;
2935                 default:               tstr = "UNKNOWN";           break;
2936         }
2937         BLI_dynstr_appendf(dynstr, "    'type': '%s',\n", tstr);
2938         BLI_dynstr_appendf(dynstr, "    'numVertData': %d,\n", dm->numVertData);
2939         BLI_dynstr_appendf(dynstr, "    'numEdgeData': %d,\n", dm->numEdgeData);
2940         BLI_dynstr_appendf(dynstr, "    'numTessFaceData': %d,\n", dm->numTessFaceData);
2941         BLI_dynstr_appendf(dynstr, "    'numPolyData': %d,\n", dm->numPolyData);
2942         BLI_dynstr_appendf(dynstr, "    'deformedOnly': %d,\n", dm->deformedOnly);
2943
2944         BLI_dynstr_appendf(dynstr, "    'vertexLayers': (\n");
2945         dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
2946         BLI_dynstr_appendf(dynstr, "    ),\n");
2947
2948         BLI_dynstr_appendf(dynstr, "    'loopLayers': (\n");
2949         dm_debug_info_layers(dynstr, dm, DM_get_loop_data_layer);
2950         BLI_dynstr_appendf(dynstr, "    ),\n");
2951
2952         BLI_dynstr_appendf(dynstr, "    'edgeLayers': (\n");
2953         dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
2954         BLI_dynstr_appendf(dynstr, "    ),\n");
2955
2956         BLI_dynstr_appendf(dynstr, "    'tessFaceLayers': (\n");
2957         dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
2958         BLI_dynstr_appendf(dynstr, "    ),\n");
2959
2960         BLI_dynstr_appendf(dynstr, "    'polyLayers': (\n");
2961         dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
2962         BLI_dynstr_appendf(dynstr, "    ),\n");
2963
2964         BLI_dynstr_appendf(dynstr, "}\n");
2965
2966         ret = BLI_dynstr_get_cstring(dynstr);
2967         BLI_dynstr_free(dynstr);
2968         return ret;
2969 }
2970
2971 void DM_debug_print(DerivedMesh *dm)
2972 {
2973         char *str = DM_debug_info(dm);
2974         printf("%s", str);
2975         fflush(stdout);
2976         MEM_freeN(str);
2977 }
2978
2979 #endif /* NDEBUG */