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