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