some speedup for drawing mesh in texture mode.
[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, int has_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 != NULL), 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 != NULL), 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, int has_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         /* int tfoffset; */ /* UNUSED */
992         int i, b, matnr, new_matnr, dodraw /* , layer */ /* UNUSED */;
993
994         dodraw = 0;
995         matnr = -1;
996
997         /* layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE); */ /* UNUSED */
998         /* tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset; */ /* UNUSED */
999
1000         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
1001         glShadeModel(GL_SMOOTH);
1002
1003         for (i=0,eve=em->verts.first; eve; eve= eve->next)
1004                 eve->tmp.l = (intptr_t) i++;
1005
1006 #define PASSATTRIB(efa, eve, vert) {                                                                                    \
1007         if(attribs.totorco) {                                                                                                           \
1008                 float *orco = attribs.orco.array[eve->tmp.l];                                                   \
1009                 glVertexAttrib3fvARB(attribs.orco.glIndex, orco);                                               \
1010         }                                                                                                                                                       \
1011         for(b = 0; b < attribs.tottface; b++) {                                                                         \
1012                 MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset);  \
1013                 glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]);                  \
1014         }                                                                                                                                                       \
1015         for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1016                 MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset);                \
1017                 GLubyte col[4];                                                                                                                 \
1018                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1019                 glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1020         }                                                                                                                                                       \
1021         if(attribs.tottang) {                                                                                                           \
1022                 float *tang = attribs.tang.array[i*4 + vert];                                                   \
1023                 glVertexAttrib4fvARB(attribs.tang.glIndex, tang);                                               \
1024         }                                                                                                                                                       \
1025 }
1026
1027         for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
1028                 int drawSmooth= (efa->flag & ME_SMOOTH);
1029
1030                 if(setDrawOptions && !setDrawOptions(userData, i))
1031                         continue;
1032
1033                 new_matnr = efa->mat_nr + 1;
1034                 if(new_matnr != matnr) {
1035                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1036                         if(dodraw)
1037                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1038                 }
1039
1040                 if(dodraw) {
1041                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
1042                         if (!drawSmooth) {
1043                                 if(vertexCos) glNormal3fv(emdm->faceNos[i]);
1044                                 else glNormal3fv(efa->n);
1045
1046                                 PASSATTRIB(efa, efa->v1, 0);
1047                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1048                                 else glVertex3fv(efa->v1->co);
1049
1050                                 PASSATTRIB(efa, efa->v2, 1);
1051                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1052                                 else glVertex3fv(efa->v2->co);
1053
1054                                 PASSATTRIB(efa, efa->v3, 2);
1055                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1056                                 else glVertex3fv(efa->v3->co);
1057
1058                                 if(efa->v4) {
1059                                         PASSATTRIB(efa, efa->v4, 3);
1060                                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1061                                         else glVertex3fv(efa->v4->co);
1062                                 }
1063                         } else {
1064                                 PASSATTRIB(efa, efa->v1, 0);
1065                                 if(vertexCos) {
1066                                         glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
1067                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1068                                 }
1069                                 else {
1070                                         glNormal3fv(efa->v1->no);
1071                                         glVertex3fv(efa->v1->co);
1072                                 }
1073
1074                                 PASSATTRIB(efa, efa->v2, 1);
1075                                 if(vertexCos) {
1076                                         glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
1077                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1078                                 }
1079                                 else {
1080                                         glNormal3fv(efa->v2->no);
1081                                         glVertex3fv(efa->v2->co);
1082                                 }
1083
1084                                 PASSATTRIB(efa, efa->v3, 2);
1085                                 if(vertexCos) {
1086                                         glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
1087                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1088                                 }
1089                                 else {
1090                                         glNormal3fv(efa->v3->no);
1091                                         glVertex3fv(efa->v3->co);
1092                                 }
1093
1094                                 if(efa->v4) {
1095                                         PASSATTRIB(efa, efa->v4, 3);
1096                                         if(vertexCos) {
1097                                                 glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
1098                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1099                                         }
1100                                         else {
1101                                                 glNormal3fv(efa->v4->no);
1102                                                 glVertex3fv(efa->v4->co);
1103                                         }
1104                                 }
1105                         }
1106                         glEnd();
1107                 }
1108         }
1109 #undef PASSATTRIB
1110 }
1111
1112 static void emDM_drawFacesGLSL(DerivedMesh *dm,
1113                            int (*setMaterial)(int, void *attribs))
1114 {
1115         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1116 }
1117
1118 static void emDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
1119 {
1120         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1121         EditVert *eve;
1122         int i;
1123
1124         if (emdm->em->verts.first) {
1125                 for (i=0,eve= emdm->em->verts.first; eve; i++,eve= eve->next) {
1126                         if (emdm->vertexCos) {
1127                                 DO_MINMAX(emdm->vertexCos[i], min_r, max_r);
1128                         } else {
1129                                 DO_MINMAX(eve->co, min_r, max_r);
1130                         }
1131                 }
1132         } else {
1133                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
1134         }
1135 }
1136 static int emDM_getNumVerts(DerivedMesh *dm)
1137 {
1138         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1139
1140         return BLI_countlist(&emdm->em->verts);
1141 }
1142
1143 static int emDM_getNumEdges(DerivedMesh *dm)
1144 {
1145         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1146
1147         return BLI_countlist(&emdm->em->edges);
1148 }
1149
1150 static int emDM_getNumFaces(DerivedMesh *dm)
1151 {
1152         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1153
1154         return BLI_countlist(&emdm->em->faces);
1155 }
1156
1157 static void emDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
1158 {
1159         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1160         EditVert *eve;
1161         int i;
1162
1163         for (i=0,eve= emdm->em->verts.first; eve; i++,eve=eve->next) {
1164                 if (emdm->vertexCos) {
1165                         copy_v3_v3(cos_r[i], emdm->vertexCos[i]);
1166                 } else {
1167                         copy_v3_v3(cos_r[i], eve->co);
1168                 }
1169         }
1170 }
1171
1172 static void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
1173 {
1174         EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
1175         int i;
1176
1177         for(i = 0; i < index; ++i) ev = ev->next;
1178
1179         VECCOPY(vert_r->co, ev->co);
1180
1181         normal_float_to_short_v3(vert_r->no, ev->no);
1182
1183         /* TODO what to do with vert_r->flag? */
1184         vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1185 }
1186
1187 static void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
1188 {
1189         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1190         EditEdge *ee = em->edges.first;
1191         EditVert *ev, *v1, *v2;
1192         int i;
1193
1194         for(i = 0; i < index; ++i) ee = ee->next;
1195
1196         edge_r->crease = (unsigned char) (ee->crease*255.0f);
1197         edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1198         /* TODO what to do with edge_r->flag? */
1199         edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1200         if (ee->seam) edge_r->flag |= ME_SEAM;
1201         if (ee->sharp) edge_r->flag |= ME_SHARP;
1202 #if 0
1203         /* this needs setup of f2 field */
1204         if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1205 #endif
1206
1207         /* goddamn, we have to search all verts to find indices */
1208         v1 = ee->v1;
1209         v2 = ee->v2;
1210         for(i = 0, ev = em->verts.first; v1 || v2; i++, ev = ev->next) {
1211                 if(ev == v1) {
1212                         edge_r->v1 = i;
1213                         v1 = NULL;
1214                 }
1215                 if(ev == v2) {
1216                         edge_r->v2 = i;
1217                         v2 = NULL;
1218                 }
1219         }
1220 }
1221
1222 static void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
1223 {
1224         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1225         EditFace *ef = em->faces.first;
1226         EditVert *ev, *v1, *v2, *v3, *v4;
1227         int i;
1228
1229         for(i = 0; i < index; ++i) ef = ef->next;
1230
1231         face_r->mat_nr = ef->mat_nr;
1232         face_r->flag = ef->flag;
1233
1234         /* goddamn, we have to search all verts to find indices */
1235         v1 = ef->v1;
1236         v2 = ef->v2;
1237         v3 = ef->v3;
1238         v4 = ef->v4;
1239         if(!v4) face_r->v4 = 0;
1240
1241         for(i = 0, ev = em->verts.first; v1 || v2 || v3 || v4;
1242                 i++, ev = ev->next) {
1243                 if(ev == v1) {
1244                         face_r->v1 = i;
1245                         v1 = NULL;
1246                 }
1247                 if(ev == v2) {
1248                         face_r->v2 = i;
1249                         v2 = NULL;
1250                 }
1251                 if(ev == v3) {
1252                         face_r->v3 = i;
1253                         v3 = NULL;
1254                 }
1255                 if(ev == v4) {
1256                         face_r->v4 = i;
1257                         v4 = NULL;
1258                 }
1259         }
1260
1261         test_index_face(face_r, NULL, 0, ef->v4?4:3);
1262 }
1263
1264 static void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
1265 {
1266         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1267         EditVert *ev = emdm->em->verts.first;
1268         int i;
1269
1270         for(i=0; ev; ev = ev->next, ++vert_r, ++i) {
1271                 if(emdm->vertexCos)
1272                         copy_v3_v3(vert_r->co, emdm->vertexCos[i]);
1273                 else
1274                         copy_v3_v3(vert_r->co, ev->co);
1275
1276                 normal_float_to_short_v3(vert_r->no, ev->no);
1277
1278                 /* TODO what to do with vert_r->flag? */
1279                 vert_r->flag = 0;
1280                 vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1281         }
1282 }
1283
1284 static void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
1285 {
1286         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1287         EditEdge *ee = em->edges.first;
1288         EditVert *ev;
1289         int i;
1290
1291         /* store vertex indices in tmp union */
1292         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1293                 ev->tmp.l = (intptr_t) i;
1294
1295         for( ; ee; ee = ee->next, ++edge_r) {
1296                 edge_r->crease = (unsigned char) (ee->crease*255.0f);
1297                 edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1298                 /* TODO what to do with edge_r->flag? */
1299                 edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1300                 if (ee->seam) edge_r->flag |= ME_SEAM;
1301                 if (ee->sharp) edge_r->flag |= ME_SHARP;
1302 #if 0
1303                 /* this needs setup of f2 field */
1304                 if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1305 #endif
1306
1307                 edge_r->v1 = (int)ee->v1->tmp.l;
1308                 edge_r->v2 = (int)ee->v2->tmp.l;
1309         }
1310 }
1311
1312 static void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
1313 {
1314         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1315         EditFace *ef = em->faces.first;
1316         EditVert *ev;
1317         int i;
1318
1319         /* store vertexes indices in tmp union */
1320         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1321                 ev->tmp.l = (intptr_t) i;
1322
1323         for( ; ef; ef = ef->next, ++face_r) {
1324                 face_r->mat_nr = ef->mat_nr;
1325                 face_r->flag = ef->flag;
1326
1327                 face_r->v1 = (int)ef->v1->tmp.l;
1328                 face_r->v2 = (int)ef->v2->tmp.l;
1329                 face_r->v3 = (int)ef->v3->tmp.l;
1330                 if(ef->v4) face_r->v4 = (int)ef->v4->tmp.l;
1331                 else face_r->v4 = 0;
1332
1333                 test_index_face(face_r, NULL, 0, ef->v4?4:3);
1334         }
1335 }
1336
1337 static void *emDM_getFaceDataArray(DerivedMesh *dm, int type)
1338 {
1339         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1340         EditMesh *em= emdm->em;
1341         EditFace *efa;
1342         char *data, *emdata;
1343         void *datalayer;
1344         int index, size;
1345
1346         datalayer = DM_get_face_data_layer(dm, type);
1347         if(datalayer)
1348                 return datalayer;
1349
1350         /* layers are store per face for editmesh, we convert to a temporary
1351          * data layer array in the derivedmesh when these are requested */
1352         if(type == CD_MTFACE || type == CD_MCOL) {
1353                 index = CustomData_get_layer_index(&em->fdata, type);
1354
1355                 if(index != -1) {
1356                         /* int offset = em->fdata.layers[index].offset; */ /* UNUSED */
1357                         size = CustomData_sizeof(type);
1358
1359                         DM_add_face_layer(dm, type, CD_CALLOC, NULL);
1360                         index = CustomData_get_layer_index(&dm->faceData, type);
1361                         dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
1362
1363                         data = datalayer = DM_get_face_data_layer(dm, type);
1364                         for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
1365                                 emdata = CustomData_em_get(&em->fdata, efa->data, type);
1366                                 memcpy(data, emdata, size);
1367                         }
1368                 }
1369         }
1370
1371         return datalayer;
1372 }
1373
1374 static void emDM_release(DerivedMesh *dm)
1375 {
1376         EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
1377
1378         if (DM_release(dm)) {
1379                 if (emdm->vertexCos) {
1380                         MEM_freeN(emdm->vertexCos);
1381                         MEM_freeN(emdm->vertexNos);
1382                         MEM_freeN(emdm->faceNos);
1383                 }
1384
1385                 MEM_freeN(emdm);
1386         }
1387 }
1388
1389 DerivedMesh *editmesh_get_derived(EditMesh *em, float (*vertexCos)[3])
1390 {
1391         EditMeshDerivedMesh *emdm = MEM_callocN(sizeof(*emdm), "emdm");
1392
1393         DM_init(&emdm->dm, DM_TYPE_EDITMESH, BLI_countlist(&em->verts),
1394                                          BLI_countlist(&em->edges), BLI_countlist(&em->faces));
1395
1396         emdm->dm.getMinMax = emDM_getMinMax;
1397
1398         emdm->dm.getNumVerts = emDM_getNumVerts;
1399         emdm->dm.getNumEdges = emDM_getNumEdges;
1400         emdm->dm.getNumFaces = emDM_getNumFaces;
1401
1402         emdm->dm.getVertCos = emDM_getVertCos;
1403
1404         emdm->dm.getVert = emDM_getVert;
1405         emdm->dm.getEdge = emDM_getEdge;
1406         emdm->dm.getFace = emDM_getFace;
1407         emdm->dm.copyVertArray = emDM_copyVertArray;
1408         emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
1409         emdm->dm.copyFaceArray = emDM_copyFaceArray;
1410         emdm->dm.getFaceDataArray = emDM_getFaceDataArray;
1411
1412         emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
1413         emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
1414         emdm->dm.foreachMappedFaceCenter = emDM_foreachMappedFaceCenter;
1415
1416         emdm->dm.drawEdges = emDM_drawEdges;
1417         emdm->dm.drawMappedEdges = emDM_drawMappedEdges;
1418         emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
1419         emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
1420         emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
1421         emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
1422         emdm->dm.drawFacesTex = emDM_drawFacesTex;
1423         emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
1424         emdm->dm.drawUVEdges = emDM_drawUVEdges;
1425
1426         emdm->dm.release = emDM_release;
1427         
1428         emdm->em = em;
1429         emdm->vertexCos = vertexCos;
1430
1431         if(CustomData_has_layer(&em->vdata, CD_MDEFORMVERT)) {
1432                 EditVert *eve;
1433                 int i;
1434
1435                 DM_add_vert_layer(&emdm->dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
1436
1437                 for(eve = em->verts.first, i = 0; eve; eve = eve->next, ++i)
1438                         DM_set_vert_data(&emdm->dm, i, CD_MDEFORMVERT,
1439                                                          CustomData_em_get(&em->vdata, eve->data, CD_MDEFORMVERT));
1440         }
1441
1442         if(vertexCos) {
1443                 EditVert *eve;
1444                 EditFace *efa;
1445                 int totface = BLI_countlist(&em->faces);
1446                 int i;
1447
1448                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
1449                         eve->tmp.l = (intptr_t) i++;
1450
1451                 emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
1452                 emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
1453
1454                 for(i=0, efa= em->faces.first; efa; i++, efa=efa->next) {
1455                         float *v1 = vertexCos[(int) efa->v1->tmp.l];
1456                         float *v2 = vertexCos[(int) efa->v2->tmp.l];
1457                         float *v3 = vertexCos[(int) efa->v3->tmp.l];
1458                         float *no = emdm->faceNos[i];
1459                         
1460                         if(efa->v4) {
1461                                 float *v4 = vertexCos[(int) efa->v4->tmp.l];
1462
1463                                 normal_quad_v3( no,v1, v2, v3, v4);
1464                                 add_v3_v3(emdm->vertexNos[(int) efa->v4->tmp.l], no);
1465                         }
1466                         else {
1467                                 normal_tri_v3( no,v1, v2, v3);
1468                         }
1469
1470                         add_v3_v3(emdm->vertexNos[(int) efa->v1->tmp.l], no);
1471                         add_v3_v3(emdm->vertexNos[(int) efa->v2->tmp.l], no);
1472                         add_v3_v3(emdm->vertexNos[(int) efa->v3->tmp.l], no);
1473                 }
1474
1475                 for(i=0, eve= em->verts.first; eve; i++, eve=eve->next) {
1476                         float *no = emdm->vertexNos[i];
1477                         /* following Mesh convention; we use vertex coordinate itself
1478                          * for normal in this case */
1479                         if (normalize_v3(no) == 0.0f) {
1480                                 normalize_v3_v3(no, vertexCos[i]);
1481                         }
1482                 }
1483         }
1484
1485         return (DerivedMesh*) emdm;
1486 }
1487
1488 /***/
1489
1490 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
1491 {
1492         Mesh *me = ob->data;
1493         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1494         DerivedMesh *dm;
1495
1496         md->scene= scene;
1497         
1498         if (!(md->mode&eModifierMode_Realtime)) return NULL;
1499         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
1500
1501         if (mti->type==eModifierTypeType_OnlyDeform) {
1502                 int numVerts;
1503                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
1504
1505                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
1506                 dm = mesh_create_derived(me, ob, deformedVerts);
1507
1508                 MEM_freeN(deformedVerts);
1509         } else {
1510                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
1511                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
1512
1513                 if(tdm != dm) tdm->release(tdm);
1514         }
1515
1516         return dm;
1517 }
1518
1519 static float *get_editmesh_orco_verts(EditMesh *em)
1520 {
1521         EditVert *eve;
1522         float *orco;
1523         int a, totvert;
1524
1525         /* these may not really be the orco's, but it's only for preview.
1526          * could be solver better once, but isn't simple */
1527
1528         totvert= 0;
1529         for(eve=em->verts.first; eve; eve=eve->next)
1530                 totvert++;
1531         
1532         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
1533
1534         for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3)
1535                 VECCOPY(orco+a, eve->co);
1536         
1537         return orco;
1538 }
1539
1540 /* orco custom data layer */
1541
1542 static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
1543 {
1544         *free= 0;
1545
1546         if(layer == CD_ORCO) {
1547                 /* get original coordinates */
1548                 *free= 1;
1549
1550                 if(em)
1551                         return (float(*)[3])get_editmesh_orco_verts(em);
1552                 else
1553                         return (float(*)[3])get_mesh_orco_verts(ob);
1554         }
1555         else if(layer == CD_CLOTH_ORCO) {
1556                 /* apply shape key for cloth, this should really be solved
1557                    by a more flexible customdata system, but not simple */
1558                 if(!em) {
1559                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
1560                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
1561
1562                         if(kb->data)
1563                                 return kb->data;
1564                 }
1565
1566                 return NULL;
1567         }
1568
1569         return NULL;
1570 }
1571
1572 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em, int layer)
1573 {
1574         DerivedMesh *dm;
1575         float (*orco)[3];
1576         int free;
1577
1578         if(em) dm= CDDM_from_editmesh(em, me);
1579         else dm= CDDM_from_mesh(me, ob);
1580
1581         orco= get_orco_coords_dm(ob, em, layer, &free);
1582
1583         if(orco) {
1584                 CDDM_apply_vert_coords(dm, orco);
1585                 if(free) MEM_freeN(orco);
1586         }
1587
1588         CDDM_calc_normals(dm);
1589
1590         return dm;
1591 }
1592
1593 static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm, int layer)
1594 {
1595         float (*orco)[3], (*layerorco)[3];
1596         int totvert, free;
1597
1598         totvert= dm->getNumVerts(dm);
1599
1600         if(orcodm) {
1601                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
1602                 free= 1;
1603
1604                 if(orcodm->getNumVerts(orcodm) == totvert)
1605                         orcodm->getVertCos(orcodm, orco);
1606                 else
1607                         dm->getVertCos(dm, orco);
1608         }
1609         else
1610                 orco= get_orco_coords_dm(ob, em, layer, &free);
1611
1612         if(orco) {
1613                 if(layer == CD_ORCO)
1614                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
1615
1616                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1617                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1618                         layerorco = DM_get_vert_data_layer(dm, layer);
1619                 }
1620
1621                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
1622                 if(free) MEM_freeN(orco);
1623         }
1624 }
1625
1626 /* weight paint colors */
1627
1628 /* Something of a hack, at the moment deal with weightpaint
1629  * by tucking into colors during modifier eval, only in
1630  * wpaint mode. Works ok but need to make sure recalc
1631  * happens on enter/exit wpaint.
1632  */
1633
1634 void weight_to_rgb(float input, float *fr, float *fg, float *fb)
1635 {
1636         float blend;
1637         
1638         blend= ((input/2.0f)+0.5f);
1639         
1640         if (input<=0.25f){      // blue->cyan
1641                 *fr= 0.0f;
1642                 *fg= blend*input*4.0f;
1643                 *fb= blend;
1644         }
1645         else if (input<=0.50f){ // cyan->green
1646                 *fr= 0.0f;
1647                 *fg= blend;
1648                 *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
1649         }
1650         else if (input <= 0.75f){       // green->yellow
1651                 *fr= blend * ((input-0.50f)*4.0f);
1652                 *fg= blend;
1653                 *fb= 0.0f;
1654         }
1655         else if (input <= 1.0f){ // yellow->red
1656                 *fr= blend;
1657                 *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
1658                 *fb= 0.0f;
1659         }
1660 }
1661
1662 /* draw_flag's for calc_weightpaint_vert_color */
1663 enum {
1664         CALC_WP_MULTIPAINT= (1<<0),
1665         CALC_WP_AUTO_NORMALIZE= (1<<1),
1666 };
1667
1668 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)
1669 {
1670         Mesh *me = ob->data;
1671         float colf[4], input = 0.0f;
1672         int i;
1673
1674         
1675         int make_black= FALSE;
1676
1677         if (me->dvert) {
1678                 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1679                         
1680                         int was_a_nonzero= FALSE;
1681                         for (i=0; i<me->dvert[vert].totweight; i++) {
1682                                 /* in multipaint, get the average if auto normalize is inactive
1683                                  * get the sum if it is active */
1684                                 if(dg_flags[me->dvert[vert].dw[i].def_nr]) {
1685                                         if(me->dvert[vert].dw[i].weight) {
1686                                                 input+= me->dvert[vert].dw[i].weight;
1687                                                 was_a_nonzero= TRUE;
1688                                         }
1689                                 }
1690                         }
1691
1692                         /* make it black if the selected groups have no weight on a vertex */
1693                         if(was_a_nonzero == FALSE) {
1694                                 make_black = TRUE;
1695                         }
1696                         else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1697                                 input /= selected; /* get the average */
1698                         }
1699                 }
1700                 else {
1701                         /* default, non tricky behavior */
1702                         for (i=0; i<me->dvert[vert].totweight; i++) {
1703                                 if (me->dvert[vert].dw[i].def_nr==ob->actdef-1) {
1704                                         input+=me->dvert[vert].dw[i].weight;
1705                                 }
1706                         }
1707                 }
1708         }
1709         
1710         if (make_black) {
1711                 col[3] = 0;
1712                 col[2] = 0;
1713                 col[1] = 0;
1714                 col[0] = 255;
1715                 return;
1716         }
1717
1718         CLAMP(input, 0.0f, 1.0f);       
1719
1720         if(coba)
1721                 do_colorband(coba, input, colf);
1722         else
1723                 weight_to_rgb(input, colf, colf+1, colf+2);
1724         
1725         col[3] = (unsigned char)(colf[0] * 255.0f);
1726         col[2] = (unsigned char)(colf[1] * 255.0f);
1727         col[1] = (unsigned char)(colf[2] * 255.0f);
1728         col[0] = 255;
1729 }
1730
1731 static ColorBand *stored_cb= NULL;
1732
1733 void vDM_ColorBand_store(ColorBand *coba)
1734 {
1735         stored_cb= coba;
1736 }
1737
1738 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
1739 {
1740         Mesh *me = ob->data;
1741         MFace *mf = me->mface;
1742         ColorBand *coba= stored_cb;     /* warning, not a local var */
1743         unsigned char *wtcol;
1744         int i;
1745         
1746         int defbase_len = BLI_countlist(&ob->defbase);
1747         char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
1748         int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
1749         int unselected = defbase_len - selected;
1750
1751         wtcol = MEM_callocN (sizeof (unsigned char) * me->totface*4*4, "weightmap");
1752         
1753         memset(wtcol, 0x55, sizeof (unsigned char) * me->totface*4*4);
1754         for (i=0; i<me->totface; i++, mf++) {
1755                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
1756                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
1757                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
1758                 if (mf->v4)
1759                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
1760         }
1761         
1762         MEM_freeN(defbase_sel);
1763
1764         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, dm->numFaceData);
1765 }
1766
1767 /* new value for useDeform -1  (hack for the gameengine):
1768  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1769  * - don't apply the key
1770  * - apply deform modifiers and input vertexco
1771  */
1772 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1773                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1774                                                                 int useRenderParams, int useDeform,
1775                                                                 int needMapping, CustomDataMask dataMask, int index, int useCache)
1776 {
1777         Mesh *me = ob->data;
1778         ModifierData *firstmd, *md;
1779         LinkNode *datamasks, *curr;
1780         CustomDataMask mask, nextmask;
1781         float (*deformedVerts)[3] = NULL;
1782         DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
1783         int numVerts = me->totvert;
1784         int required_mode;
1785         int isPrevDeform= FALSE;
1786         int skipVirtualArmature = (useDeform < 0);
1787         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1788         int has_multires = mmd != NULL, multires_applied = 0;
1789         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1790
1791         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1792                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1793
1794         if(mmd && !mmd->sculptlvl)
1795                 has_multires = 0;
1796
1797         if(!skipVirtualArmature) {
1798                 firstmd = modifiers_getVirtualModifierList(ob);
1799         }
1800         else {
1801                 /* game engine exception */
1802                 firstmd = ob->modifiers.first;
1803                 if(firstmd && firstmd->type == eModifierType_Armature)
1804                         firstmd = firstmd->next;
1805         }
1806
1807         md = firstmd;
1808
1809         modifiers_clearErrors(ob);
1810
1811         if(useRenderParams) required_mode = eModifierMode_Render;
1812         else required_mode = eModifierMode_Realtime;
1813
1814         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1815         curr = datamasks;
1816
1817         if(deform_r) *deform_r = NULL;
1818         *final_r = NULL;
1819
1820         if(useDeform) {
1821                 if(inputVertexCos)
1822                         deformedVerts = inputVertexCos;
1823                 
1824                 /* Apply all leading deforming modifiers */
1825                 for(;md; md = md->next, curr = curr->next) {
1826                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1827
1828                         md->scene= scene;
1829                         
1830                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1831                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1832
1833                         if(mti->type == eModifierTypeType_OnlyDeform) {
1834                                 if(!deformedVerts)
1835                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1836
1837                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1838                         } else {
1839                                 break;
1840                         }
1841                         
1842                         /* grab modifiers until index i */
1843                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1844                                 break;
1845                 }
1846
1847                 /* Result of all leading deforming modifiers is cached for
1848                  * places that wish to use the original mesh but with deformed
1849                  * coordinates (vpaint, etc.)
1850                  */
1851                 if (deform_r) {
1852                         *deform_r = CDDM_from_mesh(me, ob);
1853
1854                         if(deformedVerts) {
1855                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1856                                 CDDM_calc_normals(*deform_r);
1857                         }
1858                 }
1859         } else {
1860                 /* default behaviour for meshes */
1861                 if(inputVertexCos)
1862                         deformedVerts = inputVertexCos;
1863                 else
1864                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1865         }
1866
1867
1868         /* Now apply all remaining modifiers. If useDeform is off then skip
1869          * OnlyDeform ones. 
1870          */
1871         dm = NULL;
1872         orcodm = NULL;
1873         clothorcodm = NULL;
1874
1875         for(;md; md = md->next, curr = curr->next) {
1876                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1877
1878                 md->scene= scene;
1879
1880                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1881                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1882                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1883                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1884                         continue;
1885                 }
1886                 if(sculpt_mode && (!has_multires || multires_applied)) {
1887                         int unsupported= 0;
1888
1889                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1890                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1891
1892                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1893                         unsupported|= multires_applied;
1894
1895                         if(unsupported) {
1896                                 modifier_setError(md, "Not supported in sculpt mode.");
1897                                 continue;
1898                         }
1899                 }
1900                 if(needMapping && !modifier_supportsMapping(md)) continue;
1901                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1902
1903                 /* add an orco layer if needed by this modifier */
1904                 if(mti->requiredDataMask)
1905                         mask = mti->requiredDataMask(ob, md);
1906                 else
1907                         mask = 0;
1908
1909                 if(dm && (mask & CD_MASK_ORCO))
1910                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1911
1912                 /* How to apply modifier depends on (a) what we already have as
1913                  * a result of previous modifiers (could be a DerivedMesh or just
1914                  * deformed vertices) and (b) what type the modifier is.
1915                  */
1916
1917                 if(mti->type == eModifierTypeType_OnlyDeform) {
1918                         /* No existing verts to deform, need to build them. */
1919                         if(!deformedVerts) {
1920                                 if(dm) {
1921                                         /* Deforming a derived mesh, read the vertex locations
1922                                          * out of the mesh and deform them. Once done with this
1923                                          * run of deformers verts will be written back.
1924                                          */
1925                                         numVerts = dm->getNumVerts(dm);
1926                                         deformedVerts =
1927                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1928                                         dm->getVertCos(dm, deformedVerts);
1929                                 } else {
1930                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1931                                 }
1932                         }
1933
1934                         /* if this is not the last modifier in the stack then recalculate the normals
1935                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1936                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1937                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1938                                 if(dm && dm->type == DM_TYPE_CDDM) {
1939                                         CDDM_apply_vert_coords(dm, deformedVerts);
1940                                         CDDM_calc_normals(dm);
1941                                 }
1942                         }
1943
1944                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1945                 } else {
1946                         DerivedMesh *ndm;
1947
1948                         /* determine which data layers are needed by following modifiers */
1949                         if(curr->next)
1950                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1951                         else
1952                                 nextmask= dataMask;
1953
1954                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1955                         if(dm) {
1956                                 if(deformedVerts) {
1957                                         DerivedMesh *tdm = CDDM_copy(dm);
1958                                         dm->release(dm);
1959                                         dm = tdm;
1960
1961                                         CDDM_apply_vert_coords(dm, deformedVerts);
1962                                         CDDM_calc_normals(dm);
1963                                 }
1964                         } else {
1965                                 dm = CDDM_from_mesh(me, ob);
1966
1967                                 if(deformedVerts) {
1968                                         CDDM_apply_vert_coords(dm, deformedVerts);
1969                                         CDDM_calc_normals(dm);
1970                                 }
1971
1972                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1973                                         add_weight_mcol_dm(ob, dm, draw_flag); 
1974
1975                                 /* Constructive modifiers need to have an origindex
1976                                  * otherwise they wont have anywhere to copy the data from.
1977                                  *
1978                                  * Also create ORIGINDEX data if any of the following modifiers
1979                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1980                                  * data by using generic DM_copy_vert_data() functions.
1981                                  */
1982                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1983                                         /* calc */
1984                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1985                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1986                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1987
1988                                         range_vni(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1989                                         range_vni(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1990                                         range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
1991                                 }
1992                         }
1993
1994                         
1995                         /* set the DerivedMesh to only copy needed data */
1996                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1997                         /* needMapping check here fixes bug [#28112], otherwise its
1998                          * possible that it wont be copied */
1999                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
2000                         
2001                         /* add cloth rest shape key if need */
2002                         if(mask & CD_MASK_CLOTH_ORCO)
2003                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
2004
2005                         /* add an origspace layer if needed */
2006                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
2007                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2008                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2009
2010                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
2011
2012                         if(ndm) {
2013                                 /* if the modifier returned a new dm, release the old one */
2014                                 if(dm && dm != ndm) dm->release(dm);
2015
2016                                 dm = ndm;
2017
2018                                 if(deformedVerts) {
2019                                         if(deformedVerts != inputVertexCos)
2020                                                 MEM_freeN(deformedVerts);
2021
2022                                         deformedVerts = NULL;
2023                                 }
2024                         } 
2025
2026                         /* create an orco derivedmesh in parallel */
2027                         if(nextmask & CD_MASK_ORCO) {
2028                                 if(!orcodm)
2029                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
2030
2031                                 nextmask &= ~CD_MASK_ORCO;
2032                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
2033                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
2034
2035                                 if(ndm) {
2036                                         /* if the modifier returned a new dm, release the old one */
2037                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2038                                         orcodm = ndm;
2039                                 }
2040                         }
2041
2042                         /* create cloth orco derivedmesh in parallel */
2043                         if(nextmask & CD_MASK_CLOTH_ORCO) {
2044                                 if(!clothorcodm)
2045                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
2046
2047                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
2048                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
2049                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
2050
2051                                 if(ndm) {
2052                                         /* if the modifier returned a new dm, release the old one */
2053                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
2054                                         clothorcodm = ndm;
2055                                 }
2056                         }
2057                 }
2058
2059                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
2060
2061                 /* grab modifiers until index i */
2062                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
2063                         break;
2064
2065                 if(sculpt_mode && md->type == eModifierType_Multires)
2066                         multires_applied = 1;
2067         }
2068
2069         for(md=firstmd; md; md=md->next)
2070                 modifier_freeTemporaryData(md);
2071
2072         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
2073          * need to apply these back onto the DerivedMesh. If we have no
2074          * DerivedMesh then we need to build one.
2075          */
2076         if(dm && deformedVerts) {
2077                 finaldm = CDDM_copy(dm);
2078
2079                 dm->release(dm);
2080
2081                 CDDM_apply_vert_coords(finaldm, deformedVerts);
2082                 CDDM_calc_normals(finaldm);
2083
2084                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2085                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2086         } else if(dm) {
2087                 finaldm = dm;
2088         } else {
2089                 finaldm = CDDM_from_mesh(me, ob);
2090
2091                 if(deformedVerts) {
2092                         CDDM_apply_vert_coords(finaldm, deformedVerts);
2093                         CDDM_calc_normals(finaldm);
2094                 }
2095
2096                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
2097                         add_weight_mcol_dm(ob, finaldm, draw_flag);
2098         }
2099
2100         /* add an orco layer if needed */
2101         if(dataMask & CD_MASK_ORCO) {
2102                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
2103
2104                 if(deform_r && *deform_r)
2105                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
2106         }
2107
2108         *final_r = finaldm;
2109
2110         if(orcodm)
2111                 orcodm->release(orcodm);
2112         if(clothorcodm)
2113                 clothorcodm->release(clothorcodm);
2114
2115         if(deformedVerts && deformedVerts != inputVertexCos)
2116                 MEM_freeN(deformedVerts);
2117
2118         BLI_linklist_free(datamasks, NULL);
2119 }
2120
2121 float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
2122 {
2123         int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
2124         float (*cos)[3];
2125         EditVert *eve;
2126
2127         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
2128         for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
2129                 VECCOPY(cos[i], eve->co);
2130         }
2131
2132         return cos;
2133 }
2134
2135 int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2136 {
2137         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2138         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2139
2140         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
2141         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2142                 modifier_setError(md, "Modifier requires original data, bad stack position.");
2143                 return 0;
2144         }
2145         
2146         return 1;
2147 }
2148
2149 static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
2150                                                                         DerivedMesh **final_r,
2151                                                                         CustomDataMask dataMask)
2152 {
2153         ModifierData *md;
2154         float (*deformedVerts)[3] = NULL;
2155         CustomDataMask mask;
2156         DerivedMesh *dm, *orcodm = NULL;
2157         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2158         LinkNode *datamasks, *curr;
2159         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2160
2161         modifiers_clearErrors(ob);
2162
2163         if(cage_r && cageIndex == -1) {
2164                 *cage_r = editmesh_get_derived(em, NULL);
2165         }
2166
2167         dm = NULL;
2168         md = modifiers_getVirtualModifierList(ob);
2169
2170         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
2171
2172         curr = datamasks;
2173         for(i = 0; md; i++, md = md->next, curr = curr->next) {
2174                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2175
2176                 md->scene= scene;
2177                 
2178                 if(!editmesh_modifier_is_enabled(scene, md, dm))
2179                         continue;
2180
2181                 /* add an orco layer if needed by this modifier */
2182                 if(dm && mti->requiredDataMask) {
2183                         mask = mti->requiredDataMask(ob, md);
2184                         if(mask & CD_MASK_ORCO)
2185                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2186                 }
2187
2188                 /* How to apply modifier depends on (a) what we already have as
2189                  * a result of previous modifiers (could be a DerivedMesh or just
2190                  * deformed vertices) and (b) what type the modifier is.
2191                  */
2192
2193                 if(mti->type == eModifierTypeType_OnlyDeform) {
2194                         /* No existing verts to deform, need to build them. */
2195                         if(!deformedVerts) {
2196                                 if(dm) {
2197                                         /* Deforming a derived mesh, read the vertex locations
2198                                          * out of the mesh and deform them. Once done with this
2199                                          * run of deformers verts will be written back.
2200                                          */
2201                                         numVerts = dm->getNumVerts(dm);
2202                                         deformedVerts =
2203                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2204                                         dm->getVertCos(dm, deformedVerts);
2205                                 } else {
2206                                         deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
2207                                 }
2208                         }
2209
2210                         if (mti->deformVertsEM)
2211                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2212                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
2213                 } else {
2214                         DerivedMesh *ndm;
2215
2216                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2217                         if(dm) {
2218                                 if(deformedVerts) {
2219                                         DerivedMesh *tdm = CDDM_copy(dm);
2220                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
2221                                         dm = tdm;
2222
2223                                         CDDM_apply_vert_coords(dm, deformedVerts);
2224                                         CDDM_calc_normals(dm);
2225                                 } else if(cage_r && dm == *cage_r) {
2226                                         /* dm may be changed by this modifier, so we need to copy it
2227                                          */
2228                                         dm = CDDM_copy(dm);
2229                                 }
2230
2231                         } else {
2232                                 dm = CDDM_from_editmesh(em, ob->data);
2233
2234                                 if(deformedVerts) {
2235                                         CDDM_apply_vert_coords(dm, deformedVerts);
2236                                         CDDM_calc_normals(dm);
2237                                 }
2238                         }
2239
2240                         /* create an orco derivedmesh in parallel */
2241                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2242                         if(mask & CD_MASK_ORCO) {
2243                                 if(!orcodm)
2244                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
2245
2246                                 mask &= ~CD_MASK_ORCO;
2247                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2248
2249                                 if (mti->applyModifierEM)
2250                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
2251                                 else
2252                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
2253
2254                                 if(ndm) {
2255                                         /* if the modifier returned a new dm, release the old one */
2256                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2257                                         orcodm = ndm;
2258                                 }
2259                         }
2260
2261                         /* set the DerivedMesh to only copy needed data */
2262                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
2263
2264                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2265
2266                         if(mask & CD_MASK_ORIGSPACE)
2267                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2268                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2269                         
2270                         if (mti->applyModifierEM)
2271                                 ndm = mti->applyModifierEM(md, ob, em, dm);
2272                         else
2273                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
2274
2275                         if (ndm) {
2276                                 if(dm && dm != ndm)
2277                                         dm->release(dm);
2278
2279                                 dm = ndm;
2280
2281                                 if (deformedVerts) {
2282                                         MEM_freeN(deformedVerts);
2283                                         deformedVerts = NULL;
2284                                 }
2285                         }
2286                 }
2287
2288                 if(cage_r && i == cageIndex) {
2289                         if(dm && deformedVerts) {
2290                                 *cage_r = CDDM_copy(dm);
2291                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2292                         } else if(dm) {
2293                                 *cage_r = dm;
2294                         } else {
2295                                 *cage_r =
2296                                         editmesh_get_derived(em,
2297                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2298                         }
2299                 }
2300         }
2301
2302         BLI_linklist_free(datamasks, NULL);
2303
2304         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2305          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2306          * then we need to build one.
2307          */
2308         if(dm && deformedVerts) {
2309                 *final_r = CDDM_copy(dm);
2310
2311                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
2312
2313                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2314                 CDDM_calc_normals(*final_r);
2315         } else if (dm) {
2316                 *final_r = dm;
2317         } else if (!deformedVerts && cage_r && *cage_r) {
2318                 *final_r = *cage_r;
2319         } else {
2320                 *final_r = editmesh_get_derived(em, deformedVerts);
2321                 deformedVerts = NULL;
2322         }
2323
2324         /* add an orco layer if needed */
2325         if(dataMask & CD_MASK_ORCO)
2326                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2327
2328         if(orcodm)
2329                 orcodm->release(orcodm);
2330
2331         if(deformedVerts)
2332                 MEM_freeN(deformedVerts);
2333 }
2334
2335 static void clear_mesh_caches(Object *ob)
2336 {
2337         Mesh *me= ob->data;
2338
2339                 /* also serves as signal to remake texspace */
2340         if (ob->bb) {
2341                 MEM_freeN(ob->bb);
2342                 ob->bb = NULL;
2343         }
2344         if (me->bb) {
2345                 MEM_freeN(me->bb);
2346                 me->bb = NULL;
2347         }
2348
2349         freedisplist(&ob->disp);
2350
2351         if (ob->derivedFinal) {
2352                 ob->derivedFinal->needsFree = 1;
2353                 ob->derivedFinal->release(ob->derivedFinal);
2354                 ob->derivedFinal= NULL;
2355         }
2356         if (ob->derivedDeform) {
2357                 ob->derivedDeform->needsFree = 1;
2358                 ob->derivedDeform->release(ob->derivedDeform);
2359                 ob->derivedDeform= NULL;
2360         }
2361
2362         if(ob->sculpt) {
2363                 object_sculpt_modifiers_changed(ob);
2364         }
2365 }
2366
2367 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
2368 {
2369         Object *obact = scene->basact?scene->basact->object:NULL;
2370         int editing = paint_facesel_test(ob) || paint_vertsel_test(ob);/* paint_vertsel_test */
2371         /* weight paint and face select need original indices because of selection buffer drawing */
2372         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
2373
2374         clear_mesh_caches(ob);
2375
2376         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2377                                                 &ob->derivedFinal, 0, 1,
2378                                                 needMapping, dataMask, -1, 1);
2379
2380         DM_set_object_boundbox (ob, ob->derivedFinal);
2381
2382         ob->derivedFinal->needsFree = 0;
2383         ob->derivedDeform->needsFree = 0;
2384         ob->lastDataMask = dataMask;
2385 }
2386
2387 static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2388 {
2389         clear_mesh_caches(obedit);
2390
2391         if (em->derivedFinal) {
2392                 if (em->derivedFinal!=em->derivedCage) {
2393                         em->derivedFinal->needsFree = 1;
2394                         em->derivedFinal->release(em->derivedFinal);
2395                 }
2396                 em->derivedFinal = NULL;
2397         }
2398         if (em->derivedCage) {
2399                 em->derivedCage->needsFree = 1;
2400                 em->derivedCage->release(em->derivedCage);
2401                 em->derivedCage = NULL;
2402         }
2403
2404         editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2405         DM_set_object_boundbox (obedit, em->derivedFinal);
2406
2407         em->lastDataMask = dataMask;
2408         em->derivedFinal->needsFree = 0;
2409         em->derivedCage->needsFree = 0;
2410 }
2411
2412 void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
2413 {
2414         if (em) {
2415                 editmesh_build_data(scene, ob, em, dataMask);
2416         } else {
2417                 mesh_build_data(scene, ob, dataMask);
2418         }
2419 }
2420
2421 /***/
2422
2423 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2424 {
2425         /* if there's no derived mesh or the last data mask used doesn't include
2426          * the data we need, rebuild the derived mesh
2427          */
2428         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2429                 mesh_build_data(scene, ob, dataMask);
2430
2431         return ob->derivedFinal;
2432 }
2433
2434 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2435 {
2436         /* if there's no derived mesh or the last data mask used doesn't include
2437          * the data we need, rebuild the derived mesh
2438          */
2439         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2440                 mesh_build_data(scene, ob, dataMask);
2441
2442         return ob->derivedDeform;
2443 }
2444
2445 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2446 {
2447         DerivedMesh *final;
2448         
2449         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
2450
2451         return final;
2452 }
2453
2454 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2455 {
2456         DerivedMesh *final;
2457         
2458         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
2459
2460         return final;
2461 }
2462
2463 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2464 {
2465         DerivedMesh *final;
2466
2467         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
2468
2469         return final;
2470 }
2471
2472 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2473                                                                                    CustomDataMask dataMask)
2474 {
2475         DerivedMesh *final;
2476         
2477         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
2478
2479         return final;
2480 }
2481
2482 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2483                                                                                         CustomDataMask dataMask)
2484 {
2485         DerivedMesh *final;
2486         
2487         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
2488
2489         return final;
2490 }
2491
2492 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2493                                                                                         CustomDataMask dataMask)
2494 {
2495         DerivedMesh *final;
2496         
2497         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
2498
2499         return final;
2500 }
2501
2502 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2503                                                                                                   float (*vertCos)[3],
2504                                                                                                   CustomDataMask dataMask)
2505 {
2506         DerivedMesh *final;
2507
2508         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
2509
2510         return final;
2511 }
2512
2513 /***/
2514
2515 DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
2516                                                                                                  CustomDataMask dataMask)
2517 {
2518         /* if there's no derived mesh or the last data mask used doesn't include
2519          * the data we need, rebuild the derived mesh
2520          */
2521         if(!em->derivedCage ||
2522            (em->lastDataMask & dataMask) != dataMask)
2523                 editmesh_build_data(scene, obedit, em, dataMask);
2524
2525         *final_r = em->derivedFinal;
2526         return em->derivedCage;
2527 }
2528
2529 DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2530 {
2531         /* if there's no derived mesh or the last data mask used doesn't include
2532          * the data we need, rebuild the derived mesh
2533          */
2534         if(!em->derivedCage ||
2535            (em->lastDataMask & dataMask) != dataMask)
2536                 editmesh_build_data(scene, obedit, em, dataMask);
2537
2538         return em->derivedCage;
2539 }
2540
2541 DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
2542 {
2543         return editmesh_get_derived(em, NULL);
2544 }
2545
2546
2547 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2548
2549 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2550 {
2551         float *vec = userData;
2552         
2553         vec+= 6*index;
2554
2555         /* check if we've been here before (normal should not be 0) */
2556         if(vec[3] || vec[4] || vec[5]) return;
2557
2558         copy_v3_v3(vec, co);
2559         vec+= 3;
2560         if(no_f) {
2561                 copy_v3_v3(vec, no_f);
2562         }
2563         else {
2564                 normal_short_to_float_v3(vec, no_s);
2565         }
2566 }
2567
2568 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2569 /* this is needed for all code using vertexgroups (no subsurf support) */
2570 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2571 /* in use now by vertex/weight paint and particle generating */
2572
2573 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2574 {
2575         Mesh *me= ob->data;
2576         DerivedMesh *dm;
2577         float *vertexcosnos;
2578         
2579         /* lets prevent crashing... */
2580         if(ob->type!=OB_MESH || me->totvert==0)
2581                 return NULL;
2582         
2583         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2584         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2585         
2586         if(dm->foreachMappedVert) {
2587                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2588         }
2589         else {
2590                 float *fp= vertexcosnos;
2591                 int a;
2592                 
2593                 for(a=0; a< me->totvert; a++, fp+=6) {
2594                         dm->getVertCo(dm, a, fp);
2595                         dm->getVertNo(dm, a, fp+3);
2596                 }
2597         }
2598         
2599         dm->release(dm);
2600         return vertexcosnos;
2601 }
2602
2603 /* ******************* GLSL ******************** */
2604
2605 typedef struct
2606 {
2607         float * precomputedFaceNormals;
2608         MTFace * mtface;        // texture coordinates
2609         MFace * mface;          // indices
2610         MVert * mvert;          // vertices & normals
2611         float (*orco)[3];
2612         float (*tangent)[4];    // destination
2613         int numFaces;
2614
2615 } SGLSLMeshToTangent;
2616
2617 // interface
2618 #include "mikktspace.h"
2619
2620 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2621 {
2622         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2623         return pMesh->numFaces;
2624 }
2625
2626 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2627 {
2628         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2629         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2630 }
2631
2632 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2633 {
2634         //assert(vert_index>=0 && vert_index<4);
2635         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2636         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2637         VECCOPY(fPos, co);
2638 }
2639
2640 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2641 {
2642         //assert(vert_index>=0 && vert_index<4);
2643         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2644
2645         if(pMesh->mtface!=NULL) {
2646                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2647                 fUV[0]=uv[0]; fUV[1]=uv[1];
2648         }
2649         else {
2650                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2651                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2652         }
2653 }
2654
2655 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2656 {
2657         //assert(vert_index>=0 && vert_index<4);
2658         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2659
2660         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2661         if(!smoothnormal) {     // flat
2662                 if(pMesh->precomputedFaceNormals) {
2663                         VECCOPY(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2664                 }
2665                 else {
2666                         MFace *mf= &pMesh->mface[face_num];
2667                         float *p0= pMesh->mvert[mf->v1].co;
2668                         float *p1= pMesh->mvert[mf->v2].co;
2669                         float *p2= pMesh->mvert[mf->v3].co;
2670
2671                         if(mf->v4) {
2672                                 float *p3 = pMesh->mvert[mf->v4].co;
2673                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2674                         }
2675                         else {
2676                                 normal_tri_v3(fNorm, p0, p1, p2);
2677                         }
2678                 }
2679         }
2680         else {
2681                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2682                 normal_short_to_float_v3(fNorm, no);
2683         }
2684 }
2685 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2686 {
2687         //assert(vert_index>=0 && vert_index<4);
2688         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2689         float * pRes = pMesh->tangent[4*face_num+iVert];
2690         VECCOPY(pRes, fvTangent);
2691         pRes[3]=fSign;
2692 }
2693
2694
2695 void DM_add_tangent_layer(DerivedMesh *dm)
2696 {
2697         /* mesh vars */
2698         MTFace *mtface, *tf;
2699         MFace *mface, *mf;
2700         MVert *mvert, *v1, *v2, *v3, *v4;
2701         MemArena *arena= NULL;
2702         VertexTangent **vtangents= NULL;
2703         float (*orco)[3]= NULL, (*tangent)[4];
2704         float *uv1, *uv2, *uv3, *uv4, *vtang;
2705         float fno[3], tang[3], uv[4][2];
2706         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2707         float *nors;
2708
2709         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2710                 return;
2711
2712         nors = dm->getFaceDataArray(dm, CD_NORMAL);
2713
2714         /* check we have all the needed layers */
2715         totvert= dm->getNumVerts(dm);
2716         totface= dm->getNumFaces(dm);
2717
2718         mvert= dm->getVertArray(dm);
2719         mface= dm->getFaceArray(dm);
2720         mtface= dm->getFaceDataArray(dm, CD_MTFACE);
2721
2722         if(!mtface) {
2723                 orco= dm->getVertDataArray(dm, CD_ORCO);
2724                 if(!orco)
2725                         return;
2726         }
2727         
2728         /* create tangent layer */
2729         DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2730         tangent= DM_get_face_data_layer(dm, CD_TANGENT);
2731         
2732         /* allocate some space */
2733         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2734         BLI_memarena_use_calloc(arena);
2735         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2736
2737         // new computation method
2738         iCalcNewMethod = 1;
2739         if(iCalcNewMethod != 0) {
2740                 SGLSLMeshToTangent mesh2tangent= {0};
2741                 SMikkTSpaceContext sContext= {0};
2742                 SMikkTSpaceInterface sInterface= {0};
2743
2744                 mesh2tangent.precomputedFaceNormals = nors;
2745                 mesh2tangent.mtface = mtface;
2746                 mesh2tangent.mface = mface;
2747                 mesh2tangent.mvert = mvert;
2748                 mesh2tangent.orco = orco;
2749                 mesh2tangent.tangent = tangent;
2750                 mesh2tangent.numFaces = totface;
2751
2752                 sContext.m_pUserData = &mesh2tangent;
2753                 sContext.m_pInterface = &sInterface;
2754                 sInterface.m_getNumFaces = GetNumFaces;
2755                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2756                 sInterface.m_getPosition = GetPosition;
2757                 sInterface.m_getTexCoord = GetTextureCoordinate;
2758                 sInterface.m_getNormal = GetNormal;
2759                 sInterface.m_setTSpaceBasic = SetTSpace;
2760
2761                 // 0 if failed
2762                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2763         }
2764
2765         if(!iCalcNewMethod) {
2766                 /* sum tangents at connected vertices */
2767                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2768                         v1= &mvert[mf->v1];
2769                         v2= &mvert[mf->v2];
2770                         v3= &mvert[mf->v3];
2771
2772                         if (mf->v4) {
2773                                 v4= &mvert[mf->v4];
2774                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2775                         }
2776                         else {
2777                                 v4= NULL;
2778                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2779                         }
2780                 
2781                         if(mtface) {
2782                                 uv1= tf->uv[0];
2783                                 uv2= tf->uv[1];
2784                                 uv3= tf->uv[2];
2785                                 uv4= tf->uv[3];
2786                         }
2787                         else {
2788                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2789                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2790                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2791                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2792                                 if(v4)
2793                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2794                         }
2795                 
2796                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2797                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2798                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2799                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2800                 
2801                         if(mf->v4) {
2802                                 v4= &mvert[mf->v4];
2803                         
2804                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2805                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2806                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2807                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2808                         }
2809                 }
2810         
2811                 /* write tangent to layer */
2812                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2813                         len= (mf->v4)? 4 : 3; 
2814
2815                         if(mtface == NULL) {
2816                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2817                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2818                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2819                                 if(len==4)
2820                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2821                         }
2822                 
2823                         mf_vi[0]= mf->v1;
2824                         mf_vi[1]= mf->v2;
2825                         mf_vi[2]= mf->v3;
2826                         mf_vi[3]= mf->v4;
2827                 
2828                         for(j=0; j<len; j++) {
2829                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2830                                 normalize_v3_v3(tangent[j], vtang);
2831                                 ((float *) tangent[j])[3]=1.0f;
2832                         }
2833                 }
2834         }
2835         
2836         BLI_memarena_free(arena);
2837         MEM_freeN(vtangents);
2838 }
2839
2840 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2841 {
2842         CustomData *vdata, *fdata, *tfdata = NULL;
2843         int a, b, layer;
2844
2845         /* From the layers requested by the GLSL shader, figure out which ones are
2846          * actually available for this derivedmesh, and retrieve the pointers */
2847
2848         memset(attribs, 0, sizeof(DMVertexAttribs));
2849
2850         vdata = &dm->vertData;
2851         fdata = &dm->faceData;
2852
2853         /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
2854          * can use offsets instead */
2855         if(dm->release == emDM_release)
2856                 tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
2857         else
2858                 tfdata = fdata;
2859
2860         /* add a tangent layer if necessary */
2861         for(b = 0; b < gattribs->totlayer; b++)
2862                 if(gattribs->layer[b].type == CD_TANGENT)
2863                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2864                                 DM_add_tangent_layer(dm);
2865
2866         for(b = 0; b < gattribs->totlayer; b++) {
2867                 if(gattribs->layer[b].type == CD_MTFACE) {
2868                         /* uv coordinates */
2869                         if(gattribs->layer[b].name[0])
2870                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2871                                         gattribs->layer[b].name);
2872                         else
2873                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2874
2875                         if(layer != -1) {
2876                                 a = attribs->tottface++;
2877
2878                                 attribs->tface[a].array = tfdata->layers[layer].data;
2879                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2880                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2881                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2882                         }
2883                 }
2884                 else if(gattribs->layer[b].type == CD_MCOL) {
2885                         /* vertex colors */
2886                         if(gattribs->layer[b].name[0])
2887                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2888                                         gattribs->layer[b].name);
2889                         else
2890                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2891
2892                         if(layer != -1) {
2893                                 a = attribs->totmcol++;
2894
2895                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2896                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2897                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2898                         }
2899                 }
2900                 else if(gattribs->layer[b].type == CD_TANGENT) {
2901                         /* tangents */
2902                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2903
2904                         if(layer != -1) {
2905                                 attribs->tottang = 1;
2906
2907                                 attribs->tang.array = fdata->layers[layer].data;
2908                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2909                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2910                         }
2911                 }
2912                 else if(gattribs->layer[b].type == CD_ORCO) {
2913                         /* original coordinates */
2914                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2915
2916                         if(layer != -1) {
2917                                 attribs->totorco = 1;
2918
2919                                 attribs->orco.array = vdata->layers[layer].data;
2920                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2921                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2922                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2923                         }
2924                 }
2925         }
2926 }
2927
2928 /* Set object's bounding box based on DerivedMesh min/max data */
2929 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2930 {
2931         float min[3], max[3];
2932
2933         INIT_MINMAX(min, max);
2934
2935         dm->getMinMax(dm, min, max);
2936
2937         if(!ob->bb)
2938                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2939
2940         boundbox_set_from_min_max(ob->bb, min, max);
2941 }