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