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