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