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