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