svn merge ^/trunk/blender -r41175:41200 --- will need to apply fix after
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2005 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/blenkernel/intern/DerivedMesh.c
31  *  \ingroup bke
32  */
33
34
35 #include <string.h>
36 #include "limits.h"
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_cloth_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_armature_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h" // N_T
46
47 #include "BLI_blenlib.h"
48 #include "BLI_editVert.h"
49 #include "BLI_math.h"
50 #include "BLI_memarena.h"
51 #include "BLI_array.h"
52 #include "BLI_pbvh.h"
53 #include "BLI_utildefines.h"
54 #include "BLI_linklist.h"
55
56 #include "BKE_cdderivedmesh.h"
57 #include "BKE_displist.h"
58 #include "BKE_key.h"
59 #include "BKE_modifier.h"
60 #include "BKE_mesh.h"
61 #include "BKE_object.h"
62 #include "BKE_paint.h"
63 #include "BKE_texture.h"
64 #include "BKE_multires.h"
65 #include "BKE_armature.h"
66 #include "BKE_particle.h"
67 #include "BKE_tessmesh.h"
68 #include "BKE_bvhutils.h"
69
70 #ifdef WITH_GAMEENGINE
71 #include "BKE_navmesh_conversion.h"
72 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
73 #endif
74
75 #include "BLO_sys_types.h" // for intptr_t support
76
77 #include "GL/glew.h"
78
79 #include "GPU_buffers.h"
80 #include "GPU_draw.h"
81 #include "GPU_extensions.h"
82 #include "GPU_material.h"
83
84 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
85
86 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
87 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
88
89 ///////////////////////////////////
90 ///////////////////////////////////
91
92 static MVert *dm_getVertArray(DerivedMesh *dm)
93 {
94         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
95
96         if (!mvert) {
97                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
98                         dm->getNumVerts(dm));
99                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
100                 dm->copyVertArray(dm, mvert);
101         }
102
103         return mvert;
104 }
105
106 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
107 {
108         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
109
110         if (!medge) {
111                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
112                         dm->getNumEdges(dm));
113                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
114                 dm->copyEdgeArray(dm, medge);
115         }
116
117         return medge;
118 }
119
120 static MFace *dm_getFaceArray(DerivedMesh *dm)
121 {
122         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
123
124         if (!mface) {
125                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
126                         dm->getNumTessFaces(dm));
127                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
128                 dm->copyTessFaceArray(dm, mface);
129         }
130
131         return mface;
132 }
133
134 static MLoop *dm_getLoopArray(DerivedMesh *dm)
135 {
136         MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
137
138         if (!mloop) {
139                 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
140                         dm->numLoopData);
141                 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
142                 dm->copyLoopArray(dm, mloop);
143         }
144
145         return mloop;
146 }
147
148 static MPoly *dm_getPolyArray(DerivedMesh *dm)
149 {
150         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
151
152         if (!mpoly) {
153                 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
154                         dm->getNumFaces(dm));
155                 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
156                 dm->copyPolyArray(dm, mpoly);
157         }
158
159         return mpoly;
160 }
161
162 static MVert *dm_dupVertArray(DerivedMesh *dm)
163 {
164         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
165                                                          "dm_dupVertArray tmp");
166
167         if(tmp) dm->copyVertArray(dm, tmp);
168
169         return tmp;
170 }
171
172 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
173 {
174         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
175                                                          "dm_dupEdgeArray tmp");
176
177         if(tmp) dm->copyEdgeArray(dm, tmp);
178
179         return tmp;
180 }
181
182 static MFace *dm_dupFaceArray(DerivedMesh *dm)
183 {
184         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
185                                                          "dm_dupFaceArray tmp");
186
187         if(tmp) dm->copyTessFaceArray(dm, tmp);
188
189         return tmp;
190 }
191
192 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
193 {
194         MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->numLoopData,
195                                                          "dm_dupLoopArray tmp");
196
197         if(tmp) dm->copyLoopArray(dm, tmp);
198
199         return tmp;
200 }
201
202 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
203 {
204         MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->numFaceData,
205                                                          "dm_dupPolyArray tmp");
206
207         if(tmp) dm->copyPolyArray(dm, tmp);
208
209         return tmp;
210 }
211
212 static CustomData *dm_getVertCData(DerivedMesh *dm)
213 {
214         return &dm->vertData;
215 }
216
217 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
218 {
219         return &dm->edgeData;
220 }
221
222 static CustomData *dm_getFaceCData(DerivedMesh *dm)
223 {
224         return &dm->faceData;
225 }
226
227 static CustomData *dm_getLoopCData(DerivedMesh *dm)
228 {
229         return &dm->loopData;
230 }
231
232 static CustomData *dm_getPolyCData(DerivedMesh *dm)
233 {
234         return &dm->polyData;
235 }
236
237 void DM_init_funcs(DerivedMesh *dm)
238 {
239         /* default function implementations */
240         dm->getVertArray = dm_getVertArray;
241         dm->getEdgeArray = dm_getEdgeArray;
242         dm->getTessFaceArray = dm_getFaceArray;
243         dm->getLoopArray = dm_getLoopArray;
244         dm->getPolyArray = dm_getPolyArray;
245         dm->dupVertArray = dm_dupVertArray;
246         dm->dupEdgeArray = dm_dupEdgeArray;
247         dm->dupTessFaceArray = dm_dupFaceArray;
248         dm->dupLoopArray = dm_dupLoopArray;
249         dm->dupPolyArray = dm_dupPolyArray;
250
251         dm->getVertDataLayout = dm_getVertCData;
252         dm->getEdgeDataLayout = dm_getEdgeCData;
253         dm->getTessFaceDataLayout = dm_getFaceCData;
254         dm->getLoopDataLayout = dm_getLoopCData;
255         dm->getFaceDataLayout = dm_getPolyCData;
256
257         dm->getVertData = DM_get_vert_data;
258         dm->getEdgeData = DM_get_edge_data;
259         dm->getTessFaceData = DM_get_face_data;
260         dm->getVertDataArray = DM_get_vert_data_layer;
261         dm->getEdgeDataArray = DM_get_edge_data_layer;
262         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
263
264         bvhcache_init(&dm->bvhCache);
265 }
266
267 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
268              int numFaces, int numLoops, int numPoly)
269 {
270         dm->type = type;
271         dm->numVertData = numVerts;
272         dm->numEdgeData = numEdges;
273         dm->numFaceData = numFaces;
274         dm->numLoopData = numLoops;
275         dm->numPolyData = numPoly;
276
277         DM_init_funcs(dm);
278         
279         dm->needsFree = 1;
280 }
281
282 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
283                       int numVerts, int numEdges, int numFaces,
284                       int numLoops, int numPolys)
285 {
286         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
287                                         CD_CALLOC, numVerts);
288         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
289                                         CD_CALLOC, numEdges);
290         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
291                                         CD_CALLOC, numFaces);
292         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
293                         CD_CALLOC, numLoops);
294         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
295                         CD_CALLOC, numPolys);
296
297         dm->type = type;
298         dm->numVertData = numVerts;
299         dm->numEdgeData = numEdges;
300         dm->numFaceData = numFaces;
301         dm->numLoopData = numLoops;
302         dm->numPolyData = numPolys;
303
304         DM_init_funcs(dm);
305
306         dm->needsFree = 1;
307 }
308
309 int DM_release(DerivedMesh *dm)
310 {
311         if (dm->needsFree) {
312                 bvhcache_free(&dm->bvhCache);
313                 GPU_drawobject_free( dm );
314                 CustomData_free(&dm->vertData, dm->numVertData);
315                 CustomData_free(&dm->edgeData, dm->numEdgeData);
316                 CustomData_free(&dm->faceData, dm->numFaceData);
317                 CustomData_free(&dm->loopData, dm->numLoopData);
318                 CustomData_free(&dm->polyData, dm->numPolyData);
319
320                 return 1;
321         }
322         else {
323                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
324                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
325                 CustomData_free_temporary(&dm->faceData, dm->numFaceData);
326                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
327                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
328
329                 return 0;
330         }
331 }
332
333 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
334 {
335         CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_CALLOC, source->numLoopData);
336         CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_CALLOC, source->numPolyData);
337
338         target->numLoopData = source->numLoopData;
339         target->numPolyData = source->numPolyData;
340
341         if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
342                 MPoly *mpoly;
343                 MLoop *mloop;
344
345                 mloop = source->dupLoopArray(source);
346                 mpoly = source->dupPolyArray(source);
347                 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
348                 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
349         }
350 }
351
352 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
353 {
354         /* dm might depend on me, so we need to do everything with a local copy */
355         Mesh tmp = *me;
356         int totvert, totedge, totface, totloop, totpoly;
357         int did_shapekeys=0;
358         
359         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
360         memset(&tmp.edata, 0, sizeof(tmp.edata));
361         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
362         memset(&tmp.ldata, 0, sizeof(tmp.ldata));
363         memset(&tmp.pdata, 0, sizeof(tmp.pdata));
364
365         totvert = tmp.totvert = dm->getNumVerts(dm);
366         totedge = tmp.totedge = dm->getNumEdges(dm);
367         totface = tmp.totface = dm->getNumTessFaces(dm);
368         totpoly = tmp.totpoly = dm->getNumFaces(dm);
369         totloop = tmp.totloop = dm->numLoopData;
370
371         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
372         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
373         CustomData_copy(&dm->faceData, &tmp.fdata, CD_MASK_MESH, CD_DUPLICATE, totface);
374         CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
375         CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
376
377         if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
378                 KeyBlock *kb;
379                 int i=0;
380                 
381                 if (ob) {
382                         for (kb=me->key->block.first; kb; kb=kb->next, i++) {
383                                 if (i == ob->shapenr-1) {
384                                         i = kb->uid;
385                                         break;
386                                 }
387                         }
388                         
389                         if (!kb) {
390                                 printf("error in DM_to_mesh: could not find active shapekey! eek!!\n");
391                                 i = INT_MAX;
392                         }
393                 } else {
394                         /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
395                         i = INT_MAX;
396                 }
397                 
398                 shapekey_layers_to_keyblocks(dm, me, i);
399                 did_shapekeys = 1;
400         }
401         
402         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
403            we set them here in case they are missing */
404         if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
405                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
406         if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
407                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
408         if(!CustomData_has_layer(&tmp.fdata, CD_MFACE))
409                 CustomData_add_layer(&tmp.fdata, CD_MFACE, CD_ASSIGN, dm->dupTessFaceArray(dm), totface);
410         if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
411                 tmp.mloop = dm->dupLoopArray(dm);
412                 tmp.mpoly = dm->dupPolyArray(dm);
413
414                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
415                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
416         }
417
418         /* object had got displacement layer, should copy this layer to save sculpted data */
419         /* NOTE: maybe some other layers should be copied? nazgul */
420         if(CustomData_has_layer(&me->ldata, CD_MDISPS)) {
421                 if (totloop == me->totloop) {
422                         MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
423                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
424                 }
425         }
426
427         mesh_update_customdata_pointers(&tmp);
428
429         CustomData_free(&me->vdata, me->totvert);
430         CustomData_free(&me->edata, me->totedge);
431         CustomData_free(&me->fdata, me->totface);
432         CustomData_free(&me->ldata, me->totloop);
433         CustomData_free(&me->pdata, me->totpoly);
434
435         /*  ok, this should now use new CD shapekey data,
436             which shouuld be fed through the modifier 
437                 stack*/
438         if(tmp.totvert != me->totvert && !did_shapekeys && me->key) {
439                 printf("YEEK! this should be recoded! Shape key loss!!!\n");
440                 if(tmp.key) tmp.key->id.us--;
441                 tmp.key = NULL;
442         }
443
444         *me = tmp;
445 }
446
447 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
448 {
449         int a, totvert = dm->getNumVerts(dm);
450         float *fp;
451         MVert *mvert;
452         
453         if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
454         
455         if(kb->data) MEM_freeN(kb->data);
456         kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
457         kb->totelem= totvert;
458         
459         fp= kb->data;
460         mvert=dm->getVertDataArray(dm, CD_MVERT);
461         
462         for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
463                 VECCOPY(fp, mvert->co);
464         }
465 }
466
467 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
468 {
469         CustomData_set_only_copy(&dm->vertData, mask);
470         CustomData_set_only_copy(&dm->edgeData, mask);
471         CustomData_set_only_copy(&dm->faceData, mask);
472 }
473
474 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
475 {
476         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
477 }
478
479 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
480 {
481         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
482 }
483
484 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
485 {
486         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numFaceData);
487 }
488
489 static void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
490 {
491         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
492 }
493
494 void DM_add_face_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
495 {
496         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
497 }
498
499 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
500 {
501         return CustomData_get(&dm->vertData, index, type);
502 }
503
504 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
505 {
506         return CustomData_get(&dm->edgeData, index, type);
507 }
508
509 void *DM_get_face_data(DerivedMesh *dm, int index, int type)
510 {
511         return CustomData_get(&dm->faceData, index, type);
512 }
513
514 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
515 {
516         if(type == CD_MVERT)
517                 return dm->getVertArray(dm);
518
519         return CustomData_get_layer(&dm->vertData, type);
520 }
521
522 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
523 {
524         if(type == CD_MEDGE)
525                 return dm->getEdgeArray(dm);
526
527         return CustomData_get_layer(&dm->edgeData, type);
528 }
529
530 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
531 {
532         if(type == CD_MFACE)
533                 return dm->getTessFaceArray(dm);
534
535         return CustomData_get_layer(&dm->faceData, type);
536 }
537
538 void *DM_get_face_data_layer(DerivedMesh *dm, int type)
539 {
540         return CustomData_get_layer(&dm->polyData, type);
541 }
542
543 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
544 {
545         CustomData_set(&dm->vertData, index, type, data);
546 }
547
548 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
549 {
550         CustomData_set(&dm->edgeData, index, type, data);
551 }
552
553 void DM_set_face_data(DerivedMesh *dm, int index, int type, void *data)
554 {
555         CustomData_set(&dm->faceData, index, type, data);
556 }
557
558 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
559                                            int source_index, int dest_index, int count)
560 {
561         CustomData_copy_data(&source->vertData, &dest->vertData,
562                                                  source_index, dest_index, count);
563 }
564
565 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
566                                            int source_index, int dest_index, int count)
567 {
568         CustomData_copy_data(&source->edgeData, &dest->edgeData,
569                                                  source_index, dest_index, count);
570 }
571
572 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
573                                            int source_index, int dest_index, int count)
574 {
575         CustomData_copy_data(&source->faceData, &dest->faceData,
576                                                  source_index, dest_index, count);
577 }
578
579 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
580                        int source_index, int dest_index, int count)
581 {
582         CustomData_copy_data(&source->loopData, &dest->loopData,
583                              source_index, dest_index, count);
584 }
585
586 void DM_copy_face_data(DerivedMesh *source, DerivedMesh *dest,
587                        int source_index, int dest_index, int count)
588 {
589         CustomData_copy_data(&source->polyData, &dest->polyData,
590                              source_index, dest_index, count);
591 }
592
593 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
594 {
595         CustomData_free_elem(&dm->vertData, index, count);
596 }
597
598 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
599 {
600         CustomData_free_elem(&dm->edgeData, index, count);
601 }
602
603 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
604 {
605         CustomData_free_elem(&dm->faceData, index, count);
606 }
607
608 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
609 {
610         CustomData_free_elem(&dm->loopData, index, count);
611 }
612
613 void DM_free_face_data(struct DerivedMesh *dm, int index, int count)
614 {
615         CustomData_free_elem(&dm->polyData, index, count);
616 }
617
618 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
619                                                  int *src_indices, float *weights,
620                                                  int count, int dest_index)
621 {
622         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
623                                           weights, NULL, count, dest_index);
624 }
625
626 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
627                                                  int *src_indices,
628                                                  float *weights, EdgeVertWeight *vert_weights,
629                                                  int count, int dest_index)
630 {
631         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
632                                           weights, (float*)vert_weights, count, dest_index);
633 }
634
635 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
636                                                  int *src_indices,
637                                                  float *weights, FaceVertWeight *vert_weights,
638                                                  int count, int dest_index)
639 {
640         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
641                                           weights, (float*)vert_weights, count, dest_index);
642 }
643
644 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
645 {
646         CustomData_swap(&dm->faceData, index, corner_indices);
647 }
648
649 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
650                          int *src_indices,
651                          float *weights, int count, int dest_index)
652 {
653         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
654                           weights, NULL, count, dest_index);
655 }
656
657 void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
658                          int *src_indices,
659                          float *weights, int count, int dest_index)
660 {
661         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
662                           weights, NULL, count, dest_index);
663 }
664
665 ///
666 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
667 {
668         DerivedMesh *dm = CDDM_from_mesh(me, ob);
669         
670         if(!dm)
671                 return NULL;
672         
673         if (vertCos)
674                 CDDM_apply_vert_coords(dm, vertCos);
675
676         CDDM_calc_normals(dm);
677
678         return dm;
679 }
680
681 /***/
682
683 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
684         ModifierData *md, int build_shapekey_layers)
685 {
686         Mesh *me = ob->data;
687         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
688         DerivedMesh *dm;
689
690         md->scene= scene;
691         
692         if (!(md->mode&eModifierMode_Realtime)) return NULL;
693         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
694         
695         if (build_shapekey_layers && me->key && ob->shapenr <= BLI_countlist(&me->key->block)) {
696                 key_to_mesh(BLI_findlink(&me->key->block, ob->shapenr-1), me);
697         }
698         
699         if (mti->type==eModifierTypeType_OnlyDeform) {
700                 int numVerts;
701                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
702
703                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
704                 dm = mesh_create_derived(me, ob, deformedVerts);
705
706                 if (build_shapekey_layers)
707                         add_shapekey_layers(dm, me, ob);
708                 
709                 MEM_freeN(deformedVerts);
710         } else {
711                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
712
713                 if (build_shapekey_layers)
714                         add_shapekey_layers(tdm, me, ob);
715                 
716                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
717
718                 if(tdm != dm) tdm->release(tdm);
719         }
720
721         return dm;
722 }
723
724 static float *get_editbmesh_orco_verts(BMEditMesh *em)
725 {
726         BMIter iter;
727         BMVert *eve;
728         float *orco;
729         int a, totvert;
730
731         /* these may not really be the orco's, but it's only for preview.
732          * could be solver better once, but isn't simple */
733
734         totvert= em->bm->totvert;
735         
736         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
737
738         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
739         for (a=0; eve; eve=BMIter_Step(&iter), a+=3)
740                 VECCOPY(orco+a, eve->co);
741         
742         return orco;
743 }
744
745 /* orco custom data layer */
746 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
747 {
748         *free= 0;
749
750         if(layer == CD_ORCO) {
751                 /* get original coordinates */
752                 *free= 1;
753
754                 if(em)
755                         return (float(*)[3])get_editbmesh_orco_verts(em);
756                 else
757                         return (float(*)[3])get_mesh_orco_verts(ob);
758         }
759         else if(layer == CD_CLOTH_ORCO) {
760                 /* apply shape key for cloth, this should really be solved
761                    by a more flexible customdata system, but not simple */
762                 if(!em) {
763                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
764                         if (clmd) {
765                                 KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
766         
767                                 if(kb->data)
768                                         return kb->data;
769                         }
770                 }
771
772                 return NULL;
773         }
774
775         return NULL;
776 }
777
778 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
779 {
780         DerivedMesh *dm;
781         float (*orco)[3];
782         int free;
783
784         if(em) dm= CDDM_from_BMEditMesh(em, me, 0);
785         else dm= CDDM_from_mesh(me, ob);
786
787         orco= get_orco_coords_dm(ob, em, layer, &free);
788
789         if(orco) {
790                 CDDM_apply_vert_coords(dm, orco);
791                 if(free) MEM_freeN(orco);
792         }
793
794         CDDM_calc_normals(dm);
795
796         return dm;
797 }
798
799 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
800                                                 DerivedMesh *orcodm, int layer)
801 {
802         float (*orco)[3], (*layerorco)[3];
803         int totvert, free;
804
805         totvert= dm->getNumVerts(dm);
806
807         if(orcodm) {
808                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
809                 free= 1;
810
811                 if(orcodm->getNumVerts(orcodm) == totvert)
812                         orcodm->getVertCos(orcodm, orco);
813                 else
814                         dm->getVertCos(dm, orco);
815         }
816         else
817                 orco= get_orco_coords_dm(ob, em, layer, &free);
818
819         if(orco) {
820                 if(layer == CD_ORCO)
821                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
822
823                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
824                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
825                         layerorco = DM_get_vert_data_layer(dm, layer);
826                 }
827
828                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
829                 if(free) MEM_freeN(orco);
830         }
831 }
832
833 /* weight paint colors */
834
835 /* Something of a hack, at the moment deal with weightpaint
836  * by tucking into colors during modifier eval, only in
837  * wpaint mode. Works ok but need to make sure recalc
838  * happens on enter/exit wpaint.
839  */
840
841 void weight_to_rgb(float input, float *fr, float *fg, float *fb)
842 {
843         float blend;
844         
845         blend= ((input/2.0f)+0.5f);
846         
847         if (input<=0.25f){      // blue->cyan
848                 *fr= 0.0f;
849                 *fg= blend*input*4.0f;
850                 *fb= blend;
851         }
852         else if (input<=0.50f){ // cyan->green
853                 *fr= 0.0f;
854                 *fg= blend;
855                 *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
856         }
857         else if (input <= 0.75f){       // green->yellow
858                 *fr= blend * ((input-0.50f)*4.0f);
859                 *fg= blend;
860                 *fb= 0.0f;
861         }
862         else if (input <= 1.0f){ // yellow->red
863                 *fr= blend;
864                 *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
865                 *fb= 0.0f;
866         }
867 }
868
869 /* draw_flag's for calc_weightpaint_vert_color */
870 enum {
871         CALC_WP_MULTIPAINT= (1<<0),
872         CALC_WP_AUTO_NORMALIZE= (1<<1),
873 };
874
875 static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, unsigned char *col, char *dg_flags, int selected, int UNUSED(unselected), const int draw_flag)
876 {
877         Mesh *me = ob->data;
878         float colf[4], input = 0.0f;
879         int i;
880
881         
882         int make_black= FALSE;
883
884         if (me->dvert) {
885                 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
886                         
887                         int was_a_nonzero= FALSE;
888                         for (i=0; i<me->dvert[vert].totweight; i++) {
889                                 /* in multipaint, get the average if auto normalize is inactive
890                                  * get the sum if it is active */
891                                 if(dg_flags[me->dvert[vert].dw[i].def_nr]) {
892                                         if(me->dvert[vert].dw[i].weight) {
893                                                 input+= me->dvert[vert].dw[i].weight;
894                                                 was_a_nonzero= TRUE;
895                                         }
896                                 }
897                         }
898
899                         /* make it black if the selected groups have no weight on a vertex */
900                         if(was_a_nonzero == FALSE) {
901                                 make_black = TRUE;
902                         }
903                         else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
904                                 input /= selected; /* get the average */
905                         }
906                 }
907                 else {
908                         /* default, non tricky behavior */
909                         for (i=0; i<me->dvert[vert].totweight; i++) {
910                                 if (me->dvert[vert].dw[i].def_nr==ob->actdef-1) {
911                                         input+=me->dvert[vert].dw[i].weight;
912                                 }
913                         }
914                 }
915         }
916         
917         if (make_black) {
918                 col[3] = 0;
919                 col[2] = 0;
920                 col[1] = 0;
921                 col[0] = 255;
922                 return;
923         }
924
925         CLAMP(input, 0.0f, 1.0f);       
926
927         if(coba)
928                 do_colorband(coba, input, colf);
929         else
930                 weight_to_rgb(input, colf, colf+1, colf+2);
931         
932         col[3] = (unsigned char)(colf[0] * 255.0f);
933         col[2] = (unsigned char)(colf[1] * 255.0f);
934         col[1] = (unsigned char)(colf[2] * 255.0f);
935         col[0] = 255;
936 }
937
938 static ColorBand *stored_cb= NULL;
939
940 void vDM_ColorBand_store(ColorBand *coba)
941 {
942         stored_cb= coba;
943 }
944
945 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
946 {
947         // Mesh *me = ob->data; // UNUSED
948         MFace *mf = dm->getTessFaceArray(dm);
949         MLoop *mloop = dm->getLoopArray(dm), *ml;
950         MPoly *mp = dm->getPolyArray(dm);
951         ColorBand *coba= stored_cb;     /* warning, not a local var */
952         unsigned char *wtcol;
953         unsigned char(*wlcol)[4] = NULL;
954         BLI_array_declare(wlcol);
955         int i, j, totface=dm->getNumTessFaces(dm), totloop;
956         int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
957
958         int defbase_len = BLI_countlist(&ob->defbase);
959         char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
960         int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
961         int unselected = defbase_len - selected;
962
963         wtcol = MEM_callocN (sizeof (unsigned char) * totface*4*4, "weightmap");
964         
965         /*first add colors to the tesselation faces*/
966         memset(wtcol, 0x55, sizeof (unsigned char) * totface*4*4);
967         for (i=0; i<totface; i++, mf++) {
968                 /*origindex being NULL means we're operating on original mesh data*/
969                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
970                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
971                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
972                 if (mf->v4)
973                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
974         }
975         
976         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, totface);
977
978         /*now add to loops, so the data can be passed through the modifier stack*/
979         totloop = 0;
980         for (i=0; i<dm->numPolyData; i++, mp++) {
981                 ml = mloop + mp->loopstart;
982
983                 for (j=0; j<mp->totloop; j++, ml++, totloop++) {
984                         BLI_array_growone(wlcol);
985
986                         calc_weightpaint_vert_color(ob, coba, origIndex ? origIndex[ml->v] : ml->v,
987                                                                                 (unsigned char *)&wlcol[totloop], defbase_sel, selected, unselected, draw_flag);
988                 }
989         }
990
991         MEM_freeN(defbase_sel);
992
993         CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wlcol, totloop);
994 }
995
996
997 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
998 {
999         KeyBlock *kb;
1000         int i, j, tot;
1001         
1002         if (!me->key)
1003                 return; 
1004         
1005         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1006         for (i=0; i<tot; i++) {
1007                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1008                 float (*cos)[3], (*kbcos)[3];
1009                 
1010                 for (kb=me->key->block.first; kb; kb=kb->next) {
1011                         if (kb->uid == layer->uid)
1012                                 break;
1013                 }
1014                 
1015                 if (!kb) {
1016                         kb = add_keyblock(me->key, layer->name);
1017                         kb->uid = layer->uid;
1018                 }
1019                 
1020                 if (kb->data)
1021                         MEM_freeN(kb->data);
1022                 
1023                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1024                 kb->totelem = dm->numVertData;
1025
1026                 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1027                 if (kb->uid == actshape_uid) {
1028                         MVert *mvert = dm->getVertArray(dm);
1029                         
1030                         for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1031                                 copy_v3_v3(*kbcos, mvert->co);
1032                         }
1033                 } else {
1034                         for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1035                                 copy_v3_v3(*kbcos, *cos);
1036                         }
1037                 }
1038         }
1039         
1040         for (kb=me->key->block.first; kb; kb=kb->next) {
1041                 if (kb->totelem != dm->numVertData) {
1042                         if (kb->data)
1043                                 MEM_freeN(kb->data);
1044                         
1045                         kb->totelem = dm->numVertData;
1046                         kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1047                         fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1048                 }
1049         }
1050 }
1051
1052 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1053 {
1054         KeyBlock *kb;
1055         Key *key = me->key;
1056         int a, b;
1057         
1058         if (!me->key)
1059                 return;
1060         
1061         if (dm->numVertData != me->totvert) {
1062                 printf("error in add_shapekey_layers: dm isn't the same size as me\n");
1063                 return;
1064         }
1065                 
1066         for (a=0, kb=key->block.first; kb; kb=kb->next, a++) {
1067                 float (*cos)[3] = CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_CALLOC, NULL, dm->numVertData, kb->name);
1068                 int ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, a);
1069                 
1070                 dm->vertData.layers[ci].uid = kb->uid;
1071                 if (kb->totelem != dm->numVertData) {
1072                         printf("error in add_shapekey_layers: totelem and totvert don't match");
1073                         continue;
1074                 }
1075                 
1076                 for (b=0; b<kb->totelem; b++, cos++) {
1077                         copy_v3_v3((float *)cos, ((float*)kb->data)+b*3);
1078                 }
1079         }
1080 }
1081
1082 /* new value for useDeform -1  (hack for the gameengine):
1083  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1084  * - don't apply the key
1085  * - apply deform modifiers and input vertexco
1086  */
1087 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1088                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1089                                                                 int useRenderParams, int useDeform,
1090                                                                 int needMapping, CustomDataMask dataMask, 
1091                                                                 int index, int useCache, int build_shapekey_layers)
1092 {
1093         Mesh *me = ob->data;
1094         ModifierData *firstmd, *md;
1095         LinkNode *datamasks, *curr;
1096         CustomDataMask mask, nextmask;
1097         float (*deformedVerts)[3] = NULL;
1098         DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1099         int numVerts = me->totvert;
1100         int required_mode;
1101         int isPrevDeform= FALSE;
1102         int skipVirtualArmature = (useDeform < 0);
1103         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1104         int has_multires = mmd != NULL, multires_applied = 0;
1105         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1106
1107         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1108                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1109
1110         if(mmd && !mmd->sculptlvl)
1111                 has_multires = 0;
1112
1113         if(!skipVirtualArmature) {
1114                 firstmd = modifiers_getVirtualModifierList(ob);
1115         }
1116         else {
1117                 /* game engine exception */
1118                 firstmd = ob->modifiers.first;
1119                 if(firstmd && firstmd->type == eModifierType_Armature)
1120                         firstmd = firstmd->next;
1121         }
1122
1123         md = firstmd;
1124
1125         modifiers_clearErrors(ob);
1126
1127         if(useRenderParams) required_mode = eModifierMode_Render;
1128         else required_mode = eModifierMode_Realtime;
1129
1130         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1131         curr = datamasks;
1132
1133         if(deform_r) *deform_r = NULL;
1134         *final_r = NULL;
1135
1136         if(useDeform) {
1137                 if(inputVertexCos)
1138                         deformedVerts = inputVertexCos;
1139                 
1140                 /* Apply all leading deforming modifiers */
1141                 for(;md; md = md->next, curr = curr->next) {
1142                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1143
1144                         md->scene= scene;
1145                         
1146                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1147                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1148
1149                         if(mti->type == eModifierTypeType_OnlyDeform) {
1150                                 if(!deformedVerts)
1151                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1152
1153                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1154                         } else {
1155                                 break;
1156                         }
1157                         
1158                         /* grab modifiers until index i */
1159                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1160                                 break;
1161                 }
1162
1163                 /* Result of all leading deforming modifiers is cached for
1164                  * places that wish to use the original mesh but with deformed
1165                  * coordinates (vpaint, etc.)
1166                  */
1167                 if (deform_r) {
1168                         *deform_r = CDDM_from_mesh(me, ob);
1169                         
1170                         if (build_shapekey_layers)
1171                                 add_shapekey_layers(dm, me, ob);
1172                         
1173                         if(deformedVerts) {
1174                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1175                                 CDDM_calc_normals(*deform_r);
1176                         }
1177                 }
1178         } else {
1179                 /* default behaviour for meshes */
1180                 if(inputVertexCos)
1181                         deformedVerts = inputVertexCos;
1182                 else
1183                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1184         }
1185
1186
1187         /* Now apply all remaining modifiers. If useDeform is off then skip
1188          * OnlyDeform ones. 
1189          */
1190         dm = NULL;
1191         orcodm = NULL;
1192         clothorcodm = NULL;
1193
1194         for(;md; md = md->next, curr = curr->next) {
1195                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1196
1197                 md->scene= scene;
1198
1199                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1200                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1201                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1202                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1203                         continue;
1204                 }
1205                 if(sculpt_mode && (!has_multires || multires_applied)) {
1206                         int unsupported= 0;
1207
1208                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1209                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1210
1211                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1212                         unsupported|= multires_applied;
1213
1214                         if(unsupported) {
1215                                 modifier_setError(md, "Not supported in sculpt mode.");
1216                                 continue;
1217                         }
1218                 }
1219                 if(needMapping && !modifier_supportsMapping(md)) continue;
1220                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1221
1222                 /* add an orco layer if needed by this modifier */
1223                 if(mti->requiredDataMask)
1224                         mask = mti->requiredDataMask(ob, md);
1225                 else
1226                         mask = 0;
1227
1228                 if(dm && (mask & CD_MASK_ORCO))
1229                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1230
1231                 /* How to apply modifier depends on (a) what we already have as
1232                  * a result of previous modifiers (could be a DerivedMesh or just
1233                  * deformed vertices) and (b) what type the modifier is.
1234                  */
1235
1236                 if(mti->type == eModifierTypeType_OnlyDeform) {
1237                         /* No existing verts to deform, need to build them. */
1238                         if(!deformedVerts) {
1239                                 if(dm) {
1240                                         /* Deforming a derived mesh, read the vertex locations
1241                                          * out of the mesh and deform them. Once done with this
1242                                          * run of deformers verts will be written back.
1243                                          */
1244                                         numVerts = dm->getNumVerts(dm);
1245                                         deformedVerts =
1246                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1247                                         dm->getVertCos(dm, deformedVerts);
1248                                 } else {
1249                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1250                                 }
1251                         }
1252
1253                         /* if this is not the last modifier in the stack then recalculate the normals
1254                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1255                         if(dm && isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1256                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1257                                 if(dm && dm->type == DM_TYPE_CDDM) {
1258                                         CDDM_apply_vert_coords(dm, deformedVerts);
1259                                         CDDM_calc_normals(dm);
1260                                 }
1261                         }
1262
1263                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1264                 } else {
1265                         DerivedMesh *ndm;
1266
1267                         /* determine which data layers are needed by following modifiers */
1268                         if(curr->next)
1269                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1270                         else
1271                                 nextmask= dataMask;
1272
1273                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1274                         if(dm) {
1275                                 if(deformedVerts) {
1276                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1277                                         dm->release(dm);
1278                                         dm = tdm;
1279
1280                                         CDDM_apply_vert_coords(dm, deformedVerts);
1281                                         CDDM_calc_normals(dm);
1282                                 }
1283                         } else {
1284                                 dm = CDDM_from_mesh(me, ob);
1285
1286                                 if (build_shapekey_layers)
1287                                         add_shapekey_layers(dm, me, ob);
1288
1289                                 if(deformedVerts) {
1290                                         CDDM_apply_vert_coords(dm, deformedVerts);
1291                                         CDDM_calc_normals(dm);
1292                                 }
1293
1294                                 /* Constructive modifiers need to have an origindex
1295                                  * otherwise they wont have anywhere to copy the data from.
1296                                  *
1297                                  * Also create ORIGINDEX data if any of the following modifiers
1298                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1299                                  * data by using generic DM_copy_vert_data() functions.
1300                                  */
1301                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1302                                         /* calc */
1303                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1304                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1305                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1306
1307                                         range_vni(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1308                                         range_vni(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1309                                         range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1310                                 }
1311
1312                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1313                                         add_weight_mcol_dm(ob, dm, draw_flag);
1314
1315                         }
1316
1317                         
1318                         /* set the DerivedMesh to only copy needed data */
1319                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1320                         /* needMapping check here fixes bug [#28112], otherwise its
1321                          * possible that it wont be copied */
1322                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1323                         
1324                         /* add cloth rest shape key if need */
1325                         if(mask & CD_MASK_CLOTH_ORCO)
1326                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1327
1328                         /* add an origspace layer if needed */
1329                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1330                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1331                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1332
1333                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1334
1335                         if(ndm) {
1336                                 /* if the modifier returned a new dm, release the old one */
1337                                 if(dm && dm != ndm) dm->release(dm);
1338
1339                                 dm = ndm;
1340
1341                                 if(deformedVerts) {
1342                                         if(deformedVerts != inputVertexCos)
1343                                                 MEM_freeN(deformedVerts);
1344
1345                                         deformedVerts = NULL;
1346                                 }
1347                         } 
1348
1349                         /* create an orco derivedmesh in parallel */
1350                         if(nextmask & CD_MASK_ORCO) {
1351                                 if(!orcodm)
1352                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1353
1354                                 nextmask &= ~CD_MASK_ORCO;
1355                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1356                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1357
1358                                 if(ndm) {
1359                                         /* if the modifier returned a new dm, release the old one */
1360                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1361                                         orcodm = ndm;
1362                                 }
1363                         }
1364
1365                         /* create cloth orco derivedmesh in parallel */
1366                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1367                                 if(!clothorcodm)
1368                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1369
1370                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1371                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1372                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1373
1374                                 if(ndm) {
1375                                         /* if the modifier returned a new dm, release the old one */
1376                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1377                                         clothorcodm = ndm;
1378                                 }
1379                         }
1380                 }
1381
1382                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1383
1384                 /* grab modifiers until index i */
1385                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1386                         break;
1387
1388                 if(sculpt_mode && md->type == eModifierType_Multires)
1389                         multires_applied = 1;
1390         }
1391
1392         for(md=firstmd; md; md=md->next)
1393                 modifier_freeTemporaryData(md);
1394
1395         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1396          * need to apply these back onto the DerivedMesh. If we have no
1397          * DerivedMesh then we need to build one.
1398          */
1399         if(dm && deformedVerts) {
1400                 finaldm = CDDM_copy(dm, 0);
1401
1402                 dm->release(dm);
1403
1404                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1405                 CDDM_calc_normals(finaldm);
1406
1407                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1408                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1409         } else if(dm) {
1410                 finaldm = dm;
1411         } else {
1412                 int recalc_normals= 0;
1413
1414                 finaldm = CDDM_from_mesh(me, ob);
1415                 
1416                 if(build_shapekey_layers) {
1417                         add_shapekey_layers(finaldm, me, ob);
1418                         recalc_normals= 1;
1419                 }
1420                 
1421                 if(deformedVerts) {
1422                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1423                         recalc_normals= 1;
1424                 }
1425
1426                 if(recalc_normals)
1427                         CDDM_calc_normals(finaldm);
1428                 
1429                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1430                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1431         }
1432
1433         /* add an orco layer if needed */
1434         if(dataMask & CD_MASK_ORCO) {
1435                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1436
1437                 if(deform_r && *deform_r)
1438                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1439         }
1440
1441 #ifdef WITH_GAMEENGINE
1442         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1443         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1444                 DerivedMesh *tdm;
1445                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1446                 if (finaldm != tdm) {
1447                         finaldm->release(finaldm);
1448                         finaldm= tdm;
1449                 }
1450         }
1451 #endif /* WITH_GAMEENGINE */
1452
1453         *final_r = finaldm;
1454
1455         if(orcodm)
1456                 orcodm->release(orcodm);
1457         if(clothorcodm)
1458                 clothorcodm->release(clothorcodm);
1459
1460         if(deformedVerts && deformedVerts != inputVertexCos)
1461                 MEM_freeN(deformedVerts);
1462
1463         BLI_linklist_free(datamasks, NULL);
1464 }
1465
1466 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1467 {
1468         int i, numVerts = *numVerts_r = em->bm->totvert;
1469         float (*cos)[3];
1470         BMIter iter;
1471         BMVert *eve;
1472
1473         cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1474
1475         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1476         for (i=0; eve; eve=BMIter_Step(&iter), i++) {
1477                 VECCOPY(cos[i], eve->co);
1478         }
1479
1480         return cos;
1481 }
1482
1483 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1484 {
1485         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1486         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1487
1488         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1489         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1490                 modifier_setError(md, "Modifier requires original data, bad stack position.");
1491                 return 0;
1492         }
1493         
1494         return 1;
1495 }
1496
1497 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1498                                                                         DerivedMesh **final_r,
1499                                                                         CustomDataMask dataMask)
1500 {
1501         ModifierData *md;
1502         float (*deformedVerts)[3] = NULL;
1503         CustomDataMask mask;
1504         DerivedMesh *dm, *orcodm = NULL;
1505         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1506         LinkNode *datamasks, *curr;
1507         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1508
1509         modifiers_clearErrors(ob);
1510
1511         if(cage_r && cageIndex == -1) {
1512                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1513         }
1514
1515         dm = NULL;
1516         md = modifiers_getVirtualModifierList(ob);
1517
1518         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1519
1520         curr = datamasks;
1521         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1522                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1523
1524                 md->scene= scene;
1525                 
1526                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1527                         continue;
1528
1529                 /* add an orco layer if needed by this modifier */
1530                 if(dm && mti->requiredDataMask) {
1531                         mask = mti->requiredDataMask(ob, md);
1532                         if(mask & CD_MASK_ORCO)
1533                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1534                 }
1535
1536                 /* How to apply modifier depends on (a) what we already have as
1537                  * a result of previous modifiers (could be a DerivedMesh or just
1538                  * deformed vertices) and (b) what type the modifier is.
1539                  */
1540
1541                 if(mti->type == eModifierTypeType_OnlyDeform) {
1542                         /* No existing verts to deform, need to build them. */
1543                         if(!deformedVerts) {
1544                                 if(dm) {
1545                                         /* Deforming a derived mesh, read the vertex locations
1546                                          * out of the mesh and deform them. Once done with this
1547                                          * run of deformers verts will be written back.
1548                                          */
1549                                         numVerts = dm->getNumVerts(dm);
1550                                         deformedVerts =
1551                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1552                                         dm->getVertCos(dm, deformedVerts);
1553                                 } else {
1554                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1555                                 }
1556                         }
1557
1558                         if (mti->deformVertsEM)
1559                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1560                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1561                 } else {
1562                         DerivedMesh *ndm;
1563
1564                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1565                         if(dm) {
1566                                 if(deformedVerts) {
1567                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1568                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1569                                         dm = tdm;
1570
1571                                         CDDM_apply_vert_coords(dm, deformedVerts);
1572                                         CDDM_calc_normals(dm);
1573                                 } else if(cage_r && dm == *cage_r) {
1574                                         /* dm may be changed by this modifier, so we need to copy it
1575                                          */
1576                                         dm = CDDM_copy(dm, 0);
1577                                 }
1578
1579                         } else {
1580                                 dm = CDDM_from_BMEditMesh(em, ob->data, 0);
1581
1582                                 if(deformedVerts) {
1583                                         CDDM_apply_vert_coords(dm, deformedVerts);
1584                                         CDDM_calc_normals(dm);
1585                                 }
1586                         }
1587
1588                         /* create an orco derivedmesh in parallel */
1589                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1590                         if(mask & CD_MASK_ORCO) {
1591                                 if(!orcodm)
1592                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1593
1594                                 mask &= ~CD_MASK_ORCO;
1595                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1596
1597                                 if (mti->applyModifierEM)
1598                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1599                                 else
1600                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1601
1602                                 if(ndm) {
1603                                         /* if the modifier returned a new dm, release the old one */
1604                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1605                                         orcodm = ndm;
1606                                 }
1607                         }
1608
1609                         /* set the DerivedMesh to only copy needed data */
1610                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1611
1612                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1613
1614                         if(mask & CD_MASK_ORIGSPACE)
1615                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1616                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1617                         
1618                         if (mti->applyModifierEM)
1619                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1620                         else
1621                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1622
1623                         if (ndm) {
1624                                 if(dm && dm != ndm)
1625                                         dm->release(dm);
1626
1627                                 dm = ndm;
1628
1629                                 if (deformedVerts) {
1630                                         MEM_freeN(deformedVerts);
1631                                         deformedVerts = NULL;
1632                                 }
1633                         }
1634                 }
1635
1636                 if(cage_r && i == cageIndex) {
1637                         if(dm && deformedVerts) {
1638                                 *cage_r = CDDM_copy(dm, 0);
1639                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1640                         } else if(dm) {
1641                                 *cage_r = dm;
1642                         } else {
1643                                 *cage_r =
1644                                         getEditDerivedBMesh(em, ob,
1645                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1646                         }
1647                 }
1648         }
1649
1650         BLI_linklist_free(datamasks, NULL);
1651
1652         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1653          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1654          * then we need to build one.
1655          */
1656         if(dm && deformedVerts) {
1657                 *final_r = CDDM_copy(dm, 0);
1658
1659                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1660
1661                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1662                 CDDM_calc_normals(*final_r);
1663         } else if (dm) {
1664                 *final_r = dm;
1665         } else if (!deformedVerts && cage_r && *cage_r) {
1666                 *final_r = *cage_r;
1667         } else {
1668                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1669                 deformedVerts = NULL;
1670         }
1671
1672         /* add an orco layer if needed */
1673         if(dataMask & CD_MASK_ORCO)
1674                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1675
1676         if(orcodm)
1677                 orcodm->release(orcodm);
1678
1679         if(deformedVerts)
1680                 MEM_freeN(deformedVerts);
1681 }
1682
1683 static void clear_mesh_caches(Object *ob)
1684 {
1685         Mesh *me= ob->data;
1686
1687                 /* also serves as signal to remake texspace */
1688         if (ob->bb) {
1689                 MEM_freeN(ob->bb);
1690                 ob->bb = NULL;
1691         }
1692         if (me->bb) {
1693                 MEM_freeN(me->bb);
1694                 me->bb = NULL;
1695         }
1696
1697         freedisplist(&ob->disp);
1698
1699         if (ob->derivedFinal) {
1700                 ob->derivedFinal->needsFree = 1;
1701                 ob->derivedFinal->release(ob->derivedFinal);
1702                 ob->derivedFinal= NULL;
1703         }
1704         if (ob->derivedDeform) {
1705                 ob->derivedDeform->needsFree = 1;
1706                 ob->derivedDeform->release(ob->derivedDeform);
1707                 ob->derivedDeform= NULL;
1708         }
1709
1710         if(ob->sculpt) {
1711                 object_sculpt_modifiers_changed(ob);
1712         }
1713 }
1714
1715 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1716         int build_shapekey_layers)
1717 {
1718         Object *obact = scene->basact?scene->basact->object:NULL;
1719         int editing = paint_facesel_test(ob);
1720         /* weight paint and face select need original indices because of selection buffer drawing */
1721         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
1722
1723         clear_mesh_caches(ob);
1724
1725         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1726                                                 &ob->derivedFinal, 0, 1,
1727                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
1728
1729         DM_set_object_boundbox (ob, ob->derivedFinal);
1730
1731         ob->derivedFinal->needsFree = 0;
1732         ob->derivedDeform->needsFree = 0;
1733         ob->lastDataMask = dataMask;
1734 }
1735
1736 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1737 {
1738         clear_mesh_caches(obedit);
1739
1740         if (em->derivedFinal) {
1741                 if (em->derivedFinal!=em->derivedCage) {
1742                         em->derivedFinal->needsFree = 1;
1743                         em->derivedFinal->release(em->derivedFinal);
1744                 }
1745                 em->derivedFinal = NULL;
1746         }
1747         if (em->derivedCage) {
1748                 em->derivedCage->needsFree = 1;
1749                 em->derivedCage->release(em->derivedCage);
1750                 em->derivedCage = NULL;
1751         }
1752
1753         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1754         DM_set_object_boundbox (obedit, em->derivedFinal);
1755
1756         em->lastDataMask = dataMask;
1757         em->derivedFinal->needsFree = 0;
1758         em->derivedCage->needsFree = 0;
1759 }
1760
1761 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
1762         CustomDataMask dataMask, int build_shapekey_layers)
1763 {
1764         if (em) {
1765                 editbmesh_build_data(scene, ob, em, dataMask);
1766         } else {
1767                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
1768         }
1769 }
1770
1771 /***/
1772
1773 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
1774 {
1775         /* if there's no derived mesh or the last data mask used doesn't include
1776          * the data we need, rebuild the derived mesh
1777          */
1778         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
1779                 mesh_build_data(scene, ob, dataMask, 0);
1780
1781         return ob->derivedFinal;
1782 }
1783
1784 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
1785 {
1786         /* if there's no derived mesh or the last data mask used doesn't include
1787          * the data we need, rebuild the derived mesh
1788          */
1789         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
1790                 mesh_build_data(scene, ob, dataMask, 0);
1791
1792         return ob->derivedDeform;
1793 }
1794
1795 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
1796 {
1797         DerivedMesh *final;
1798         
1799         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
1800
1801         return final;
1802 }
1803
1804 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
1805 {
1806         DerivedMesh *final;
1807         
1808         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
1809
1810         return final;
1811 }
1812
1813 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
1814 {
1815         DerivedMesh *final;
1816
1817         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
1818
1819         return final;
1820 }
1821
1822 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
1823                                                                                    CustomDataMask dataMask)
1824 {
1825         DerivedMesh *final;
1826         
1827         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
1828
1829         return final;
1830 }
1831
1832 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
1833                                                                                         CustomDataMask dataMask)
1834 {
1835         DerivedMesh *final;
1836         
1837         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
1838
1839         return final;
1840 }
1841
1842 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
1843                                                                                         CustomDataMask dataMask)
1844 {
1845         DerivedMesh *final;
1846         
1847         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
1848
1849         return final;
1850 }
1851
1852 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
1853                                                                                                   float (*vertCos)[3],
1854                                                                                                   CustomDataMask dataMask)
1855 {
1856         DerivedMesh *final;
1857
1858         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
1859
1860         return final;
1861 }
1862
1863 /***/
1864
1865 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
1866                                                                                                  CustomDataMask dataMask)
1867 {
1868         /* if there's no derived mesh or the last data mask used doesn't include
1869          * the data we need, rebuild the derived mesh
1870          */
1871         if(!em->derivedCage ||
1872            (em->lastDataMask & dataMask) != dataMask)
1873                 editbmesh_build_data(scene, obedit, em, dataMask);
1874
1875         *final_r = em->derivedFinal;
1876         return em->derivedCage;
1877 }
1878
1879 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1880 {
1881         /* if there's no derived mesh or the last data mask used doesn't include
1882          * the data we need, rebuild the derived mesh
1883          */
1884         if(!em->derivedCage ||
1885            (em->lastDataMask & dataMask) != dataMask)
1886                 editbmesh_build_data(scene, obedit, em, dataMask);
1887
1888         return em->derivedCage;
1889 }
1890
1891 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
1892 {
1893         return getEditDerivedBMesh(em, obedit, NULL);
1894 }
1895
1896
1897 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
1898
1899 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
1900 {
1901         float *vec = userData;
1902         
1903         vec+= 6*index;
1904
1905         /* check if we've been here before (normal should not be 0) */
1906         if(vec[3] || vec[4] || vec[5]) return;
1907
1908         copy_v3_v3(vec, co);
1909         vec+= 3;
1910         if(no_f) {
1911                 copy_v3_v3(vec, no_f);
1912         }
1913         else {
1914                 normal_short_to_float_v3(vec, no_s);
1915         }
1916 }
1917
1918 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
1919 /* this is needed for all code using vertexgroups (no subsurf support) */
1920 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
1921 /* in use now by vertex/weight paint and particle generating */
1922
1923 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
1924 {
1925         Mesh *me= ob->data;
1926         DerivedMesh *dm;
1927         float *vertexcosnos;
1928         
1929         /* lets prevent crashing... */
1930         if(ob->type!=OB_MESH || me->totvert==0)
1931                 return NULL;
1932         
1933         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
1934         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
1935         
1936         if(dm->foreachMappedVert) {
1937                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
1938         }
1939         else {
1940                 float *fp= vertexcosnos;
1941                 int a;
1942                 
1943                 for(a=0; a< me->totvert; a++, fp+=6) {
1944                         dm->getVertCo(dm, a, fp);
1945                         dm->getVertNo(dm, a, fp+3);
1946                 }
1947         }
1948         
1949         dm->release(dm);
1950         return vertexcosnos;
1951 }
1952
1953 /* ******************* GLSL ******************** */
1954
1955 typedef struct
1956 {
1957         float * precomputedFaceNormals;
1958         MTFace * mtface;        // texture coordinates
1959         MFace * mface;          // indices
1960         MVert * mvert;          // vertices & normals
1961         float (*orco)[3];
1962         float (*tangent)[4];    // destination
1963         int numFaces;
1964
1965 } SGLSLMeshToTangent;
1966
1967 // interface
1968 #include "mikktspace.h"
1969
1970 static int GetNumFaces(const SMikkTSpaceContext * pContext)
1971 {
1972         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1973         return pMesh->numFaces;
1974 }
1975
1976 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
1977 {
1978         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1979         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
1980 }
1981
1982 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
1983 {
1984         //assert(vert_index>=0 && vert_index<4);
1985         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1986         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
1987         VECCOPY(fPos, co);
1988 }
1989
1990 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
1991 {
1992         //assert(vert_index>=0 && vert_index<4);
1993         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
1994
1995         if(pMesh->mtface!=NULL) {
1996                 float * uv = pMesh->mtface[face_num].uv[vert_index];
1997                 fUV[0]=uv[0]; fUV[1]=uv[1];
1998         }
1999         else {
2000                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2001                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2002         }
2003 }
2004
2005 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2006 {
2007         //assert(vert_index>=0 && vert_index<4);
2008         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2009
2010         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2011         if(!smoothnormal) {     // flat
2012                 if(pMesh->precomputedFaceNormals) {
2013                         VECCOPY(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2014                 }
2015                 else {
2016                         MFace *mf= &pMesh->mface[face_num];
2017                         float *p0= pMesh->mvert[mf->v1].co;
2018                         float *p1= pMesh->mvert[mf->v2].co;
2019                         float *p2= pMesh->mvert[mf->v3].co;
2020
2021                         if(mf->v4) {
2022                                 float *p3 = pMesh->mvert[mf->v4].co;
2023                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2024                         }
2025                         else {
2026                                 normal_tri_v3(fNorm, p0, p1, p2);
2027                         }
2028                 }
2029         }
2030         else {
2031                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2032                 normal_short_to_float_v3(fNorm, no);
2033         }
2034 }
2035 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2036 {
2037         //assert(vert_index>=0 && vert_index<4);
2038         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2039         float * pRes = pMesh->tangent[4*face_num+iVert];
2040         VECCOPY(pRes, fvTangent);
2041         pRes[3]=fSign;
2042 }
2043
2044
2045 void DM_add_tangent_layer(DerivedMesh *dm)
2046 {
2047         /* mesh vars */
2048         MTFace *mtface, *tf;
2049         MFace *mface, *mf;
2050         MVert *mvert, *v1, *v2, *v3, *v4;
2051         MemArena *arena= NULL;
2052         VertexTangent **vtangents= NULL;
2053         float (*orco)[3]= NULL, (*tangent)[4];
2054         float *uv1, *uv2, *uv3, *uv4, *vtang;
2055         float fno[3], tang[3], uv[4][2];
2056         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2057         float *nors;
2058
2059         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2060                 return;
2061
2062         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2063
2064         /* check we have all the needed layers */
2065         totvert= dm->getNumVerts(dm);
2066         totface= dm->getNumTessFaces(dm);
2067
2068         mvert= dm->getVertArray(dm);
2069         mface= dm->getTessFaceArray(dm);
2070         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2071
2072         if(!mtface) {
2073                 orco= dm->getVertDataArray(dm, CD_ORCO);
2074                 if(!orco)
2075                         return;
2076         }
2077         
2078         /* create tangent layer */
2079         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2080         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2081         
2082         /* allocate some space */
2083         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2084         BLI_memarena_use_calloc(arena);
2085         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2086
2087         // new computation method
2088         iCalcNewMethod = 1;
2089         if(iCalcNewMethod != 0) {
2090                 SGLSLMeshToTangent mesh2tangent= {0};
2091                 SMikkTSpaceContext sContext= {0};
2092                 SMikkTSpaceInterface sInterface= {0};
2093
2094                 mesh2tangent.precomputedFaceNormals = nors;
2095                 mesh2tangent.mtface = mtface;
2096                 mesh2tangent.mface = mface;
2097                 mesh2tangent.mvert = mvert;
2098                 mesh2tangent.orco = orco;
2099                 mesh2tangent.tangent = tangent;
2100                 mesh2tangent.numFaces = totface;
2101
2102                 sContext.m_pUserData = &mesh2tangent;
2103                 sContext.m_pInterface = &sInterface;
2104                 sInterface.m_getNumFaces = GetNumFaces;
2105                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2106                 sInterface.m_getPosition = GetPosition;
2107                 sInterface.m_getTexCoord = GetTextureCoordinate;
2108                 sInterface.m_getNormal = GetNormal;
2109                 sInterface.m_setTSpaceBasic = SetTSpace;
2110
2111                 // 0 if failed
2112                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2113         }
2114
2115         if(!iCalcNewMethod) {
2116                 /* sum tangents at connected vertices */
2117                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2118                         v1= &mvert[mf->v1];
2119                         v2= &mvert[mf->v2];
2120                         v3= &mvert[mf->v3];
2121
2122                         if (mf->v4) {
2123                                 v4= &mvert[mf->v4];
2124                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2125                         }
2126                         else {
2127                                 v4= NULL;
2128                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2129                         }
2130                 
2131                         if(mtface) {
2132                                 uv1= tf->uv[0];
2133                                 uv2= tf->uv[1];
2134                                 uv3= tf->uv[2];
2135                                 uv4= tf->uv[3];
2136                         }
2137                         else {
2138                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2139                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2140                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2141                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2142                                 if(v4)
2143                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2144                         }
2145                 
2146                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2147                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2148                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2149                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2150                 
2151                         if(mf->v4) {
2152                                 v4= &mvert[mf->v4];
2153                         
2154                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2155                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2156                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2157                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2158                         }
2159                 }
2160         
2161                 /* write tangent to layer */
2162                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2163                         len= (mf->v4)? 4 : 3; 
2164
2165                         if(mtface == NULL) {
2166                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2167                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2168                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2169                                 if(len==4)
2170                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2171                         }
2172                 
2173                         mf_vi[0]= mf->v1;
2174                         mf_vi[1]= mf->v2;
2175                         mf_vi[2]= mf->v3;
2176                         mf_vi[3]= mf->v4;
2177                 
2178                         for(j=0; j<len; j++) {
2179                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2180                                 normalize_v3_v3(tangent[j], vtang);
2181                                 ((float *) tangent[j])[3]=1.0f;
2182                         }
2183                 }
2184         }
2185         
2186         BLI_memarena_free(arena);
2187         MEM_freeN(vtangents);
2188 }
2189
2190 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2191 {
2192         CustomData *vdata, *fdata, *tfdata = NULL;
2193         int a, b, layer;
2194
2195         /* From the layers requested by the GLSL shader, figure out which ones are
2196          * actually available for this derivedmesh, and retrieve the pointers */
2197
2198         memset(attribs, 0, sizeof(DMVertexAttribs));
2199
2200         vdata = &dm->vertData;
2201         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2202         
2203         /* add a tangent layer if necessary */
2204         for(b = 0; b < gattribs->totlayer; b++)
2205                 if(gattribs->layer[b].type == CD_TANGENT)
2206                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2207                                 DM_add_tangent_layer(dm);
2208
2209         for(b = 0; b < gattribs->totlayer; b++) {
2210                 if(gattribs->layer[b].type == CD_MTFACE) {
2211                         /* uv coordinates */
2212                         if(gattribs->layer[b].name[0])
2213                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2214                                         gattribs->layer[b].name);
2215                         else
2216                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2217
2218                         if(layer != -1) {
2219                                 a = attribs->tottface++;
2220
2221                                 attribs->tface[a].array = tfdata->layers[layer].data;
2222                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2223                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2224                         } /*else {
2225                                 int player;
2226                                 CustomData *pdata = dm->getFaceDataLayout(dm);
2227                                 
2228                                 if(gattribs->layer[b].name[0])
2229                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2230                                                 gattribs->layer[b].name);
2231                                 else
2232                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2233                                 
2234                                 if (player != -1) {
2235                                         a = attribs->tottface++;
2236         
2237                                         attribs->tface[a].array = NULL;
2238                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2239                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2240                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2241                                         
2242                                 }
2243                         }*/
2244                 }
2245                 else if(gattribs->layer[b].type == CD_MCOL) {
2246                         /* vertex colors */
2247                         if(gattribs->layer[b].name[0])
2248                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2249                                         gattribs->layer[b].name);
2250                         else
2251                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2252
2253                         if(layer != -1) {
2254                                 a = attribs->totmcol++;
2255
2256                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2257                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2258                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2259                         }
2260                 }
2261                 else if(gattribs->layer[b].type == CD_TANGENT) {
2262                         /* tangents */
2263                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2264
2265                         if(layer != -1) {
2266                                 attribs->tottang = 1;
2267
2268                                 attribs->tang.array = fdata->layers[layer].data;
2269                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2270                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2271                         }
2272                 }
2273                 else if(gattribs->layer[b].type == CD_ORCO) {
2274                         /* original coordinates */
2275                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2276
2277                         if(layer != -1) {
2278                                 attribs->totorco = 1;
2279
2280                                 attribs->orco.array = vdata->layers[layer].data;
2281                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2282                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2283                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2284                         }
2285                 }
2286         }
2287 }
2288
2289 /* Set object's bounding box based on DerivedMesh min/max data */
2290 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2291 {
2292         float min[3], max[3];
2293
2294         INIT_MINMAX(min, max);
2295
2296         dm->getMinMax(dm, min, max);
2297
2298         if(!ob->bb)
2299                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2300
2301         boundbox_set_from_min_max(ob->bb, min, max);
2302 }
2303
2304 /* --- NAVMESH (begin) --- */
2305 #ifdef WITH_GAMEENGINE
2306
2307 BM_INLINE int navmesh_bit(int a, int b)
2308 {
2309         return (a & (1 << b)) >> b;
2310 }
2311
2312 BM_INLINE void navmesh_intToCol(int i, float col[3])
2313 {
2314         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2315         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2316         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2317         col[0] = 1 - r*63.0f/255.0f;
2318         col[1] = 1 - g*63.0f/255.0f;
2319         col[2] = 1 - b*63.0f/255.0f;
2320 }
2321
2322 static void navmesh_drawColored(DerivedMesh *dm)
2323 {
2324         int a, glmode;
2325         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2326         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2327         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2328         float col[3];
2329
2330         if (!polygonIdx)
2331                 return;
2332
2333         /*
2334         //UI_ThemeColor(TH_WIRE);
2335         glDisable(GL_LIGHTING);
2336         glLineWidth(2.0);
2337         dm->drawEdges(dm, 0, 1);
2338         glLineWidth(1.0);
2339         glEnable(GL_LIGHTING);*/
2340
2341         glDisable(GL_LIGHTING);
2342         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2343                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2344                 //glShadeModel(GL_SMOOTH);
2345                 glBegin(glmode = GL_QUADS);
2346                 for(a = 0; a < dm->numFaceData; a++, mface++) {
2347                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2348                         int pi = polygonIdx[a];
2349                         if (pi <= 0) {
2350                                 zero_v3(col);
2351                         }
2352                         else {
2353                                 navmesh_intToCol(pi, col);
2354                         }
2355
2356                         if(new_glmode != glmode) {
2357                                 glEnd();
2358                                 glBegin(glmode = new_glmode);
2359                         }
2360                         glColor3fv(col);
2361                         glVertex3fv(mvert[mface->v1].co);
2362                         glVertex3fv(mvert[mface->v2].co);
2363                         glVertex3fv(mvert[mface->v3].co);
2364                         if(mface->v4) {
2365                                 glVertex3fv(mvert[mface->v4].co);
2366                         }
2367                 }
2368                 glEnd();
2369         }
2370         glEnable(GL_LIGHTING);
2371 }
2372
2373 static void navmesh_DM_drawFacesTex(DerivedMesh *dm, int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr))
2374 {
2375         (void) setDrawOptions;
2376
2377         navmesh_drawColored(dm);
2378 }
2379
2380 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2381                                       float (*partial_redraw_planes)[4],
2382                                       int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2383 {
2384         (void) partial_redraw_planes;
2385         (void) setMaterial;
2386
2387         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2388         navmesh_drawColored(dm);
2389 }
2390
2391 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2392 {
2393         DerivedMesh *result;
2394         int maxFaces = dm->getNumFaces(dm);
2395         int *recastData;
2396         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2397         float* verts=NULL;
2398         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2399         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2400         int res;
2401
2402         result = CDDM_copy(dm);
2403         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2404                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2405                 if (sourceRecastData) {
2406                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2407                                                    sourceRecastData, maxFaces, "recastData");
2408                 }
2409         }
2410         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2411
2412         /* note: This is not good design! - really should not be doing this */
2413         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2414         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2415
2416
2417         /* process mesh */
2418         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2419                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2420                                              &trisToFacesMap);
2421         if (res) {
2422                 size_t polyIdx;
2423
2424                 /* invalidate concave polygon */
2425                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2426                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2427                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2428                                 /* set negative polygon idx to all faces */
2429                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2430                                 unsigned short tbase = dmesh[2];
2431                                 unsigned short tnum = dmesh[3];
2432                                 unsigned short ti;
2433
2434                                 for (ti=0; ti<tnum; ti++) {
2435                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2436                                         unsigned short faceidx = trisToFacesMap[triidx];
2437                                         if (recastData[faceidx] > 0) {
2438                                                 recastData[faceidx] = -recastData[faceidx];
2439                                         }
2440                                 }
2441                         }
2442                 }
2443         }
2444         else {
2445                 printf("Error during creation polygon infos\n");
2446         }
2447
2448         /* clean up */
2449         if (verts!=NULL)
2450                 MEM_freeN(verts);
2451         if (dtris!=NULL)
2452                 MEM_freeN(dtris);
2453         if (dmeshes!=NULL)
2454                 MEM_freeN(dmeshes);
2455         if (polys!=NULL)
2456                 MEM_freeN(polys);
2457         if (dtrisToPolysMap!=NULL)
2458                 MEM_freeN(dtrisToPolysMap);
2459         if (dtrisToTrisMap!=NULL)
2460                 MEM_freeN(dtrisToTrisMap);
2461         if (trisToFacesMap!=NULL)
2462                 MEM_freeN(trisToFacesMap);
2463
2464         return result;
2465 }
2466
2467 #endif /* WITH_GAMEENGINE */
2468
2469 /* --- NAVMESH (end) --- */