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