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