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