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