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