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