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