Fix #28347: VBO's highlights wrong faces when Mirror modifier is in use
[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;
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                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1894                         
1895                         /* add cloth rest shape key if need */
1896                         if(mask & CD_MASK_CLOTH_ORCO)
1897                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1898
1899                         /* add an origspace layer if needed */
1900                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1901                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1902                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1903
1904                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1905
1906                         if(ndm) {
1907                                 /* if the modifier returned a new dm, release the old one */
1908                                 if(dm && dm != ndm) dm->release(dm);
1909
1910                                 dm = ndm;
1911
1912                                 if(deformedVerts) {
1913                                         if(deformedVerts != inputVertexCos)
1914                                                 MEM_freeN(deformedVerts);
1915
1916                                         deformedVerts = NULL;
1917                                 }
1918                         } 
1919
1920                         /* create an orco derivedmesh in parallel */
1921                         if(nextmask & CD_MASK_ORCO) {
1922                                 if(!orcodm)
1923                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1924
1925                                 nextmask &= ~CD_MASK_ORCO;
1926                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1927                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1928
1929                                 if(ndm) {
1930                                         /* if the modifier returned a new dm, release the old one */
1931                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1932                                         orcodm = ndm;
1933                                 }
1934                         }
1935
1936                         /* create cloth orco derivedmesh in parallel */
1937                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1938                                 if(!clothorcodm)
1939                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1940
1941                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1942                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1943                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1944
1945                                 if(ndm) {
1946                                         /* if the modifier returned a new dm, release the old one */
1947                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1948                                         clothorcodm = ndm;
1949                                 }
1950                         }
1951                 }
1952
1953                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1954
1955                 /* grab modifiers until index i */
1956                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1957                         break;
1958
1959                 if(sculpt_mode && md->type == eModifierType_Multires)
1960                         multires_applied = 1;
1961         }
1962
1963         for(md=firstmd; md; md=md->next)
1964                 modifier_freeTemporaryData(md);
1965
1966         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1967          * need to apply these back onto the DerivedMesh. If we have no
1968          * DerivedMesh then we need to build one.
1969          */
1970         if(dm && deformedVerts) {
1971                 finaldm = CDDM_copy(dm);
1972
1973                 dm->release(dm);
1974
1975                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1976                 CDDM_calc_normals(finaldm);
1977
1978                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1979                         add_weight_mcol_dm(ob, finaldm);
1980         } else if(dm) {
1981                 finaldm = dm;
1982         } else {
1983                 finaldm = CDDM_from_mesh(me, ob);
1984
1985                 if(deformedVerts) {
1986                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1987                         CDDM_calc_normals(finaldm);
1988                 }
1989
1990                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1991                         add_weight_mcol_dm(ob, finaldm);
1992         }
1993
1994         /* add an orco layer if needed */
1995         if(dataMask & CD_MASK_ORCO) {
1996                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1997
1998                 if(deform_r && *deform_r)
1999                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
2000         }
2001
2002         *final_r = finaldm;
2003
2004         if(orcodm)
2005                 orcodm->release(orcodm);
2006         if(clothorcodm)
2007                 clothorcodm->release(clothorcodm);
2008
2009         if(deformedVerts && deformedVerts != inputVertexCos)
2010                 MEM_freeN(deformedVerts);
2011
2012         BLI_linklist_free(datamasks, NULL);
2013 }
2014
2015 float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
2016 {
2017         int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
2018         float (*cos)[3];
2019         EditVert *eve;
2020
2021         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
2022         for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
2023                 VECCOPY(cos[i], eve->co);
2024         }
2025
2026         return cos;
2027 }
2028
2029 int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2030 {
2031         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2032         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2033
2034         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
2035         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2036                 modifier_setError(md, "Modifier requires original data, bad stack position.");
2037                 return 0;
2038         }
2039         
2040         return 1;
2041 }
2042
2043 static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
2044                                                                         DerivedMesh **final_r,
2045                                                                         CustomDataMask dataMask)
2046 {
2047         ModifierData *md;
2048         float (*deformedVerts)[3] = NULL;
2049         CustomDataMask mask;
2050         DerivedMesh *dm, *orcodm = NULL;
2051         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2052         LinkNode *datamasks, *curr;
2053         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2054
2055         modifiers_clearErrors(ob);
2056
2057         if(cage_r && cageIndex == -1) {
2058                 *cage_r = editmesh_get_derived(em, NULL);
2059         }
2060
2061         dm = NULL;
2062         md = modifiers_getVirtualModifierList(ob);
2063
2064         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
2065
2066         curr = datamasks;
2067         for(i = 0; md; i++, md = md->next, curr = curr->next) {
2068                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2069
2070                 md->scene= scene;
2071                 
2072                 if(!editmesh_modifier_is_enabled(scene, md, dm))
2073                         continue;
2074
2075                 /* add an orco layer if needed by this modifier */
2076                 if(dm && mti->requiredDataMask) {
2077                         mask = mti->requiredDataMask(ob, md);
2078                         if(mask & CD_MASK_ORCO)
2079                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2080                 }
2081
2082                 /* How to apply modifier depends on (a) what we already have as
2083                  * a result of previous modifiers (could be a DerivedMesh or just
2084                  * deformed vertices) and (b) what type the modifier is.
2085                  */
2086
2087                 if(mti->type == eModifierTypeType_OnlyDeform) {
2088                         /* No existing verts to deform, need to build them. */
2089                         if(!deformedVerts) {
2090                                 if(dm) {
2091                                         /* Deforming a derived mesh, read the vertex locations
2092                                          * out of the mesh and deform them. Once done with this
2093                                          * run of deformers verts will be written back.
2094                                          */
2095                                         numVerts = dm->getNumVerts(dm);
2096                                         deformedVerts =
2097                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2098                                         dm->getVertCos(dm, deformedVerts);
2099                                 } else {
2100                                         deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
2101                                 }
2102                         }
2103
2104                         if (mti->deformVertsEM)
2105                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2106                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
2107                 } else {
2108                         DerivedMesh *ndm;
2109
2110                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2111                         if(dm) {
2112                                 if(deformedVerts) {
2113                                         DerivedMesh *tdm = CDDM_copy(dm);
2114                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
2115                                         dm = tdm;
2116
2117                                         CDDM_apply_vert_coords(dm, deformedVerts);
2118                                         CDDM_calc_normals(dm);
2119                                 } else if(cage_r && dm == *cage_r) {
2120                                         /* dm may be changed by this modifier, so we need to copy it
2121                                          */
2122                                         dm = CDDM_copy(dm);
2123                                 }
2124
2125                         } else {
2126                                 dm = CDDM_from_editmesh(em, ob->data);
2127
2128                                 if(deformedVerts) {
2129                                         CDDM_apply_vert_coords(dm, deformedVerts);
2130                                         CDDM_calc_normals(dm);
2131                                 }
2132                         }
2133
2134                         /* create an orco derivedmesh in parallel */
2135                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2136                         if(mask & CD_MASK_ORCO) {
2137                                 if(!orcodm)
2138                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
2139
2140                                 mask &= ~CD_MASK_ORCO;
2141                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2142
2143                                 if (mti->applyModifierEM)
2144                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
2145                                 else
2146                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
2147
2148                                 if(ndm) {
2149                                         /* if the modifier returned a new dm, release the old one */
2150                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2151                                         orcodm = ndm;
2152                                 }
2153                         }
2154
2155                         /* set the DerivedMesh to only copy needed data */
2156                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
2157
2158                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2159
2160                         if(mask & CD_MASK_ORIGSPACE)
2161                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2162                                         DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2163                         
2164                         if (mti->applyModifierEM)
2165                                 ndm = mti->applyModifierEM(md, ob, em, dm);
2166                         else
2167                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
2168
2169                         if (ndm) {
2170                                 if(dm && dm != ndm)
2171                                         dm->release(dm);
2172
2173                                 dm = ndm;
2174
2175                                 if (deformedVerts) {
2176                                         MEM_freeN(deformedVerts);
2177                                         deformedVerts = NULL;
2178                                 }
2179                         }
2180                 }
2181
2182                 if(cage_r && i == cageIndex) {
2183                         if(dm && deformedVerts) {
2184                                 *cage_r = CDDM_copy(dm);
2185                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2186                         } else if(dm) {
2187                                 *cage_r = dm;
2188                         } else {
2189                                 *cage_r =
2190                                         editmesh_get_derived(em,
2191                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2192                         }
2193                 }
2194         }
2195
2196         BLI_linklist_free(datamasks, NULL);
2197
2198         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2199          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2200          * then we need to build one.
2201          */
2202         if(dm && deformedVerts) {
2203                 *final_r = CDDM_copy(dm);
2204
2205                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
2206
2207                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2208                 CDDM_calc_normals(*final_r);
2209         } else if (dm) {
2210                 *final_r = dm;
2211         } else if (!deformedVerts && cage_r && *cage_r) {
2212                 *final_r = *cage_r;
2213         } else {
2214                 *final_r = editmesh_get_derived(em, deformedVerts);
2215                 deformedVerts = NULL;
2216         }
2217
2218         /* add an orco layer if needed */
2219         if(dataMask & CD_MASK_ORCO)
2220                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2221
2222         if(orcodm)
2223                 orcodm->release(orcodm);
2224
2225         if(deformedVerts)
2226                 MEM_freeN(deformedVerts);
2227 }
2228
2229 static void clear_mesh_caches(Object *ob)
2230 {
2231         Mesh *me= ob->data;
2232
2233                 /* also serves as signal to remake texspace */
2234         if (ob->bb) {
2235                 MEM_freeN(ob->bb);
2236                 ob->bb = NULL;
2237         }
2238         if (me->bb) {
2239                 MEM_freeN(me->bb);
2240                 me->bb = NULL;
2241         }
2242
2243         freedisplist(&ob->disp);
2244
2245         if (ob->derivedFinal) {
2246                 ob->derivedFinal->needsFree = 1;
2247                 ob->derivedFinal->release(ob->derivedFinal);
2248                 ob->derivedFinal= NULL;
2249         }
2250         if (ob->derivedDeform) {
2251                 ob->derivedDeform->needsFree = 1;
2252                 ob->derivedDeform->release(ob->derivedDeform);
2253                 ob->derivedDeform= NULL;
2254         }
2255
2256         if(ob->sculpt) {
2257                 ED_sculpt_modifiers_changed(ob);
2258         }
2259 }
2260
2261 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
2262 {
2263         Object *obact = scene->basact?scene->basact->object:NULL;
2264         int editing = paint_facesel_test(ob);
2265         /* weight paint and face select need original indices because of selection buffer drawing */
2266         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
2267
2268         clear_mesh_caches(ob);
2269
2270         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2271                                                 &ob->derivedFinal, 0, 1,
2272                                                 needMapping, dataMask, -1, 1);
2273
2274         DM_set_object_boundbox (ob, ob->derivedFinal);
2275
2276         ob->derivedFinal->needsFree = 0;
2277         ob->derivedDeform->needsFree = 0;
2278         ob->lastDataMask = dataMask;
2279 }
2280
2281 static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2282 {
2283         clear_mesh_caches(obedit);
2284
2285         if (em->derivedFinal) {
2286                 if (em->derivedFinal!=em->derivedCage) {
2287                         em->derivedFinal->needsFree = 1;
2288                         em->derivedFinal->release(em->derivedFinal);
2289                 }
2290                 em->derivedFinal = NULL;
2291         }
2292         if (em->derivedCage) {
2293                 em->derivedCage->needsFree = 1;
2294                 em->derivedCage->release(em->derivedCage);
2295                 em->derivedCage = NULL;
2296         }
2297
2298         editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2299         DM_set_object_boundbox (obedit, em->derivedFinal);
2300
2301         em->lastDataMask = dataMask;
2302         em->derivedFinal->needsFree = 0;
2303         em->derivedCage->needsFree = 0;
2304 }
2305
2306 void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
2307 {
2308         if (em) {
2309                 editmesh_build_data(scene, ob, em, dataMask);
2310         } else {
2311                 mesh_build_data(scene, ob, dataMask);
2312         }
2313 }
2314
2315 /***/
2316
2317 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2318 {
2319         /* if there's no derived mesh or the last data mask used doesn't include
2320          * the data we need, rebuild the derived mesh
2321          */
2322         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2323                 mesh_build_data(scene, ob, dataMask);
2324
2325         return ob->derivedFinal;
2326 }
2327
2328 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2329 {
2330         /* if there's no derived mesh or the last data mask used doesn't include
2331          * the data we need, rebuild the derived mesh
2332          */
2333         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2334                 mesh_build_data(scene, ob, dataMask);
2335
2336         return ob->derivedDeform;
2337 }
2338
2339 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2340 {
2341         DerivedMesh *final;
2342         
2343         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
2344
2345         return final;
2346 }
2347
2348 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2349 {
2350         DerivedMesh *final;
2351         
2352         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
2353
2354         return final;
2355 }
2356
2357 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2358 {
2359         DerivedMesh *final;
2360
2361         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
2362
2363         return final;
2364 }
2365
2366 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2367                                                                                    CustomDataMask dataMask)
2368 {
2369         DerivedMesh *final;
2370         
2371         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
2372
2373         return final;
2374 }
2375
2376 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2377                                                                                         CustomDataMask dataMask)
2378 {
2379         DerivedMesh *final;
2380         
2381         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
2382
2383         return final;
2384 }
2385
2386 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2387                                                                                         CustomDataMask dataMask)
2388 {
2389         DerivedMesh *final;
2390         
2391         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
2392
2393         return final;
2394 }
2395
2396 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2397                                                                                                   float (*vertCos)[3],
2398                                                                                                   CustomDataMask dataMask)
2399 {
2400         DerivedMesh *final;
2401
2402         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
2403
2404         return final;
2405 }
2406
2407 /***/
2408
2409 DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
2410                                                                                                  CustomDataMask dataMask)
2411 {
2412         /* if there's no derived mesh or the last data mask used doesn't include
2413          * the data we need, rebuild the derived mesh
2414          */
2415         if(!em->derivedCage ||
2416            (em->lastDataMask & dataMask) != dataMask)
2417                 editmesh_build_data(scene, obedit, em, dataMask);
2418
2419         *final_r = em->derivedFinal;
2420         return em->derivedCage;
2421 }
2422
2423 DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
2424 {
2425         /* if there's no derived mesh or the last data mask used doesn't include
2426          * the data we need, rebuild the derived mesh
2427          */
2428         if(!em->derivedCage ||
2429            (em->lastDataMask & dataMask) != dataMask)
2430                 editmesh_build_data(scene, obedit, em, dataMask);
2431
2432         return em->derivedCage;
2433 }
2434
2435 DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
2436 {
2437         return editmesh_get_derived(em, NULL);
2438 }
2439
2440
2441 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2442
2443 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2444 {
2445         float *vec = userData;
2446         
2447         vec+= 6*index;
2448
2449         /* check if we've been here before (normal should not be 0) */
2450         if(vec[3] || vec[4] || vec[5]) return;
2451
2452         VECCOPY(vec, co);
2453         vec+= 3;
2454         if(no_f) {
2455                 VECCOPY(vec, no_f);
2456         }
2457         else {
2458                 VECCOPY(vec, no_s);
2459         }
2460 }
2461
2462 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2463 /* this is needed for all code using vertexgroups (no subsurf support) */
2464 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2465 /* in use now by vertex/weight paint and particle generating */
2466
2467 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2468 {
2469         Mesh *me= ob->data;
2470         DerivedMesh *dm;
2471         float *vertexcosnos;
2472         
2473         /* lets prevent crashing... */
2474         if(ob->type!=OB_MESH || me->totvert==0)
2475                 return NULL;
2476         
2477         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2478         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2479         
2480         if(dm->foreachMappedVert) {
2481                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2482         }
2483         else {
2484                 float *fp= vertexcosnos;
2485                 int a;
2486                 
2487                 for(a=0; a< me->totvert; a++, fp+=6) {
2488                         dm->getVertCo(dm, a, fp);
2489                         dm->getVertNo(dm, a, fp+3);
2490                 }
2491         }
2492         
2493         dm->release(dm);
2494         return vertexcosnos;
2495 }
2496
2497 /* ******************* GLSL ******************** */
2498
2499 typedef struct
2500 {
2501         float * precomputedFaceNormals;
2502         MTFace * mtface;        // texture coordinates
2503         MFace * mface;          // indices
2504         MVert * mvert;          // vertices & normals
2505         float (*orco)[3];
2506         float (*tangent)[4];    // destination
2507         int numFaces;
2508
2509 } SGLSLMeshToTangent;
2510
2511 // interface
2512 #include "mikktspace.h"
2513
2514 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2515 {
2516         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2517         return pMesh->numFaces;
2518 }
2519
2520 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2521 {
2522         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2523         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2524 }
2525
2526 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2527 {
2528         //assert(vert_index>=0 && vert_index<4);
2529         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2530         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2531         VECCOPY(fPos, co);
2532 }
2533
2534 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2535 {
2536         //assert(vert_index>=0 && vert_index<4);
2537         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2538
2539         if(pMesh->mtface!=NULL) {
2540                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2541                 fUV[0]=uv[0]; fUV[1]=uv[1];
2542         }
2543         else {
2544                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2545                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2546         }
2547 }
2548
2549 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2550 {
2551         //assert(vert_index>=0 && vert_index<4);
2552         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2553
2554         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2555         if(!smoothnormal) {     // flat
2556                 if(pMesh->precomputedFaceNormals) {
2557                         VECCOPY(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2558                 }
2559                 else {
2560                         MFace *mf= &pMesh->mface[face_num];
2561                         float *p0= pMesh->mvert[mf->v1].co;
2562                         float *p1= pMesh->mvert[mf->v2].co;
2563                         float *p2= pMesh->mvert[mf->v3].co;
2564
2565                         if(mf->v4) {
2566                                 float *p3 = pMesh->mvert[mf->v4].co;
2567                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2568                         }
2569                         else {
2570                                 normal_tri_v3(fNorm, p0, p1, p2);
2571                         }
2572                 }
2573         }
2574         else {
2575                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2576                 normal_short_to_float_v3(fNorm, no);
2577         }
2578 }
2579 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2580 {
2581         //assert(vert_index>=0 && vert_index<4);
2582         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2583         float * pRes = pMesh->tangent[4*face_num+iVert];
2584         VECCOPY(pRes, fvTangent);
2585         pRes[3]=fSign;
2586 }
2587
2588
2589 void DM_add_tangent_layer(DerivedMesh *dm)
2590 {
2591         /* mesh vars */
2592         MTFace *mtface, *tf;
2593         MFace *mface, *mf;
2594         MVert *mvert, *v1, *v2, *v3, *v4;
2595         MemArena *arena= NULL;
2596         VertexTangent **vtangents= NULL;
2597         float (*orco)[3]= NULL, (*tangent)[4];
2598         float *uv1, *uv2, *uv3, *uv4, *vtang;
2599         float fno[3], tang[3], uv[4][2];
2600         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2601         float *nors;
2602
2603         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2604                 return;
2605
2606         nors = dm->getFaceDataArray(dm, CD_NORMAL);
2607
2608         /* check we have all the needed layers */
2609         totvert= dm->getNumVerts(dm);
2610         totface= dm->getNumFaces(dm);
2611
2612         mvert= dm->getVertArray(dm);
2613         mface= dm->getFaceArray(dm);
2614         mtface= dm->getFaceDataArray(dm, CD_MTFACE);
2615
2616         if(!mtface) {
2617                 orco= dm->getVertDataArray(dm, CD_ORCO);
2618                 if(!orco)
2619                         return;
2620         }
2621         
2622         /* create tangent layer */
2623         DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2624         tangent= DM_get_face_data_layer(dm, CD_TANGENT);
2625         
2626         /* allocate some space */
2627         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2628         BLI_memarena_use_calloc(arena);
2629         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2630
2631         // new computation method
2632         iCalcNewMethod = 1;
2633         if(iCalcNewMethod != 0) {
2634                 SGLSLMeshToTangent mesh2tangent= {0};
2635                 SMikkTSpaceContext sContext= {0};
2636                 SMikkTSpaceInterface sInterface= {0};
2637
2638                 mesh2tangent.precomputedFaceNormals = nors;
2639                 mesh2tangent.mtface = mtface;
2640                 mesh2tangent.mface = mface;
2641                 mesh2tangent.mvert = mvert;
2642                 mesh2tangent.orco = orco;
2643                 mesh2tangent.tangent = tangent;
2644                 mesh2tangent.numFaces = totface;
2645
2646                 sContext.m_pUserData = &mesh2tangent;
2647                 sContext.m_pInterface = &sInterface;
2648                 sInterface.m_getNumFaces = GetNumFaces;
2649                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2650                 sInterface.m_getPosition = GetPosition;
2651                 sInterface.m_getTexCoord = GetTextureCoordinate;
2652                 sInterface.m_getNormal = GetNormal;
2653                 sInterface.m_setTSpaceBasic = SetTSpace;
2654
2655                 // 0 if failed
2656                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2657         }
2658
2659         if(!iCalcNewMethod) {
2660                 /* sum tangents at connected vertices */
2661                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2662                         v1= &mvert[mf->v1];
2663                         v2= &mvert[mf->v2];
2664                         v3= &mvert[mf->v3];
2665
2666                         if (mf->v4) {
2667                                 v4= &mvert[mf->v4];
2668                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2669                         }
2670                         else {
2671                                 v4= NULL;
2672                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2673                         }
2674                 
2675                         if(mtface) {
2676                                 uv1= tf->uv[0];
2677                                 uv2= tf->uv[1];
2678                                 uv3= tf->uv[2];
2679                                 uv4= tf->uv[3];
2680                         }
2681                         else {
2682                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2683                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2684                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2685                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2686                                 if(v4)
2687                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2688                         }
2689                 
2690                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2691                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2692                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2693                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2694                 
2695                         if(mf->v4) {
2696                                 v4= &mvert[mf->v4];
2697                         
2698                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2699                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2700                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2701                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2702                         }
2703                 }
2704         
2705                 /* write tangent to layer */
2706                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2707                         len= (mf->v4)? 4 : 3; 
2708
2709                         if(mtface == NULL) {
2710                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2711                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2712                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2713                                 if(len==4)
2714                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2715                         }
2716                 
2717                         mf_vi[0]= mf->v1;
2718                         mf_vi[1]= mf->v2;
2719                         mf_vi[2]= mf->v3;
2720                         mf_vi[3]= mf->v4;
2721                 
2722                         for(j=0; j<len; j++) {
2723                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2724                                 normalize_v3_v3(tangent[j], vtang);
2725                                 ((float *) tangent[j])[3]=1.0f;
2726                         }
2727                 }
2728         }
2729         
2730         BLI_memarena_free(arena);
2731         MEM_freeN(vtangents);
2732 }
2733
2734 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2735 {
2736         CustomData *vdata, *fdata, *tfdata = NULL;
2737         int a, b, layer;
2738
2739         /* From the layers requested by the GLSL shader, figure out which ones are
2740          * actually available for this derivedmesh, and retrieve the pointers */
2741
2742         memset(attribs, 0, sizeof(DMVertexAttribs));
2743
2744         vdata = &dm->vertData;
2745         fdata = &dm->faceData;
2746
2747         /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
2748          * can use offsets instead */
2749         if(dm->release == emDM_release)
2750                 tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
2751         else
2752                 tfdata = fdata;
2753
2754         /* add a tangent layer if necessary */
2755         for(b = 0; b < gattribs->totlayer; b++)
2756                 if(gattribs->layer[b].type == CD_TANGENT)
2757                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2758                                 DM_add_tangent_layer(dm);
2759
2760         for(b = 0; b < gattribs->totlayer; b++) {
2761                 if(gattribs->layer[b].type == CD_MTFACE) {
2762                         /* uv coordinates */
2763                         if(gattribs->layer[b].name[0])
2764                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2765                                         gattribs->layer[b].name);
2766                         else
2767                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2768
2769                         if(layer != -1) {
2770                                 a = attribs->tottface++;
2771
2772                                 attribs->tface[a].array = tfdata->layers[layer].data;
2773                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2774                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2775                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2776                         }
2777                 }
2778                 else if(gattribs->layer[b].type == CD_MCOL) {
2779                         /* vertex colors */
2780                         if(gattribs->layer[b].name[0])
2781                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2782                                         gattribs->layer[b].name);
2783                         else
2784                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2785
2786                         if(layer != -1) {
2787                                 a = attribs->totmcol++;
2788
2789                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2790                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2791                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2792                         }
2793                 }
2794                 else if(gattribs->layer[b].type == CD_TANGENT) {
2795                         /* tangents */
2796                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2797
2798                         if(layer != -1) {
2799                                 attribs->tottang = 1;
2800
2801                                 attribs->tang.array = fdata->layers[layer].data;
2802                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2803                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2804                         }
2805                 }
2806                 else if(gattribs->layer[b].type == CD_ORCO) {
2807                         /* original coordinates */
2808                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2809
2810                         if(layer != -1) {
2811                                 attribs->totorco = 1;
2812
2813                                 attribs->orco.array = vdata->layers[layer].data;
2814                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2815                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2816                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2817                         }
2818                 }
2819         }
2820 }
2821
2822 /* Set object's bounding box based on DerivedMesh min/max data */
2823 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2824 {
2825         float min[3], max[3];
2826
2827         INIT_MINMAX(min, max);
2828
2829         dm->getMinMax(dm, min, max);
2830
2831         if(!ob->bb)
2832                 ob->bb= MEM_callocN(sizeof(BoundBox), "bb");
2833
2834         boundbox_set_from_min_max(ob->bb, min, max);
2835 }