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