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