merge with trunk at r31523
[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 #include <string.h>
31
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_cloth_types.h"
36 #include "DNA_key_types.h"
37 #include "DNA_meshdata_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_scene_types.h" // N_T
40
41 #include "BLI_blenlib.h"
42 #include "BLI_editVert.h"
43 #include "BLI_math.h"
44 #include "BLI_memarena.h"
45 #include "BLI_array.h"
46 #include "BLI_pbvh.h"
47
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_displist.h"
50 #include "BKE_key.h"
51 #include "BKE_modifier.h"
52 #include "BKE_mesh.h"
53 #include "BKE_object.h"
54 #include "BKE_paint.h"
55 #include "BKE_texture.h"
56 #include "BKE_utildefines.h"
57 #include "BKE_particle.h"
58 #include "BKE_tessmesh.h"
59 #include "BKE_bvhutils.h"
60
61 #include "BLO_sys_types.h" // for intptr_t support
62
63 #include "BIF_gl.h"
64 #include "BIF_glutil.h"
65
66 #include "GPU_buffers.h"
67 #include "GPU_draw.h"
68 #include "GPU_extensions.h"
69 #include "GPU_material.h"
70
71 ///////////////////////////////////
72 ///////////////////////////////////
73
74 static MVert *dm_getVertArray(DerivedMesh *dm)
75 {
76         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
77
78         if (!mvert) {
79                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
80                         dm->getNumVerts(dm));
81                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
82                 dm->copyVertArray(dm, mvert);
83         }
84
85         return mvert;
86 }
87
88 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
89 {
90         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
91
92         if (!medge) {
93                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
94                         dm->getNumEdges(dm));
95                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
96                 dm->copyEdgeArray(dm, medge);
97         }
98
99         return medge;
100 }
101
102 static MFace *dm_getFaceArray(DerivedMesh *dm)
103 {
104         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
105
106         if (!mface) {
107                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
108                         dm->getNumTessFaces(dm));
109                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
110                 dm->copyTessFaceArray(dm, mface);
111         }
112
113         return mface;
114 }
115
116 static MVert *dm_dupVertArray(DerivedMesh *dm)
117 {
118         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
119                                                          "dm_dupVertArray tmp");
120
121         if(tmp) dm->copyVertArray(dm, tmp);
122
123         return tmp;
124 }
125
126 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
127 {
128         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
129                                                          "dm_dupEdgeArray tmp");
130
131         if(tmp) dm->copyEdgeArray(dm, tmp);
132
133         return tmp;
134 }
135
136 static MFace *dm_dupFaceArray(DerivedMesh *dm)
137 {
138         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
139                                                          "dm_dupFaceArray tmp");
140
141         if(tmp) dm->copyTessFaceArray(dm, tmp);
142
143         return tmp;
144 }
145
146 CustomData *dm_getVertCData(DerivedMesh *dm)
147 {
148         return &dm->vertData;
149 }
150
151 CustomData *dm_getEdgeCData(DerivedMesh *dm)
152 {
153         return &dm->edgeData;
154 }
155
156 CustomData *dm_getFaceCData(DerivedMesh *dm)
157 {
158         return &dm->faceData;
159 }
160
161 CustomData *dm_getLoopCData(DerivedMesh *dm)
162 {
163         return &dm->loopData;
164 }
165
166 CustomData *dm_getPolyCData(DerivedMesh *dm)
167 {
168         return &dm->polyData;
169 }
170
171 void DM_init_funcs(DerivedMesh *dm)
172 {
173         /* default function implementations */
174         dm->getVertArray = dm_getVertArray;
175         dm->getEdgeArray = dm_getEdgeArray;
176         dm->getTessFaceArray = dm_getFaceArray;
177         dm->dupVertArray = dm_dupVertArray;
178         dm->dupEdgeArray = dm_dupEdgeArray;
179         dm->dupTessFaceArray = dm_dupFaceArray;
180
181         dm->getVertDataLayout = dm_getVertCData;
182         dm->getEdgeDataLayout = dm_getEdgeCData;
183         dm->getTessFaceDataLayout = dm_getFaceCData;
184         dm->getLoopDataLayout = dm_getLoopCData;
185         dm->getFaceDataLayout = dm_getPolyCData;
186
187         dm->getVertData = DM_get_vert_data;
188         dm->getEdgeData = DM_get_edge_data;
189         dm->getTessFaceData = DM_get_face_data;
190         dm->getVertDataArray = DM_get_vert_data_layer;
191         dm->getEdgeDataArray = DM_get_edge_data_layer;
192         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
193
194         bvhcache_init(&dm->bvhCache);
195 }
196
197 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
198              int numFaces, int numLoops, int numPoly)
199 {
200         dm->type = type;
201         dm->numVertData = numVerts;
202         dm->numEdgeData = numEdges;
203         dm->numFaceData = numFaces;
204         dm->numLoopData = numLoops;
205         dm->numPolyData = numPoly;
206
207         DM_init_funcs(dm);
208         
209         dm->needsFree = 1;
210 }
211
212 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
213                       int numVerts, int numEdges, int numFaces,
214                       int numLoops, int numPolys)
215 {
216         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
217                                         CD_CALLOC, numVerts);
218         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
219                                         CD_CALLOC, numEdges);
220         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
221                                         CD_CALLOC, numFaces);
222         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
223                         CD_CALLOC, numLoops);
224         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
225                         CD_CALLOC, numPolys);
226
227         dm->type = type;
228         dm->numVertData = numVerts;
229         dm->numEdgeData = numEdges;
230         dm->numFaceData = numFaces;
231         dm->numLoopData = numLoops;
232         dm->numPolyData = numPolys;
233
234         DM_init_funcs(dm);
235
236         dm->needsFree = 1;
237 }
238
239 int DM_release(DerivedMesh *dm)
240 {
241         if (dm->needsFree) {
242                 bvhcache_free(&dm->bvhCache);
243                 GPU_drawobject_free( dm );
244                 CustomData_free(&dm->vertData, dm->numVertData);
245                 CustomData_free(&dm->edgeData, dm->numEdgeData);
246                 CustomData_free(&dm->faceData, dm->numFaceData);
247                 CustomData_free(&dm->loopData, dm->numLoopData);
248                 CustomData_free(&dm->polyData, dm->numPolyData);
249
250                 return 1;
251         }
252         else {
253                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
254                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
255                 CustomData_free_temporary(&dm->faceData, dm->numFaceData);
256                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
257                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
258
259                 return 0;
260         }
261 }
262
263 void dm_add_polys_from_iter(CustomData *ldata, CustomData *pdata, DerivedMesh *dm, int totloop)
264 {
265         DMFaceIter *iter = dm->newFaceIter(dm);
266         DMLoopIter *liter;
267         CustomData *oldata, *opdata;
268         MPoly *mpoly;
269         MLoop *mloop;
270         int p, l, i, j, lasttype;
271
272         oldata = dm->getLoopDataLayout(dm);
273         opdata = dm->getFaceDataLayout(dm);
274
275         CustomData_copy(oldata, ldata, CD_MASK_DERIVEDMESH, CD_CALLOC, totloop);
276         CustomData_copy(opdata, pdata, CD_MASK_DERIVEDMESH, CD_CALLOC, dm->getNumFaces(dm));
277
278         mloop = MEM_callocN(sizeof(MLoop)*totloop, "MLoop from dm_add_polys_from_iter");
279         CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop);
280         mpoly = MEM_callocN(sizeof(MPoly)*dm->getNumFaces(dm), "MPoly from dm_add_polys_from_iter");
281         CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, dm->getNumFaces(dm));
282
283         l = 0;
284         for (p=0; !iter->done; iter->step(iter), mpoly++, p++) {
285                 mpoly->flag = iter->flags;
286                 mpoly->loopstart = l;
287                 mpoly->totloop = iter->len;
288                 mpoly->mat_nr = iter->mat_nr;
289                 
290                 j = 0;
291                 lasttype = -1;
292                 for (i=0; i<opdata->totlayer; i++) {
293                         void *e1, *e2;
294
295                         if (opdata->layers[i].type == lasttype)
296                                 j++;
297                         else
298                                 j = 0;
299
300                         if (opdata->layers[i].type == CD_MPOLY)
301                                 continue;
302                         
303                         e1 = iter->getCDData(iter, opdata->layers[i].type, j);
304                         e2 = (char*)CustomData_get_n(pdata, opdata->layers[i].type, p, j);
305                         
306                         if (!e2)
307                                 continue;
308
309                         CustomData_copy_elements(opdata->layers[i].type, e1, e2, 1);
310                         
311                         lasttype = opdata->layers[i].type;                              
312                 }
313
314                 liter = iter->getLoopsIter(iter);
315                 for (; !liter->done; liter->step(liter), mloop++, l++) {
316                         mloop->v = liter->vindex;
317                         mloop->e = liter->eindex;
318
319                         j = 0;
320                         lasttype = -1;
321                         for (i=0; i<oldata->totlayer; i++) {
322                                 void *e1, *e2;
323
324                                 if (oldata->layers[i].type == CD_MLOOP)
325                                         continue;
326                                 
327                                 if (oldata->layers[i].type == lasttype)
328                                         j++;
329                                 else
330                                         j = 0;
331
332                                 e1 = liter->getLoopCDData(liter, oldata->layers[i].type, j);
333                                 e2 = CustomData_get_n(ldata, oldata->layers[i].type, l, j);
334                                 
335                                 if (!e2)
336                                         continue;
337
338                                 CustomData_copy_elements(oldata->layers[i].type, e1, e2, 1);
339                                 lasttype = oldata->layers[i].type;                              
340                         }
341                 }
342         }
343         iter->free(iter);
344 }
345
346 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
347 {
348         DMFaceIter *iter = source->newFaceIter(source);
349         DMLoopIter *liter;
350         int totloop = source->numLoopData;
351
352         dm_add_polys_from_iter(&target->loopData, &target->polyData, source, totloop);
353
354         target->numLoopData = totloop;
355         target->numPolyData = source->getNumFaces(source);
356 }
357
358 void DM_to_mesh(DerivedMesh *dm, Mesh *me)
359 {
360         /* dm might depend on me, so we need to do everything with a local copy */
361         Mesh tmp = *me;
362         DMFaceIter *iter;
363         int totvert, totedge, totface, totloop, totpoly;
364
365         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
366         memset(&tmp.edata, 0, sizeof(tmp.edata));
367         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
368         memset(&tmp.ldata, 0, sizeof(tmp.ldata));
369         memset(&tmp.pdata, 0, sizeof(tmp.pdata));
370
371         totvert = tmp.totvert = dm->getNumVerts(dm);
372         totedge = tmp.totedge = dm->getNumEdges(dm);
373         totface = tmp.totface = dm->getNumTessFaces(dm);
374         totpoly = tmp.totpoly = dm->getNumFaces(dm);
375         
376         totloop = 0;
377         for (iter=dm->newFaceIter(dm); !iter->done; iter->step(iter)) {
378                 totloop += iter->len;
379         }
380         iter->free(iter);
381         
382         tmp.totloop = totloop;
383
384         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
385         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
386         CustomData_copy(&dm->faceData, &tmp.fdata, CD_MASK_MESH, CD_DUPLICATE, totface);
387         CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
388         CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
389
390         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
391            we set them here in case they are missing */
392         if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
393                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
394         if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
395                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
396         if(!CustomData_has_layer(&tmp.fdata, CD_MFACE))
397                 CustomData_add_layer(&tmp.fdata, CD_MFACE, CD_ASSIGN, dm->dupTessFaceArray(dm), totface);
398         if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY))
399                 dm_add_polys_from_iter(&tmp.ldata, &tmp.pdata, dm, totloop);
400
401         mesh_update_customdata_pointers(&tmp);
402
403         CustomData_free(&me->vdata, me->totvert);
404         CustomData_free(&me->edata, me->totedge);
405         CustomData_free(&me->fdata, me->totface);
406         CustomData_free(&me->ldata, me->totloop);
407         CustomData_free(&me->pdata, me->totpoly);
408
409         /* BMESH_TODO/XXX: ok, this should use new CD shapekey data,
410                            which shouuld be fed through the modifier 
411                                            stack*/
412         if(tmp.totvert != me->totvert) {
413                 printf("YEEK! this should be recoded! Shape key loss!!!\n");
414                 if(tmp.key) tmp.key->id.us--;
415                 tmp.key = NULL;
416         }
417
418         *me = tmp;
419 }
420
421 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
422 {
423         int a, totvert = dm->getNumVerts(dm);
424         float *fp;
425         MVert *mvert;
426         
427         if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
428         
429         if(kb->data) MEM_freeN(kb->data);
430         kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
431         kb->totelem= totvert;
432         
433         fp= kb->data;
434         mvert=dm->getVertDataArray(dm, CD_MVERT);
435         
436         for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
437                 VECCOPY(fp, mvert->co);
438         }
439 }
440
441 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
442 {
443         CustomData_set_only_copy(&dm->vertData, mask);
444         CustomData_set_only_copy(&dm->edgeData, mask);
445         CustomData_set_only_copy(&dm->faceData, mask);
446 }
447
448 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
449 {
450         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
451 }
452
453 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
454 {
455         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
456 }
457
458 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
459 {
460         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numFaceData);
461 }
462
463 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
464 {
465         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
466 }
467
468 void DM_add_face_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
469 {
470         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
471 }
472
473 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
474 {
475         return CustomData_get(&dm->vertData, index, type);
476 }
477
478 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
479 {
480         return CustomData_get(&dm->edgeData, index, type);
481 }
482
483 void *DM_get_face_data(DerivedMesh *dm, int index, int type)
484 {
485         return CustomData_get(&dm->faceData, index, type);
486 }
487
488 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
489 {
490         if(type == CD_MVERT)
491                 return dm->getVertArray(dm);
492
493         return CustomData_get_layer(&dm->vertData, type);
494 }
495
496 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
497 {
498         if(type == CD_MEDGE)
499                 return dm->getEdgeArray(dm);
500
501         return CustomData_get_layer(&dm->edgeData, type);
502 }
503
504 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
505 {
506         if(type == CD_MFACE)
507                 return dm->getTessFaceArray(dm);
508
509         return CustomData_get_layer(&dm->faceData, type);
510 }
511
512 void *DM_get_face_data_layer(DerivedMesh *dm, int type)
513 {
514         return CustomData_get_layer(&dm->polyData, type);
515 }
516
517 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
518 {
519         CustomData_set(&dm->vertData, index, type, data);
520 }
521
522 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
523 {
524         CustomData_set(&dm->edgeData, index, type, data);
525 }
526
527 void DM_set_face_data(DerivedMesh *dm, int index, int type, void *data)
528 {
529         CustomData_set(&dm->faceData, index, type, data);
530 }
531
532 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
533                                            int source_index, int dest_index, int count)
534 {
535         CustomData_copy_data(&source->vertData, &dest->vertData,
536                                                  source_index, dest_index, count);
537 }
538
539 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
540                                            int source_index, int dest_index, int count)
541 {
542         CustomData_copy_data(&source->edgeData, &dest->edgeData,
543                                                  source_index, dest_index, count);
544 }
545
546 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
547                                            int source_index, int dest_index, int count)
548 {
549         CustomData_copy_data(&source->faceData, &dest->faceData,
550                                                  source_index, dest_index, count);
551 }
552
553 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
554                        int source_index, int dest_index, int count)
555 {
556         CustomData_copy_data(&source->loopData, &dest->loopData,
557                              source_index, dest_index, count);
558 }
559
560 void DM_copy_face_data(DerivedMesh *source, DerivedMesh *dest,
561                        int source_index, int dest_index, int count)
562 {
563         CustomData_copy_data(&source->polyData, &dest->polyData,
564                              source_index, dest_index, count);
565 }
566
567 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
568 {
569         CustomData_free_elem(&dm->vertData, index, count);
570 }
571
572 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
573 {
574         CustomData_free_elem(&dm->edgeData, index, count);
575 }
576
577 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
578 {
579         CustomData_free_elem(&dm->faceData, index, count);
580 }
581
582 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
583 {
584         CustomData_free_elem(&dm->loopData, index, count);
585 }
586
587 void DM_free_face_data(struct DerivedMesh *dm, int index, int count)
588 {
589         CustomData_free_elem(&dm->polyData, index, count);
590 }
591
592 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
593                                                  int *src_indices, float *weights,
594                                                  int count, int dest_index)
595 {
596         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
597                                           weights, NULL, count, dest_index);
598 }
599
600 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
601                                                  int *src_indices,
602                                                  float *weights, EdgeVertWeight *vert_weights,
603                                                  int count, int dest_index)
604 {
605         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
606                                           weights, (float*)vert_weights, count, dest_index);
607 }
608
609 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
610                                                  int *src_indices,
611                                                  float *weights, FaceVertWeight *vert_weights,
612                                                  int count, int dest_index)
613 {
614         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
615                                           weights, (float*)vert_weights, count, dest_index);
616 }
617
618 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
619 {
620         CustomData_swap(&dm->faceData, index, corner_indices);
621 }
622
623 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
624                          int *src_indices,
625                          float *weights, int count, int dest_index)
626 {
627         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
628                           weights, NULL, count, dest_index);
629 }
630
631 void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
632                          int *src_indices,
633                          float *weights, int count, int dest_index)
634 {
635         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
636                           weights, NULL, count, dest_index);
637 }
638
639 ///
640 static DerivedMesh *getMeshDerivedMesh(Mesh *me, Object *ob, float (*vertCos)[3])
641 {
642         DerivedMesh *dm = CDDM_from_mesh(me, ob);
643         
644         if(!dm)
645                 return NULL;
646         
647         if (vertCos)
648                 CDDM_apply_vert_coords(dm, vertCos);
649
650         CDDM_calc_normals(dm);
651
652         return dm;
653 }
654
655 /***/
656
657 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
658 {
659         Mesh *me = ob->data;
660         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
661         DerivedMesh *dm;
662
663         md->scene= scene;
664         
665         if (!(md->mode&eModifierMode_Realtime)) return NULL;
666         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
667
668         if (mti->type==eModifierTypeType_OnlyDeform) {
669                 int numVerts;
670                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
671
672                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
673                 dm = getMeshDerivedMesh(me, ob, deformedVerts);
674
675                 MEM_freeN(deformedVerts);
676         } else {
677                 DerivedMesh *tdm = getMeshDerivedMesh(me, ob, NULL);
678                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
679
680                 if(tdm != dm) tdm->release(tdm);
681         }
682
683         return dm;
684 }
685
686 static float *get_editbmesh_orco_verts(BMEditMesh *em)
687 {
688         BMIter iter;
689         BMVert *eve;
690         float *orco;
691         int a, totvert;
692
693         /* these may not really be the orco's, but it's only for preview.
694          * could be solver better once, but isn't simple */
695
696         totvert= em->bm->totvert;
697         
698         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
699
700         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
701         for (a=0; eve; eve=BMIter_Step(&iter), a+=3)
702                 VECCOPY(orco+a, eve->co);
703         
704         return orco;
705 }
706
707 /* orco custom data layer */
708 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
709 {
710         *free= 0;
711
712         if(layer == CD_ORCO) {
713                 /* get original coordinates */
714                 *free= 1;
715
716                 if(em)
717                         return (float(*)[3])get_editbmesh_orco_verts(em);
718                 else
719                         return (float(*)[3])get_mesh_orco_verts(ob);
720         }
721         else if(layer == CD_CLOTH_ORCO) {
722                 /* apply shape key for cloth, this should really be solved
723                    by a more flexible customdata system, but not simple */
724                 if(!em) {
725                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
726                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
727
728                         if(kb->data)
729                                 return kb->data;
730                 }
731
732                 return NULL;
733         }
734
735         return NULL;
736 }
737
738 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
739 {
740         DerivedMesh *dm;
741         float (*orco)[3];
742         int free;
743
744         if(em) dm= CDDM_from_BMEditMesh(em, me);
745         else dm= CDDM_from_mesh(me, ob);
746
747         orco= get_orco_coords_dm(ob, em, layer, &free);
748
749         if(orco) {
750                 CDDM_apply_vert_coords(dm, orco);
751                 if(free) MEM_freeN(orco);
752         }
753
754         CDDM_calc_normals(dm);
755
756         return dm;
757 }
758
759 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
760                                                 DerivedMesh *orcodm, int layer)
761 {
762         float (*orco)[3], (*layerorco)[3];
763         int totvert, free;
764
765         totvert= dm->getNumVerts(dm);
766
767         if(orcodm) {
768                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
769                 free= 1;
770
771                 if(orcodm->getNumVerts(orcodm) == totvert)
772                         orcodm->getVertCos(orcodm, orco);
773                 else
774                         dm->getVertCos(dm, orco);
775         }
776         else
777                 orco= get_orco_coords_dm(ob, em, layer, &free);
778
779         if(orco) {
780                 if(layer == CD_ORCO)
781                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
782
783                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
784                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
785                         layerorco = DM_get_vert_data_layer(dm, layer);
786                 }
787
788                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
789                 if(free) MEM_freeN(orco);
790         }
791 }
792
793 /* weight paint colors */
794
795 /* Something of a hack, at the moment deal with weightpaint
796  * by tucking into colors during modifier eval, only in
797  * wpaint mode. Works ok but need to make sure recalc
798  * happens on enter/exit wpaint.
799  */
800
801 void weight_to_rgb(float input, float *fr, float *fg, float *fb)
802 {
803         float blend;
804         
805         blend= ((input/2.0f)+0.5f);
806         
807         if (input<=0.25f){      // blue->cyan
808                 *fr= 0.0f;
809                 *fg= blend*input*4.0f;
810                 *fb= blend;
811         }
812         else if (input<=0.50f){ // cyan->green
813                 *fr= 0.0f;
814                 *fg= blend;
815                 *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
816         }
817         else if (input<=0.75){  // green->yellow
818                 *fr= blend * ((input-0.50f)*4.0f);
819                 *fg= blend;
820                 *fb= 0.0f;
821         }
822         else if (input<=1.0){ // yellow->red
823                 *fr= blend;
824                 *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
825                 *fb= 0.0f;
826         }
827 }
828
829 static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, unsigned char *col)
830 {
831         Mesh *me = ob->data;
832         float colf[4], input = 0.0f;
833         int i;
834
835         if (me->dvert) {
836                 for (i=0; i<me->dvert[vert].totweight; i++)
837                         if (me->dvert[vert].dw[i].def_nr==ob->actdef-1)
838                                 input+=me->dvert[vert].dw[i].weight;            
839         }
840
841         CLAMP(input, 0.0f, 1.0f);
842         
843         if(coba)
844                 do_colorband(coba, input, colf);
845         else
846                 weight_to_rgb(input, colf, colf+1, colf+2);
847         
848         col[3] = (unsigned char)(colf[0] * 255.0f);
849         col[2] = (unsigned char)(colf[1] * 255.0f);
850         col[1] = (unsigned char)(colf[2] * 255.0f);
851         col[0] = 255;
852 }
853
854 static ColorBand *stored_cb= NULL;
855
856 void vDM_ColorBand_store(ColorBand *coba)
857 {
858         stored_cb= coba;
859 }
860
861 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm)
862 {
863         Mesh *me = ob->data;
864         MFace *mf = dm->getTessFaceArray(dm);
865         DMFaceIter *dfiter;
866         DMLoopIter *dliter;
867         ColorBand *coba= stored_cb;     /* warning, not a local var */
868         unsigned char *wtcol;
869         unsigned char(*wlcol)[4] = NULL;
870         BLI_array_declare(wlcol);
871         int i, totface=dm->getNumTessFaces(dm), totpoly=dm->getNumFaces, totloop;
872         int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
873         
874         wtcol = MEM_callocN (sizeof (unsigned char) * totface*4*4, "weightmap");
875         
876         /*first add colors to the tesselation faces*/
877         memset(wtcol, 0x55, sizeof (unsigned char) * totface*4*4);
878         for (i=0; i<totface; i++, mf++) {
879                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4]); 
880                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4]); 
881                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4]); 
882                 if (mf->v4)
883                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4]); 
884         }
885         
886         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, totface);
887
888         /*now add to loops, so the data can be passed through the modifier stack*/
889         totloop = 0;
890         dfiter = dm->newFaceIter(dm);
891         for (; !dfiter->done; dfiter->step(dfiter)) {
892                 dliter = dfiter->getLoopsIter(dfiter);
893                 for (; !dliter->done; dliter->step(dliter), totloop++) {
894                         BLI_array_growone(wlcol);
895                         calc_weightpaint_vert_color(ob, coba, dliter->vindex, (unsigned
896 char *)&wlcol[totloop]);                         
897                 }
898         }
899
900         CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wlcol, totloop);
901
902         dfiter->free(dfiter);
903 }
904
905 /* new value for useDeform -1  (hack for the gameengine):
906  * - apply only the modifier stack of the object, skipping the virtual modifiers,
907  * - don't apply the key
908  * - apply deform modifiers and input vertexco
909  */
910 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
911                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
912                                                                 int useRenderParams, int useDeform,
913                                                                 int needMapping, CustomDataMask dataMask, int index, int useCache)
914 {
915         Mesh *me = ob->data;
916         ModifierData *firstmd, *md;
917         LinkNode *datamasks, *curr;
918         CustomDataMask mask, nextmask;
919         float (*deformedVerts)[3] = NULL;
920         DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
921         int numVerts = me->totvert;
922         int required_mode;
923
924         md = firstmd = (useDeform<0) ? ob->modifiers.first : modifiers_getVirtualModifierList(ob);
925
926         modifiers_clearErrors(ob);
927
928         if(useRenderParams) required_mode = eModifierMode_Render;
929         else required_mode = eModifierMode_Realtime;
930
931         /* we always want to keep original indices */
932         dataMask |= CD_MASK_ORIGINDEX;
933
934         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
935         curr = datamasks;
936
937         if(deform_r) *deform_r = NULL;
938         *final_r = NULL;
939
940         if(useDeform) {
941                 if(inputVertexCos)
942                         deformedVerts = inputVertexCos;
943                 
944                 /* Apply all leading deforming modifiers */
945                 for(;md; md = md->next, curr = curr->next) {
946                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
947
948                         md->scene= scene;
949                         
950                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
951                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
952
953                         if(mti->type == eModifierTypeType_OnlyDeform) {
954                                 if(!deformedVerts)
955                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
956
957                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
958                         } else {
959                                 break;
960                         }
961                         
962                         /* grab modifiers until index i */
963                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
964                                 break;
965                 }
966
967                 /* Result of all leading deforming modifiers is cached for
968                  * places that wish to use the original mesh but with deformed
969                  * coordinates (vpaint, etc.)
970                  */
971                 if (deform_r) {
972                         *deform_r = CDDM_from_mesh(me, ob);
973
974                         if(deformedVerts) {
975                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
976                                 CDDM_calc_normals(*deform_r);
977                         }
978                 }
979         } else {
980                 /* default behaviour for meshes */
981                 if(inputVertexCos)
982                         deformedVerts = inputVertexCos;
983                 else
984                         deformedVerts = mesh_getVertexCos(me, &numVerts);
985         }
986
987
988         /* Now apply all remaining modifiers. If useDeform is off then skip
989          * OnlyDeform ones. 
990          */
991         dm = NULL;
992         orcodm = NULL;
993         clothorcodm = NULL;
994
995         for(;md; md = md->next, curr = curr->next) {
996                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
997
998                 md->scene= scene;
999                 
1000                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1001                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1002                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1003                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1004                         continue;
1005                 }
1006                 if(needMapping && !modifier_supportsMapping(md)) continue;
1007                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1008
1009                 /* add an orco layer if needed by this modifier */
1010                 if(mti->requiredDataMask)
1011                         mask = mti->requiredDataMask(ob, md);
1012                 else
1013                         mask = 0;
1014
1015                 if(dm && (mask & CD_MASK_ORCO))
1016                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1017
1018                 /* How to apply modifier depends on (a) what we already have as
1019                  * a result of previous modifiers (could be a DerivedMesh or just
1020                  * deformed vertices) and (b) what type the modifier is.
1021                  */
1022
1023                 if(mti->type == eModifierTypeType_OnlyDeform) {
1024                         /* No existing verts to deform, need to build them. */
1025                         if(!deformedVerts) {
1026                                 if(dm) {
1027                                         /* Deforming a derived mesh, read the vertex locations
1028                                          * out of the mesh and deform them. Once done with this
1029                                          * run of deformers verts will be written back.
1030                                          */
1031                                         numVerts = dm->getNumVerts(dm);
1032                                         deformedVerts =
1033                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1034                                         dm->getVertCos(dm, deformedVerts);
1035                                 } else {
1036                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1037                                 }
1038                         }
1039
1040                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1041                 } else {
1042                         DerivedMesh *ndm;
1043
1044                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1045                         if(dm) {
1046                                 if(deformedVerts) {
1047                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1048                                         dm->release(dm);
1049                                         dm = tdm;
1050
1051                                         CDDM_apply_vert_coords(dm, deformedVerts);
1052                                         CDDM_calc_normals(dm);
1053                                 }
1054                         } else {
1055                                 dm = CDDM_from_mesh(me, ob);
1056
1057                                 if(deformedVerts) {
1058                                         CDDM_apply_vert_coords(dm, deformedVerts);
1059                                         CDDM_calc_normals(dm);
1060                                 }
1061
1062                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1063                                         add_weight_mcol_dm(ob, dm);
1064
1065                                 /* constructive modifiers need to have an origindex
1066                                  * otherwise they wont have anywhere to copy the data from */
1067                                 if(needMapping) {
1068                                         int *index, i;
1069                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1070                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1071                                         DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1072
1073                                         index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1074                                         for(i=0; i<dm->numVertData; i++) *index++= i;
1075                                         index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1076                                         for(i=0; i<dm->numEdgeData; i++) *index++= i;
1077                                         index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
1078                                         for(i=0; i<dm->numFaceData; i++) *index++= i;
1079                                 }
1080                         }
1081
1082                         /* determine which data layers are needed by following modifiers */
1083                         if(curr->next)
1084                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1085                         else
1086                                 nextmask= dataMask;
1087                         
1088                         /* set the DerivedMesh to only copy needed data */
1089                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1090                         DM_set_only_copy(dm, mask);
1091                         
1092                         /* add cloth rest shape key if need */
1093                         if(mask & CD_MASK_CLOTH_ORCO)
1094                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1095
1096                         /* add an origspace layer if needed */
1097                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1098                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1099                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1100
1101                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1102
1103                         if(ndm) {
1104                                 /* if the modifier returned a new dm, release the old one */
1105                                 if(dm && dm != ndm) dm->release(dm);
1106
1107                                 dm = ndm;
1108
1109                                 if(deformedVerts) {
1110                                         if(deformedVerts != inputVertexCos)
1111                                                 MEM_freeN(deformedVerts);
1112
1113                                         deformedVerts = NULL;
1114                                 }
1115                         } 
1116
1117                         /* create an orco derivedmesh in parallel */
1118                         if(nextmask & CD_MASK_ORCO) {
1119                                 if(!orcodm)
1120                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1121
1122                                 nextmask &= ~CD_MASK_ORCO;
1123                                 DM_set_only_copy(orcodm, nextmask);
1124                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1125
1126                                 if(ndm) {
1127                                         /* if the modifier returned a new dm, release the old one */
1128                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1129                                         orcodm = ndm;
1130                                 }
1131                         }
1132
1133                         /* create cloth orco derivedmesh in parallel */
1134                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1135                                 if(!clothorcodm)
1136                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1137
1138                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1139                                 DM_set_only_copy(clothorcodm, nextmask);
1140                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1141
1142                                 if(ndm) {
1143                                         /* if the modifier returned a new dm, release the old one */
1144                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1145                                         clothorcodm = ndm;
1146                                 }
1147                         }
1148                 }
1149
1150                 /* grab modifiers until index i */
1151                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1152                         break;
1153         }
1154
1155         for(md=firstmd; md; md=md->next)
1156                 modifier_freeTemporaryData(md);
1157
1158         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1159          * need to apply these back onto the DerivedMesh. If we have no
1160          * DerivedMesh then we need to build one.
1161          */
1162         if(dm && deformedVerts) {
1163                 finaldm = CDDM_copy(dm, 0);
1164
1165                 dm->release(dm);
1166
1167                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1168                 CDDM_calc_normals(finaldm);
1169
1170                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1171                         add_weight_mcol_dm(ob, finaldm);
1172         } else if(dm) {
1173                 finaldm = dm;
1174         } else {
1175                 finaldm = CDDM_from_mesh(me, ob);
1176
1177                 if(deformedVerts) {
1178                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1179                         CDDM_calc_normals(finaldm);
1180                 }
1181
1182                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1183                         add_weight_mcol_dm(ob, finaldm);
1184         }
1185
1186         /* add an orco layer if needed */
1187         if(dataMask & CD_MASK_ORCO) {
1188                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1189
1190                 if(deform_r && *deform_r)
1191                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1192         }
1193
1194         *final_r = finaldm;
1195
1196         if(orcodm)
1197                 orcodm->release(orcodm);
1198         if(clothorcodm)
1199                 clothorcodm->release(clothorcodm);
1200
1201         if(deformedVerts && deformedVerts != inputVertexCos)
1202                 MEM_freeN(deformedVerts);
1203
1204         BLI_linklist_free(datamasks, NULL);
1205 }
1206
1207 static float (*editbmesh_getVertexCos(BMEditMesh *em, int *numVerts_r))[3]
1208 {
1209         int i, numVerts = *numVerts_r = em->bm->totvert;
1210         float (*cos)[3];
1211         BMIter iter;
1212         BMVert *eve;
1213
1214         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
1215
1216         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1217         for (i=0; eve; eve=BMIter_Step(&iter), i++) {
1218                 VECCOPY(cos[i], eve->co);
1219         }
1220
1221         return cos;
1222 }
1223
1224 static int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1225 {
1226         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1227         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1228
1229         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1230         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1231                 modifier_setError(md, "Modifier requires original data, bad stack position.");
1232                 return 0;
1233         }
1234         
1235         return 1;
1236 }
1237
1238 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1239                                                                         DerivedMesh **final_r,
1240                                                                         CustomDataMask dataMask)
1241 {
1242         ModifierData *md;
1243         float (*deformedVerts)[3] = NULL;
1244         CustomDataMask mask;
1245         DerivedMesh *dm, *orcodm = NULL;
1246         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1247         LinkNode *datamasks, *curr;
1248         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1249
1250         modifiers_clearErrors(ob);
1251
1252         if(cage_r && cageIndex == -1) {
1253                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1254         }
1255
1256         dm = NULL;
1257         md = modifiers_getVirtualModifierList(ob);
1258         
1259         /* we always want to keep original indices */
1260         dataMask |= CD_MASK_ORIGINDEX;
1261
1262         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1263
1264         curr = datamasks;
1265         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1266                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1267
1268                 md->scene= scene;
1269                 
1270                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1271                         continue;
1272
1273                 /* add an orco layer if needed by this modifier */
1274                 if(dm && mti->requiredDataMask) {
1275                         mask = mti->requiredDataMask(ob, md);
1276                         if(mask & CD_MASK_ORCO)
1277                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1278                 }
1279
1280                 /* How to apply modifier depends on (a) what we already have as
1281                  * a result of previous modifiers (could be a DerivedMesh or just
1282                  * deformed vertices) and (b) what type the modifier is.
1283                  */
1284
1285                 if(mti->type == eModifierTypeType_OnlyDeform) {
1286                         /* No existing verts to deform, need to build them. */
1287                         if(!deformedVerts) {
1288                                 if(dm) {
1289                                         /* Deforming a derived mesh, read the vertex locations
1290                                          * out of the mesh and deform them. Once done with this
1291                                          * run of deformers verts will be written back.
1292                                          */
1293                                         numVerts = dm->getNumVerts(dm);
1294                                         deformedVerts =
1295                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1296                                         dm->getVertCos(dm, deformedVerts);
1297                                 } else {
1298                                         deformedVerts = editbmesh_getVertexCos(em, &numVerts);
1299                                 }
1300                         }
1301
1302                         if (mti->deformVertsEM)
1303                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1304                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1305                 } else {
1306                         DerivedMesh *ndm;
1307
1308                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1309                         if(dm) {
1310                                 if(deformedVerts) {
1311                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1312                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1313                                         dm = tdm;
1314
1315                                         CDDM_apply_vert_coords(dm, deformedVerts);
1316                                         CDDM_calc_normals(dm);
1317                                 } else if(cage_r && dm == *cage_r) {
1318                                         /* dm may be changed by this modifier, so we need to copy it
1319                                          */
1320                                         dm = CDDM_copy(dm, 0);
1321                                 }
1322
1323                         } else {
1324                                 dm = CDDM_from_BMEditMesh(em, ob->data);
1325
1326                                 if(deformedVerts) {
1327                                         CDDM_apply_vert_coords(dm, deformedVerts);
1328                                         CDDM_calc_normals(dm);
1329                                 }
1330                         }
1331
1332                         /* create an orco derivedmesh in parallel */
1333                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1334                         if(mask & CD_MASK_ORCO) {
1335                                 if(!orcodm)
1336                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1337
1338                                 mask &= ~CD_MASK_ORCO;
1339                                 DM_set_only_copy(orcodm, mask);
1340
1341                                 if (mti->applyModifierEM)
1342                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1343                                 else
1344                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1345
1346                                 if(ndm) {
1347                                         /* if the modifier returned a new dm, release the old one */
1348                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1349                                         orcodm = ndm;
1350                                 }
1351                         }
1352
1353                         /* set the DerivedMesh to only copy needed data */
1354                         DM_set_only_copy(dm, (CustomDataMask)GET_INT_FROM_POINTER(curr->link));
1355
1356                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1357                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1358                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1359                         
1360                         if (mti->applyModifierEM)
1361                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1362                         else
1363                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1364
1365                         if (ndm) {
1366                                 if(dm && dm != ndm)
1367                                         dm->release(dm);
1368
1369                                 dm = ndm;
1370
1371                                 if (deformedVerts) {
1372                                         MEM_freeN(deformedVerts);
1373                                         deformedVerts = NULL;
1374                                 }
1375                         }
1376                 }
1377
1378                 if(cage_r && i == cageIndex) {
1379                         if(dm && deformedVerts) {
1380                                 *cage_r = CDDM_copy(dm, 0);
1381                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1382                         } else if(dm) {
1383                                 *cage_r = dm;
1384                         } else {
1385                                 *cage_r =
1386                                         getEditDerivedBMesh(em, ob,
1387                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1388                         }
1389                 }
1390         }
1391
1392         BLI_linklist_free(datamasks, NULL);
1393
1394         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1395          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1396          * then we need to build one.
1397          */
1398         if(dm && deformedVerts) {
1399                 *final_r = CDDM_copy(dm, 0);
1400
1401                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1402
1403                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1404                 CDDM_calc_normals(*final_r);
1405         } else if (dm) {
1406                 *final_r = dm;
1407         } else if (!deformedVerts && cage_r && *cage_r) {
1408                 *final_r = *cage_r;
1409         } else {
1410                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1411                 deformedVerts = NULL;
1412         }
1413
1414         /* add an orco layer if needed */
1415         if(dataMask & CD_MASK_ORCO)
1416                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1417
1418         if(orcodm)
1419                 orcodm->release(orcodm);
1420
1421         if(deformedVerts)
1422                 MEM_freeN(deformedVerts);
1423 }
1424
1425 static void clear_mesh_caches(Object *ob)
1426 {
1427         Mesh *me= ob->data;
1428
1429                 /* also serves as signal to remake texspace */
1430         if (ob->bb) {
1431                 MEM_freeN(ob->bb);
1432                 ob->bb = NULL;
1433         }
1434         if (me->bb) {
1435                 MEM_freeN(me->bb);
1436                 me->bb = NULL;
1437         }
1438
1439         freedisplist(&ob->disp);
1440
1441         if (ob->derivedFinal) {
1442                 ob->derivedFinal->needsFree = 1;
1443                 ob->derivedFinal->release(ob->derivedFinal);
1444                 ob->derivedFinal= NULL;
1445         }
1446         if (ob->derivedDeform) {
1447                 ob->derivedDeform->needsFree = 1;
1448                 ob->derivedDeform->release(ob->derivedDeform);
1449                 ob->derivedDeform= NULL;
1450         }
1451         /* we free pbvh on changes, except during sculpt since it can't deal with
1452            changing PVBH node organization, we hope topology does not change in
1453            the meantime .. weak */
1454         if(ob->sculpt && ob->sculpt->pbvh) {
1455                 if(!ob->sculpt->cache) {
1456                         BLI_pbvh_free(ob->sculpt->pbvh);
1457                         ob->sculpt->pbvh= NULL;
1458                 }
1459         }
1460 }
1461
1462 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
1463 {
1464         Object *obact = scene->basact?scene->basact->object:NULL;
1465         int editing = paint_facesel_test(ob);
1466         /* weight paint and face select need original indicies because of selection buffer drawing */
1467         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)) || editing);
1468
1469         clear_mesh_caches(ob);
1470
1471         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1472                                                 &ob->derivedFinal, 0, 1,
1473                                                 needMapping, dataMask, -1, 1);
1474
1475         DM_set_object_boundbox (ob, ob->derivedFinal);
1476
1477         ob->derivedFinal->needsFree = 0;
1478         ob->derivedDeform->needsFree = 0;
1479         ob->lastDataMask = dataMask;
1480 }
1481
1482 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1483 {
1484         clear_mesh_caches(obedit);
1485
1486         if (em->derivedFinal) {
1487                 if (em->derivedFinal!=em->derivedCage) {
1488                         em->derivedFinal->needsFree = 1;
1489                         em->derivedFinal->release(em->derivedFinal);
1490                 }
1491                 em->derivedFinal = NULL;
1492         }
1493         if (em->derivedCage) {
1494                 em->derivedCage->needsFree = 1;
1495                 em->derivedCage->release(em->derivedCage);
1496                 em->derivedCage = NULL;
1497         }
1498
1499         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1500         DM_set_object_boundbox (obedit, em->derivedFinal);
1501
1502         em->lastDataMask = dataMask;
1503         em->derivedFinal->needsFree = 0;
1504         em->derivedCage->needsFree = 0;
1505 }
1506
1507 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em, CustomDataMask dataMask)
1508 {
1509         if (em) {
1510                 editbmesh_build_data(scene, ob, em, dataMask);
1511         } else {
1512                 mesh_build_data(scene, ob, dataMask);
1513         }
1514 }
1515
1516 /***/
1517
1518 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
1519 {
1520         /* if there's no derived mesh or the last data mask used doesn't include
1521          * the data we need, rebuild the derived mesh
1522          */
1523         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
1524                 mesh_build_data(scene, ob, dataMask);
1525
1526         return ob->derivedFinal;
1527 }
1528
1529 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
1530 {
1531         /* if there's no derived mesh or the last data mask used doesn't include
1532          * the data we need, rebuild the derived mesh
1533          */
1534         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
1535                 mesh_build_data(scene, ob, dataMask);
1536
1537         return ob->derivedDeform;
1538 }
1539
1540 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
1541 {
1542         DerivedMesh *final;
1543         
1544         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
1545
1546         return final;
1547 }
1548
1549 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
1550 {
1551         DerivedMesh *final;
1552         
1553         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
1554
1555         return final;
1556 }
1557
1558 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
1559 {
1560         DerivedMesh *final;
1561
1562         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
1563
1564         return final;
1565 }
1566
1567 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
1568                                                                                    CustomDataMask dataMask)
1569 {
1570         DerivedMesh *final;
1571         
1572         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
1573
1574         return final;
1575 }
1576
1577 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
1578                                                                                         CustomDataMask dataMask)
1579 {
1580         DerivedMesh *final;
1581         
1582         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
1583
1584         return final;
1585 }
1586
1587 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
1588                                                                                                   float (*vertCos)[3],
1589                                                                                                   CustomDataMask dataMask)
1590 {
1591         DerivedMesh *final;
1592
1593         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
1594
1595         return final;
1596 }
1597
1598 /***/
1599
1600 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
1601                                                                                                  CustomDataMask dataMask)
1602 {
1603         /* if there's no derived mesh or the last data mask used doesn't include
1604          * the data we need, rebuild the derived mesh
1605          */
1606         if(!em->derivedCage ||
1607            (em->lastDataMask & dataMask) != dataMask)
1608                 editbmesh_build_data(scene, obedit, em, dataMask);
1609
1610         *final_r = em->derivedFinal;
1611         return em->derivedCage;
1612 }
1613
1614 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1615 {
1616         /* if there's no derived mesh or the last data mask used doesn't include
1617          * the data we need, rebuild the derived mesh
1618          */
1619         if(!em->derivedCage ||
1620            (em->lastDataMask & dataMask) != dataMask)
1621                 editbmesh_build_data(scene, obedit, em, dataMask);
1622
1623         return em->derivedCage;
1624 }
1625
1626 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
1627 {
1628         return getEditDerivedBMesh(em, obedit, NULL);
1629 }
1630
1631
1632 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
1633
1634 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
1635 {
1636         float *vec = userData;
1637         
1638         vec+= 6*index;
1639
1640         /* check if we've been here before (normal should not be 0) */
1641         if(vec[3] || vec[4] || vec[5]) return;
1642
1643         VECCOPY(vec, co);
1644         vec+= 3;
1645         if(no_f) {
1646                 VECCOPY(vec, no_f);
1647         }
1648         else {
1649                 VECCOPY(vec, no_s);
1650         }
1651 }
1652
1653 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
1654 /* this is needed for all code using vertexgroups (no subsurf support) */
1655 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
1656 /* in use now by vertex/weight paint and particle generating */
1657
1658 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
1659 {
1660         Mesh *me= ob->data;
1661         DerivedMesh *dm;
1662         float *vertexcosnos;
1663         
1664         /* lets prevent crashing... */
1665         if(ob->type!=OB_MESH || me->totvert==0)
1666                 return NULL;
1667         
1668         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1669         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
1670         
1671         if(dm->foreachMappedVert) {
1672                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
1673         }
1674         else {
1675                 float *fp= vertexcosnos;
1676                 int a;
1677                 
1678                 for(a=0; a< me->totvert; a++, fp+=6) {
1679                         dm->getVertCo(dm, a, fp);
1680                         dm->getVertNo(dm, a, fp+3);
1681                 }
1682         }
1683         
1684         dm->release(dm);
1685         return vertexcosnos;
1686 }
1687
1688 /* ********* crazyspace *************** */
1689
1690 int editbmesh_get_first_deform_matrices(Scene *scene, Object *ob, BMEditMesh *em, float (**deformmats)[3][3], float (**deformcos)[3])
1691 {
1692         ModifierData *md;
1693         DerivedMesh *dm;
1694         int i, a, numleft = 0, numVerts = 0;
1695         int cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1696         float (*defmats)[3][3] = NULL, (*deformedVerts)[3] = NULL;
1697
1698         modifiers_clearErrors(ob);
1699
1700         dm = NULL;
1701         md = modifiers_getVirtualModifierList(ob);
1702
1703         /* compute the deformation matrices and coordinates for the first
1704            modifiers with on cage editing that are enabled and support computing
1705            deform matrices */
1706         for(i = 0; md && i <= cageIndex; i++, md = md->next) {
1707                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1708
1709                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1710                         continue;
1711
1712                 if(mti->type==eModifierTypeType_OnlyDeform && mti->deformMatricesEM) {
1713                         if(!defmats) {
1714                                 dm= getEditDerivedBMesh(em, ob, NULL);
1715                                 deformedVerts= editbmesh_getVertexCos(em, &numVerts);
1716                                 defmats= MEM_callocN(sizeof(*defmats)*numVerts, "defmats");
1717
1718                                 for(a=0; a<numVerts; a++)
1719                                         unit_m3(defmats[a]);
1720                         }
1721
1722                         mti->deformMatricesEM(md, ob, em, dm, deformedVerts, defmats,
1723                                 numVerts);
1724                 }
1725                 else
1726                         break;
1727         }
1728
1729         for(; md && i <= cageIndex; md = md->next, i++)
1730                 if(editbmesh_modifier_is_enabled(scene, md, dm) && modifier_isCorrectableDeformed(md))
1731                         numleft++;
1732
1733         if(dm)
1734                 dm->release(dm);
1735         
1736         *deformmats= defmats;
1737         *deformcos= deformedVerts;
1738
1739         return numleft;
1740 }
1741
1742 /* ******************* GLSL ******************** */
1743
1744 void DM_add_tangent_layer(DerivedMesh *dm)
1745 {
1746         /* mesh vars */
1747         MTFace *mtface, *tf;
1748         MFace *mface, *mf;
1749         MVert *mvert, *v1, *v2, *v3, *v4;
1750         MemArena *arena= NULL;
1751         VertexTangent **vtangents= NULL;
1752         float (*orco)[3]= NULL, (*tangent)[3];
1753         float *uv1, *uv2, *uv3, *uv4, *vtang;
1754         float fno[3], tang[3], uv[4][2];
1755         int i, j, len, mf_vi[4], totvert, totface;
1756
1757         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
1758                 return;
1759
1760         /* check we have all the needed layers */
1761         totvert= dm->getNumVerts(dm);
1762         totface= dm->getNumTessFaces(dm);
1763
1764         mvert= dm->getVertArray(dm);
1765         mface= dm->getTessFaceArray(dm);
1766         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
1767
1768         if(!mtface) {
1769                 orco= dm->getVertDataArray(dm, CD_ORCO);
1770                 if(!orco)
1771                         return;
1772         }
1773         
1774         /* create tangent layer */
1775         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
1776         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
1777         
1778         /* allocate some space */
1779         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
1780         BLI_memarena_use_calloc(arena);
1781         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
1782         
1783         /* sum tangents at connected vertices */
1784         for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
1785                 v1= &mvert[mf->v1];
1786                 v2= &mvert[mf->v2];
1787                 v3= &mvert[mf->v3];
1788
1789                 if (mf->v4) {
1790                         v4= &mvert[mf->v4];
1791                         normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
1792                 }
1793                 else {
1794                         v4= NULL;
1795                         normal_tri_v3( fno,v3->co, v2->co, v1->co);
1796                 }
1797                 
1798                 if(mtface) {
1799                         uv1= tf->uv[0];
1800                         uv2= tf->uv[1];
1801                         uv3= tf->uv[2];
1802                         uv4= tf->uv[3];
1803                 }
1804                 else {
1805                         uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
1806                         map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
1807                         map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
1808                         map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
1809                         if(v4)
1810                                 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
1811                 }
1812                 
1813                 tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
1814                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
1815                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
1816                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
1817                 
1818                 if(mf->v4) {
1819                         v4= &mvert[mf->v4];
1820                         
1821                         tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
1822                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
1823                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
1824                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
1825                 }
1826         }
1827         
1828         /* write tangent to layer */
1829         for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
1830                 len= (mf->v4)? 4 : 3; 
1831                 
1832                 if(mtface) {
1833                         uv1= tf->uv[0];
1834                         uv2= tf->uv[1];
1835                         uv3= tf->uv[2];
1836                         uv4= tf->uv[3];
1837                 }
1838                 else {
1839                         uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
1840                         map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
1841                         map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
1842                         map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
1843                         if(len==4)
1844                                 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
1845                 }
1846                 
1847                 mf_vi[0]= mf->v1;
1848                 mf_vi[1]= mf->v2;
1849                 mf_vi[2]= mf->v3;
1850                 mf_vi[3]= mf->v4;
1851                 
1852                 for(j=0; j<len; j++) {
1853                         vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
1854                         normalize_v3_v3(tangent[j], vtang);
1855                 }
1856         }
1857         
1858         BLI_memarena_free(arena);
1859         MEM_freeN(vtangents);
1860 }
1861
1862 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
1863 {
1864         CustomData *vdata, *fdata, *tfdata = NULL;
1865         int a, b, layer;
1866
1867         /* From the layers requested by the GLSL shader, figure out which ones are
1868          * actually available for this derivedmesh, and retrieve the pointers */
1869
1870         memset(attribs, 0, sizeof(DMVertexAttribs));
1871
1872         vdata = &dm->vertData;
1873         fdata = tfdata = dm->getTessFaceDataLayout(dm);
1874         
1875         /* add a tangent layer if necessary */
1876         for(b = 0; b < gattribs->totlayer; b++)
1877                 if(gattribs->layer[b].type == CD_TANGENT)
1878                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
1879                                 DM_add_tangent_layer(dm);
1880
1881         for(b = 0; b < gattribs->totlayer; b++) {
1882                 if(gattribs->layer[b].type == CD_MTFACE) {
1883                         /* uv coordinates */
1884                         if(gattribs->layer[b].name[0])
1885                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
1886                                         gattribs->layer[b].name);
1887                         else
1888                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
1889
1890                         if(layer != -1) {
1891                                 a = attribs->tottface++;
1892
1893                                 attribs->tface[a].array = tfdata->layers[layer].data;
1894                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
1895                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
1896                         }
1897                 }
1898                 else if(gattribs->layer[b].type == CD_MCOL) {
1899                         /* vertex colors */
1900                         if(gattribs->layer[b].name[0])
1901                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
1902                                         gattribs->layer[b].name);
1903                         else
1904                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
1905
1906                         if(layer != -1) {
1907                                 a = attribs->totmcol++;
1908
1909                                 attribs->mcol[a].array = tfdata->layers[layer].data;
1910                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
1911                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
1912                         }
1913                 }
1914                 else if(gattribs->layer[b].type == CD_TANGENT) {
1915                         /* tangents */
1916                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
1917
1918                         if(layer != -1) {
1919                                 attribs->tottang = 1;
1920
1921                                 attribs->tang.array = fdata->layers[layer].data;
1922                                 attribs->tang.emOffset = fdata->layers[layer].offset;
1923                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
1924                         }
1925                 }
1926                 else if(gattribs->layer[b].type == CD_ORCO) {
1927                         /* original coordinates */
1928                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
1929
1930                         if(layer != -1) {
1931                                 attribs->totorco = 1;
1932
1933                                 attribs->orco.array = vdata->layers[layer].data;
1934                                 attribs->orco.emOffset = vdata->layers[layer].offset;
1935                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
1936                         }
1937                 }
1938         }
1939 }
1940
1941 /* Set object's bounding box based on DerivedMesh min/max data */
1942 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
1943 {
1944         float min[3], max[3];
1945
1946         INIT_MINMAX(min, max);
1947
1948         dm->getMinMax(dm, min, max);
1949
1950         if(!ob->bb)
1951                 ob->bb= MEM_callocN(sizeof(BoundBox), "bb");
1952
1953         boundbox_set_from_min_max(ob->bb, min, max);
1954 }