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