part 1 of cleaning up my little array macro library to be a formal API. also removed...
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2005 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <string.h>
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35
36 #include "PIL_time.h"
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_effect_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_key_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_object_force.h"
47 #include "DNA_object_fluidsim.h" // N_T
48 #include "DNA_scene_types.h" // N_T
49 #include "DNA_texture_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_space_types.h"
53 #include "DNA_particle_types.h"
54
55 #include "BLI_arithb.h"
56 #include "BLI_blenlib.h"
57 #include "BLI_edgehash.h"
58 #include "BLI_editVert.h"
59 #include "BLI_linklist.h"
60 #include "BLI_memarena.h"
61 #include "BLI_array.h"
62
63 #include "BKE_cdderivedmesh.h"
64 #include "BKE_customdata.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_deform.h"
67 #include "BKE_displist.h"
68 #include "BKE_effect.h"
69 #include "BKE_fluidsim.h"
70 #include "BKE_global.h"
71 #include "BKE_key.h"
72 #include "BKE_material.h"
73 #include "BKE_modifier.h"
74 #include "BKE_mesh.h"
75 #include "BKE_object.h"
76 #include "BKE_paint.h"
77 #include "BKE_subsurf.h"
78 #include "BKE_texture.h"
79 #include "BKE_utildefines.h"
80 #include "BKE_particle.h"
81 #include "BKE_tessmesh.h"
82 #include "BKE_bvhutils.h"
83
84 #include "BLO_sys_types.h" // for intptr_t support
85
86 #include "BIF_gl.h"
87 #include "BIF_glutil.h"
88
89 #include "GPU_draw.h"
90 #include "GPU_extensions.h"
91 #include "GPU_material.h"
92
93 ///////////////////////////////////
94 ///////////////////////////////////
95
96 static MVert *dm_getVertArray(DerivedMesh *dm)
97 {
98         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
99
100         if (!mvert) {
101                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
102                         dm->getNumVerts(dm));
103                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
104                 dm->copyVertArray(dm, mvert);
105         }
106
107         return mvert;
108 }
109
110 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
111 {
112         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
113
114         if (!medge) {
115                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
116                         dm->getNumEdges(dm));
117                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
118                 dm->copyEdgeArray(dm, medge);
119         }
120
121         return medge;
122 }
123
124 static MFace *dm_getFaceArray(DerivedMesh *dm)
125 {
126         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
127
128         if (!mface) {
129                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
130                         dm->getNumTessFaces(dm));
131                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
132                 dm->copyTessFaceArray(dm, mface);
133         }
134
135         return mface;
136 }
137
138 static MVert *dm_dupVertArray(DerivedMesh *dm)
139 {
140         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
141                                  "dm_dupVertArray tmp");
142
143         if(tmp) dm->copyVertArray(dm, tmp);
144
145         return tmp;
146 }
147
148 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
149 {
150         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
151                                  "dm_dupEdgeArray tmp");
152
153         if(tmp) dm->copyEdgeArray(dm, tmp);
154
155         return tmp;
156 }
157
158 static MFace *dm_dupFaceArray(DerivedMesh *dm)
159 {
160         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
161                                  "dm_dupFaceArray tmp");
162
163         if(tmp) dm->copyTessFaceArray(dm, tmp);
164
165         return tmp;
166 }
167
168 CustomData *dm_getVertCData(DerivedMesh *dm)
169 {
170         return &dm->vertData;
171 }
172
173 CustomData *dm_getEdgeCData(DerivedMesh *dm)
174 {
175         return &dm->edgeData;
176 }
177
178 CustomData *dm_getFaceCData(DerivedMesh *dm)
179 {
180         return &dm->faceData;
181 }
182
183 CustomData *dm_getLoopCData(DerivedMesh *dm)
184 {
185         return &dm->loopData;
186 }
187
188 CustomData *dm_getPolyCData(DerivedMesh *dm)
189 {
190         return &dm->polyData;
191 }
192
193 void DM_init_funcs(DerivedMesh *dm)
194 {
195         /* default function implementations */
196         dm->getVertArray = dm_getVertArray;
197         dm->getEdgeArray = dm_getEdgeArray;
198         dm->getTessFaceArray = dm_getFaceArray;
199         dm->dupVertArray = dm_dupVertArray;
200         dm->dupEdgeArray = dm_dupEdgeArray;
201         dm->dupTessFaceArray = dm_dupFaceArray;
202
203         dm->getVertDataLayout = dm_getVertCData;
204         dm->getEdgeDataLayout = dm_getEdgeCData;
205         dm->getTessFaceDataLayout = dm_getFaceCData;
206         dm->getLoopDataLayout = dm_getLoopCData;
207         dm->getFaceDataLayout = dm_getPolyCData;
208
209         dm->getVertData = DM_get_vert_data;
210         dm->getEdgeData = DM_get_edge_data;
211         dm->getTessFaceData = DM_get_face_data;
212         dm->getVertDataArray = DM_get_vert_data_layer;
213         dm->getEdgeDataArray = DM_get_edge_data_layer;
214         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
215
216         bvhcache_init(&dm->bvhCache);
217 }
218
219 void DM_init(DerivedMesh *dm, int numVerts, int numEdges, int numFaces,
220              int numLoops, int numPoly)
221 {
222         dm->numVertData = numVerts;
223         dm->numEdgeData = numEdges;
224         dm->numFaceData = numFaces;
225         dm->numLoopData = numLoops;
226         dm->numPolyData = numPoly;
227
228         DM_init_funcs(dm);
229         
230         dm->needsFree = 1;
231 }
232
233 void DM_from_template(DerivedMesh *dm, DerivedMesh *source,
234                       int numVerts, int numEdges, int numFaces,
235                       int numLoops, int numPolys)
236 {
237         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
238                         CD_CALLOC, numVerts);
239         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
240                         CD_CALLOC, numEdges);
241         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
242                         CD_CALLOC, numFaces);
243         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
244                         CD_CALLOC, numLoops);
245         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
246                         CD_CALLOC, numPolys);
247
248         dm->numVertData = numVerts;
249         dm->numEdgeData = numEdges;
250         dm->numFaceData = numFaces;
251         dm->numLoopData = numLoops;
252         dm->numPolyData = numPolys;
253
254         DM_init_funcs(dm);
255
256         dm->needsFree = 1;
257 }
258
259 int DM_release(DerivedMesh *dm)
260 {
261         if (dm->needsFree) {
262                 bvhcache_free(&dm->bvhCache);
263
264                 CustomData_free(&dm->vertData, dm->numVertData);
265                 CustomData_free(&dm->edgeData, dm->numEdgeData);
266                 CustomData_free(&dm->faceData, dm->numFaceData);
267                 CustomData_free(&dm->loopData, dm->numLoopData);
268                 CustomData_free(&dm->polyData, dm->numPolyData);
269
270                 return 1;
271         }
272         else {
273                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
274                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
275                 CustomData_free_temporary(&dm->faceData, dm->numFaceData);
276                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
277                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
278
279                 return 0;
280         }
281 }
282
283 void dm_add_polys_from_iter(CustomData *ldata, CustomData *pdata, DerivedMesh *dm, int totloop)
284 {
285         DMFaceIter *iter = dm->newFaceIter(dm);
286         DMLoopIter *liter;
287         CustomData *oldata, *opdata;
288         MPoly *mpoly;
289         MLoop *mloop;
290         int p, l, i, j, lasttype;
291
292         oldata = dm->getLoopDataLayout(dm);
293         opdata = dm->getFaceDataLayout(dm);
294
295         CustomData_copy(oldata, ldata, CD_MASK_DERIVEDMESH, CD_CALLOC, totloop);
296         CustomData_copy(opdata, pdata, CD_MASK_DERIVEDMESH, CD_CALLOC, dm->getNumFaces(dm));
297
298         mloop = MEM_callocN(sizeof(MLoop)*totloop, "MLoop from dm_add_polys_from_iter");
299         CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop);
300         mpoly = MEM_callocN(sizeof(MPoly)*dm->getNumFaces(dm), "MPoly from dm_add_polys_from_iter");
301         CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, dm->getNumFaces(dm));
302
303         l = 0;
304         for (p=0; !iter->done; iter->step(iter), mpoly++, p++) {
305                 mpoly->flag = iter->flags;
306                 mpoly->loopstart = l;
307                 mpoly->totloop = iter->len;
308                 mpoly->mat_nr = iter->mat_nr;
309                 
310                 j = 0;
311                 lasttype = -1;
312                 for (i=0; i<opdata->totlayer; i++) {
313                         void *e1, *e2;
314
315                         if (opdata->layers[i].type == lasttype)
316                                 j++;
317                         else
318                                 j = 0;
319
320                         if (opdata->layers[i].type == CD_MPOLY)
321                                 continue;
322                         
323                         e1 = iter->getCDData(iter, opdata->layers[i].type, j);
324                         e2 = (char*)CustomData_get_n(pdata, opdata->layers[i].type, p, j);
325                         
326                         if (!e2)
327                                 continue;
328
329                         CustomData_copy_elements(opdata->layers[i].type, e1, e2, 1);
330                         
331                         lasttype = opdata->layers[i].type;                              
332                 }
333
334                 liter = iter->getLoopsIter(iter);
335                 for (; !liter->done; liter->step(liter), mloop++, l++) {
336                         mloop->v = liter->vindex;
337                         mloop->e = liter->eindex;
338
339                         j = 0;
340                         lasttype = -1;
341                         for (i=0; i<oldata->totlayer; i++) {
342                                 void *e1, *e2;
343
344                                 if (oldata->layers[i].type == CD_MLOOP)
345                                         continue;
346                                 
347                                 if (oldata->layers[i].type == lasttype)
348                                         j++;
349                                 else
350                                         j = 0;
351
352                                 e1 = liter->getLoopCDData(liter, oldata->layers[i].type, j);
353                                 e2 = CustomData_get_n(ldata, oldata->layers[i].type, l, j);
354                                 
355                                 if (!e2)
356                                         continue;
357
358                                 CustomData_copy_elements(oldata->layers[i].type, e1, e2, 1);
359                                 lasttype = oldata->layers[i].type;                              
360                         }
361                 }
362         }
363         iter->free(iter);
364 }
365
366 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
367 {
368         DMFaceIter *iter = source->newFaceIter(source);
369         DMLoopIter *liter;
370         int totloop = source->numLoopData;
371
372         dm_add_polys_from_iter(&target->loopData, &target->polyData, source, totloop);
373
374         target->numLoopData = totloop;
375         target->numPolyData = source->getNumFaces(source);
376 }
377
378 void DM_to_mesh(DerivedMesh *dm, Mesh *me)
379 {
380         /* dm might depend on me, so we need to do everything with a local copy */
381         Mesh tmp = *me;
382         DMFaceIter *iter;
383         int totvert, totedge, totface, totloop, totpoly;
384
385         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
386         memset(&tmp.edata, 0, sizeof(tmp.edata));
387         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
388         memset(&tmp.ldata, 0, sizeof(tmp.ldata));
389         memset(&tmp.pdata, 0, sizeof(tmp.pdata));
390
391         totvert = tmp.totvert = dm->getNumVerts(dm);
392         totedge = tmp.totedge = dm->getNumEdges(dm);
393         totface = tmp.totface = dm->getNumTessFaces(dm);
394         totpoly = tmp.totpoly = dm->getNumFaces(dm);
395         
396         totloop = 0;
397         for (iter=dm->newFaceIter(dm); !iter->done; iter->step(iter)) {
398                 totloop += iter->len;
399         }
400         iter->free(iter);
401         
402         tmp.totloop = totloop;
403
404         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
405         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
406         CustomData_copy(&dm->faceData, &tmp.fdata, CD_MASK_MESH, CD_DUPLICATE, totface);
407         CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
408         CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
409
410         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
411            we set them here in case they are missing */
412         if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
413                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
414         if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
415                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
416         if(!CustomData_has_layer(&tmp.fdata, CD_MFACE))
417                 CustomData_add_layer(&tmp.fdata, CD_MFACE, CD_ASSIGN, dm->dupTessFaceArray(dm), totface);
418         if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY))
419                 dm_add_polys_from_iter(&tmp.ldata, &tmp.pdata, dm, totloop);
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         /* if the number of verts has changed, remove invalid data */
430         if(tmp.totvert != me->totvert) {
431                 if(me->key) me->key->id.us--;
432                 me->key = NULL;
433         }
434
435         *me = tmp;
436 }
437
438 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
439 {
440         CustomData_set_only_copy(&dm->vertData, mask);
441         CustomData_set_only_copy(&dm->edgeData, mask);
442         CustomData_set_only_copy(&dm->faceData, mask);
443 }
444
445 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
446 {
447         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
448 }
449
450 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
451 {
452         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
453 }
454
455 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
456 {
457         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numFaceData);
458 }
459
460 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
461 {
462         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
463 }
464
465 void DM_add_face_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
466 {
467         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
468 }
469
470 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
471 {
472         return CustomData_get(&dm->vertData, index, type);
473 }
474
475 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
476 {
477         return CustomData_get(&dm->edgeData, index, type);
478 }
479
480 void *DM_get_face_data(DerivedMesh *dm, int index, int type)
481 {
482         return CustomData_get(&dm->faceData, index, type);
483 }
484
485 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
486 {
487         return CustomData_get_layer(&dm->vertData, type);
488 }
489
490 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
491 {
492         return CustomData_get_layer(&dm->edgeData, type);
493 }
494
495 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
496 {
497         return CustomData_get_layer(&dm->faceData, type);
498 }
499
500 void *DM_get_face_data_layer(DerivedMesh *dm, int type)
501 {
502         return CustomData_get_layer(&dm->polyData, type);
503 }
504
505 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
506 {
507         CustomData_set(&dm->vertData, index, type, data);
508 }
509
510 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
511 {
512         CustomData_set(&dm->edgeData, index, type, data);
513 }
514
515 void DM_set_face_data(DerivedMesh *dm, int index, int type, void *data)
516 {
517         CustomData_set(&dm->faceData, index, type, data);
518 }
519
520 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
521                        int source_index, int dest_index, int count)
522 {
523         CustomData_copy_data(&source->vertData, &dest->vertData,
524                              source_index, dest_index, count);
525 }
526
527 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
528                        int source_index, int dest_index, int count)
529 {
530         CustomData_copy_data(&source->edgeData, &dest->edgeData,
531                              source_index, dest_index, count);
532 }
533
534 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
535                        int source_index, int dest_index, int count)
536 {
537         CustomData_copy_data(&source->faceData, &dest->faceData,
538                              source_index, dest_index, count);
539 }
540
541 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
542                        int source_index, int dest_index, int count)
543 {
544         CustomData_copy_data(&source->loopData, &dest->loopData,
545                              source_index, dest_index, count);
546 }
547
548 void DM_copy_face_data(DerivedMesh *source, DerivedMesh *dest,
549                        int source_index, int dest_index, int count)
550 {
551         CustomData_copy_data(&source->polyData, &dest->polyData,
552                              source_index, dest_index, count);
553 }
554
555 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
556 {
557         CustomData_free_elem(&dm->vertData, index, count);
558 }
559
560 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
561 {
562         CustomData_free_elem(&dm->edgeData, index, count);
563 }
564
565 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
566 {
567         CustomData_free_elem(&dm->faceData, index, count);
568 }
569
570 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
571 {
572         CustomData_free_elem(&dm->loopData, index, count);
573 }
574
575 void DM_free_face_data(struct DerivedMesh *dm, int index, int count)
576 {
577         CustomData_free_elem(&dm->polyData, index, count);
578 }
579
580 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
581                          int *src_indices, float *weights,
582                          int count, int dest_index)
583 {
584         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
585                           weights, NULL, count, dest_index);
586 }
587
588 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
589                          int *src_indices,
590                          float *weights, EdgeVertWeight *vert_weights,
591                          int count, int dest_index)
592 {
593         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
594                           weights, (float*)vert_weights, count, dest_index);
595 }
596
597 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
598                          int *src_indices,
599                          float *weights, FaceVertWeight *vert_weights,
600                          int count, int dest_index)
601 {
602         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
603                           weights, (float*)vert_weights, count, dest_index);
604 }
605
606
607 void DM_swap_tessface_data(DerivedMesh *dm, int index, int *corner_indices)
608 {
609         CustomData_swap(&dm->faceData, index, corner_indices);
610 }
611
612 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
613                          int *src_indices,
614                          float *weights, int count, int dest_index)
615 {
616         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
617                           weights, NULL, count, dest_index);
618 }
619
620 void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
621                          int *src_indices,
622                          float *weights, int count, int dest_index)
623 {
624         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
625                           weights, NULL, count, dest_index);
626 }
627
628 ///
629 static DerivedMesh *getMeshDerivedMesh(Mesh *me, Object *ob, float (*vertCos)[3])
630 {
631         DerivedMesh *dm = CDDM_from_mesh(me, ob);
632         
633         if(!dm)
634                 return NULL;
635         
636         if (vertCos)
637                 CDDM_apply_vert_coords(dm, vertCos);
638
639         CDDM_calc_normals(dm);
640
641         return dm;
642 }
643
644 ///
645
646 typedef struct {
647         DerivedMesh dm;
648
649         EditMesh *em;
650         float (*vertexCos)[3];
651         float (*vertexNos)[3];
652         float (*faceNos)[3];
653 } EditMeshDerivedMesh;
654
655 static void emDM_foreachMappedVert(void *dm, void (*func)(void *userData, int index, float *co, float *no_f, short *no_s), void *userData)
656 {
657         EditMeshDerivedMesh *emdm= dm;
658         EditVert *eve;
659         int i;
660
661         for (i=0,eve= emdm->em->verts.first; eve; i++,eve=eve->next) {
662                 if (emdm->vertexCos) {
663                         func(userData, i, emdm->vertexCos[i], emdm->vertexNos[i], NULL);
664                 } else {
665                         func(userData, i, eve->co, eve->no, NULL);
666                 }
667         }
668 }
669 static void emDM_foreachMappedEdge(void *dm, void (*func)(void *userData, int index, float *v0co, float *v1co), void *userData)
670 {
671         EditMeshDerivedMesh *emdm= dm;
672         EditEdge *eed;
673         int i;
674
675         if (emdm->vertexCos) {
676                 EditVert *eve;
677
678                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
679                         eve->tmp.l = (intptr_t) i++;
680                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
681                         func(userData, i, emdm->vertexCos[(int) eed->v1->tmp.l], emdm->vertexCos[(int) eed->v2->tmp.l]);
682         } else {
683                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
684                         func(userData, i, eed->v1->co, eed->v2->co);
685         }
686 }
687 static void emDM_drawMappedEdges(void *dm, int (*setDrawOptions)(void *userData, int index), void *userData) 
688 {
689         EditMeshDerivedMesh *emdm= dm;
690         EditEdge *eed;
691         int i;
692
693         if (emdm->vertexCos) {
694                 EditVert *eve;
695
696                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
697                         eve->tmp.l = (intptr_t) i++;
698
699                 glBegin(GL_LINES);
700                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
701                         if(!setDrawOptions || setDrawOptions(userData, i)) {
702                                 glVertex3fv(emdm->vertexCos[(int) eed->v1->tmp.l]);
703                                 glVertex3fv(emdm->vertexCos[(int) eed->v2->tmp.l]);
704                         }
705                 }
706                 glEnd();
707         } else {
708                 glBegin(GL_LINES);
709                 for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
710                         if(!setDrawOptions || setDrawOptions(userData, i)) {
711                                 glVertex3fv(eed->v1->co);
712                                 glVertex3fv(eed->v2->co);
713                         }
714                 }
715                 glEnd();
716         }
717 }
718 static void emDM_drawEdges(void *dm, int drawLooseEdges)
719 {
720         emDM_drawMappedEdges(dm, NULL, NULL);
721 }
722 static void emDM_drawMappedEdgesInterp(void *dm, int (*setDrawOptions)(void *userData, int index), void (*setDrawInterpOptions)(void *userData, int index, float t), void *userData) 
723 {
724         EditMeshDerivedMesh *emdm= dm;
725         EditEdge *eed;
726         int i;
727
728         if (emdm->vertexCos) {
729                 EditVert *eve;
730
731                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
732                         eve->tmp.l = (intptr_t) i++;
733
734                 glBegin(GL_LINES);
735                 for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
736                         if(!setDrawOptions || setDrawOptions(userData, i)) {
737                                 setDrawInterpOptions(userData, i, 0.0);
738                                 glVertex3fv(emdm->vertexCos[(int) eed->v1->tmp.l]);
739                                 setDrawInterpOptions(userData, i, 1.0);
740                                 glVertex3fv(emdm->vertexCos[(int) eed->v2->tmp.l]);
741                         }
742                 }
743                 glEnd();
744         } else {
745                 glBegin(GL_LINES);
746                 for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
747                         if(!setDrawOptions || setDrawOptions(userData, i)) {
748                                 setDrawInterpOptions(userData, i, 0.0);
749                                 glVertex3fv(eed->v1->co);
750                                 setDrawInterpOptions(userData, i, 1.0);
751                                 glVertex3fv(eed->v2->co);
752                         }
753                 }
754                 glEnd();
755         }
756 }
757
758 static void emDM_drawUVEdges(void *dm)
759 {
760         EditMeshDerivedMesh *emdm= dm;
761         EditFace *efa;
762         MTFace *tf;
763
764         glBegin(GL_LINES);
765         for(efa= emdm->em->faces.first; efa; efa= efa->next) {
766                 tf = CustomData_em_get(&emdm->em->fdata, efa->data, CD_MTFACE);
767
768                 if(tf && !(efa->h)) {
769                         glVertex2fv(tf->uv[0]);
770                         glVertex2fv(tf->uv[1]);
771
772                         glVertex2fv(tf->uv[1]);
773                         glVertex2fv(tf->uv[2]);
774
775                         if (!efa->v4) {
776                                 glVertex2fv(tf->uv[2]);
777                                 glVertex2fv(tf->uv[0]);
778                         } else {
779                                 glVertex2fv(tf->uv[2]);
780                                 glVertex2fv(tf->uv[3]);
781                                 glVertex2fv(tf->uv[3]);
782                                 glVertex2fv(tf->uv[0]);
783                         }
784                 }
785         }
786         glEnd();
787 }
788
789 static void emDM__calcFaceCent(EditFace *efa, float cent[3], float (*vertexCos)[3])
790 {
791         if (vertexCos) {
792                 VECCOPY(cent, vertexCos[(int) efa->v1->tmp.l]);
793                 VecAddf(cent, cent, vertexCos[(int) efa->v2->tmp.l]);
794                 VecAddf(cent, cent, vertexCos[(int) efa->v3->tmp.l]);
795                 if (efa->v4) VecAddf(cent, cent, vertexCos[(int) efa->v4->tmp.l]);
796         } else {
797                 VECCOPY(cent, efa->v1->co);
798                 VecAddf(cent, cent, efa->v2->co);
799                 VecAddf(cent, cent, efa->v3->co);
800                 if (efa->v4) VecAddf(cent, cent, efa->v4->co);
801         }
802
803         if (efa->v4) {
804                 VecMulf(cent, 0.25f);
805         } else {
806                 VecMulf(cent, 0.33333333333f);
807         }
808 }
809 static void emDM_foreachMappedFaceCenter(void *dm, void (*func)(void *userData, int index, float *co, float *no), void *userData)
810 {
811         EditMeshDerivedMesh *emdm= dm;
812         EditVert *eve;
813         EditFace *efa;
814         float cent[3];
815         int i;
816
817         if (emdm->vertexCos) {
818                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
819                         eve->tmp.l = (intptr_t) i++;
820         }
821
822         for(i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
823                 emDM__calcFaceCent(efa, cent, emdm->vertexCos);
824                 func(userData, i, cent, emdm->vertexCos?emdm->faceNos[i]:efa->n);
825         }
826 }
827 static void emDM_drawMappedFaces(void *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors)
828 {
829         EditMeshDerivedMesh *emdm= dm;
830         EditFace *efa;
831         int i, draw;
832
833         if (emdm->vertexCos) {
834                 EditVert *eve;
835
836                 for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
837                         eve->tmp.l = (intptr_t) i++;
838
839                 for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
840                         int drawSmooth = (efa->flag & ME_SMOOTH);
841                         draw = setDrawOptions==NULL ? 1 : setDrawOptions(userData, i, &drawSmooth);
842                         if(draw) {
843                                 if (draw==2) { /* enabled with stipple */
844                                         glEnable(GL_POLYGON_STIPPLE);
845                                         glPolygonStipple(stipple_quarttone);
846                                 }
847                                 
848                                 glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
849
850                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
851                                 if (!drawSmooth) {
852                                         glNormal3fv(emdm->faceNos[i]);
853                                         glVertex3fv(emdm->vertexCos[(int) efa->v1->tmp.l]);
854                                         glVertex3fv(emdm->vertexCos[(int) efa->v2->tmp.l]);
855                                         glVertex3fv(emdm->vertexCos[(int) efa->v3->tmp.l]);
856                                         if(efa->v4) glVertex3fv(emdm->vertexCos[(int) efa->v4->tmp.l]);
857                                 } else {
858                                         glNormal3fv(emdm->vertexNos[(int) efa->v1->tmp.l]);
859                                         glVertex3fv(emdm->vertexCos[(int) efa->v1->tmp.l]);
860                                         glNormal3fv(emdm->vertexNos[(int) efa->v2->tmp.l]);
861                                         glVertex3fv(emdm->vertexCos[(int) efa->v2->tmp.l]);
862                                         glNormal3fv(emdm->vertexNos[(int) efa->v3->tmp.l]);
863                                         glVertex3fv(emdm->vertexCos[(int) efa->v3->tmp.l]);
864                                         if(efa->v4) {
865                                                 glNormal3fv(emdm->vertexNos[(int) efa->v4->tmp.l]);
866                                                 glVertex3fv(emdm->vertexCos[(int) efa->v4->tmp.l]);
867                                         }
868                                 }
869                                 glEnd();
870                                 
871                                 if (draw==2)
872                                         glDisable(GL_POLYGON_STIPPLE);
873                         }
874                 }
875         } else {
876                 for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
877                         int drawSmooth = (efa->flag & ME_SMOOTH);
878                         draw = setDrawOptions==NULL ? 1 : setDrawOptions(userData, i, &drawSmooth);
879                         if(draw) {
880                                 if (draw==2) { /* enabled with stipple */
881                                         glEnable(GL_POLYGON_STIPPLE);
882                                         glPolygonStipple(stipple_quarttone);
883                                 }
884                                 glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
885
886                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
887                                 if (!drawSmooth) {
888                                         glNormal3fv(efa->n);
889                                         glVertex3fv(efa->v1->co);
890                                         glVertex3fv(efa->v2->co);
891                                         glVertex3fv(efa->v3->co);
892                                         if(efa->v4) glVertex3fv(efa->v4->co);
893                                 } else {
894                                         glNormal3fv(efa->v1->no);
895                                         glVertex3fv(efa->v1->co);
896                                         glNormal3fv(efa->v2->no);
897                                         glVertex3fv(efa->v2->co);
898                                         glNormal3fv(efa->v3->no);
899                                         glVertex3fv(efa->v3->co);
900                                         if(efa->v4) {
901                                                 glNormal3fv(efa->v4->no);
902                                                 glVertex3fv(efa->v4->co);
903                                         }
904                                 }
905                                 glEnd();
906                                 
907                                 if (draw==2)
908                                         glDisable(GL_POLYGON_STIPPLE);
909                         }
910                 }
911         }
912 }
913
914 static void emDM_drawFacesTex_common(void *dm,
915                int (*drawParams)(MTFace *tface, MCol *mcol, int matnr),
916                int (*drawParamsMapped)(void *userData, int index),
917                void *userData) 
918 {
919         EditMeshDerivedMesh *emdm= dm;
920         EditMesh *em= emdm->em;
921         float (*vertexCos)[3]= emdm->vertexCos;
922         float (*vertexNos)[3]= emdm->vertexNos;
923         EditFace *efa;
924         int i;
925
926         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
927         glShadeModel(GL_SMOOTH);
928         
929         if (vertexCos) {
930                 EditVert *eve;
931
932                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
933                         eve->tmp.l = (intptr_t) i++;
934
935                 for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
936                         MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
937                         MCol *mcol= CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
938                         unsigned char *cp= NULL;
939                         int drawSmooth= (efa->flag & ME_SMOOTH);
940                         int flag;
941
942                         if(drawParams)
943                                 flag= drawParams(tf, mcol, efa->mat_nr);
944                         else if(drawParamsMapped)
945                                 flag= drawParamsMapped(userData, i);
946                         else
947                                 flag= 1;
948
949                         if(flag != 0) { /* flag 0 == the face is hidden or invisible */
950                                 
951                                 /* we always want smooth here since otherwise vertex colors dont interpolate */
952                                 if (mcol) {
953                                         if (flag==1) {
954                                                 cp= (unsigned char*)mcol;
955                                         }
956                                 } else {
957                                         glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
958                                 } 
959                                 
960                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
961                                 if (!drawSmooth) {
962                                         glNormal3fv(emdm->faceNos[i]);
963
964                                         if(tf) glTexCoord2fv(tf->uv[0]);
965                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
966                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
967
968                                         if(tf) glTexCoord2fv(tf->uv[1]);
969                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
970                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
971
972                                         if(tf) glTexCoord2fv(tf->uv[2]);
973                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
974                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
975
976                                         if(efa->v4) {
977                                                 if(tf) glTexCoord2fv(tf->uv[3]);
978                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
979                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
980                                         }
981                                 } else {
982                                         if(tf) glTexCoord2fv(tf->uv[0]);
983                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
984                                         glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
985                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
986
987                                         if(tf) glTexCoord2fv(tf->uv[1]);
988                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
989                                         glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
990                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
991
992                                         if(tf) glTexCoord2fv(tf->uv[2]);
993                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
994                                         glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
995                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
996
997                                         if(efa->v4) {
998                                                 if(tf) glTexCoord2fv(tf->uv[3]);
999                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
1000                                                 glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
1001                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1002                                         }
1003                                 }
1004                                 glEnd();
1005                         }
1006                 }
1007         } else {
1008                 for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
1009                         MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1010                         MCol *mcol= CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1011                         unsigned char *cp= NULL;
1012                         int drawSmooth= (efa->flag & ME_SMOOTH);
1013                         int flag;
1014
1015                         if(drawParams)
1016                                 flag= drawParams(tf, mcol, efa->mat_nr);
1017                         else if(drawParamsMapped)
1018                                 flag= drawParamsMapped(userData, i);
1019                         else
1020                                 flag= 1;
1021
1022                         if(flag != 0) { /* flag 0 == the face is hidden or invisible */
1023                                 /* we always want smooth here since otherwise vertex colors dont interpolate */
1024                                 if (mcol) {
1025                                         if (flag==1) {
1026                                                 cp= (unsigned char*)mcol;
1027                                         }
1028                                 } else {
1029                                         glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
1030                                 } 
1031
1032                                 glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
1033                                 if (!drawSmooth) {
1034                                         glNormal3fv(efa->n);
1035
1036                                         if(tf) glTexCoord2fv(tf->uv[0]);
1037                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
1038                                         glVertex3fv(efa->v1->co);
1039
1040                                         if(tf) glTexCoord2fv(tf->uv[1]);
1041                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
1042                                         glVertex3fv(efa->v2->co);
1043
1044                                         if(tf) glTexCoord2fv(tf->uv[2]);
1045                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
1046                                         glVertex3fv(efa->v3->co);
1047
1048                                         if(efa->v4) {
1049                                                 if(tf) glTexCoord2fv(tf->uv[3]);
1050                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
1051                                                 glVertex3fv(efa->v4->co);
1052                                         }
1053                                 } else {
1054                                         if(tf) glTexCoord2fv(tf->uv[0]);
1055                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
1056                                         glNormal3fv(efa->v1->no);
1057                                         glVertex3fv(efa->v1->co);
1058
1059                                         if(tf) glTexCoord2fv(tf->uv[1]);
1060                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
1061                                         glNormal3fv(efa->v2->no);
1062                                         glVertex3fv(efa->v2->co);
1063
1064                                         if(tf) glTexCoord2fv(tf->uv[2]);
1065                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
1066                                         glNormal3fv(efa->v3->no);
1067                                         glVertex3fv(efa->v3->co);
1068
1069                                         if(efa->v4) {
1070                                                 if(tf) glTexCoord2fv(tf->uv[3]);
1071                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
1072                                                 glNormal3fv(efa->v4->no);
1073                                                 glVertex3fv(efa->v4->co);
1074                                         }
1075                                 }
1076                                 glEnd();
1077                         }
1078                 }
1079         }
1080 }
1081
1082 static void emDM_drawFacesTex(void *dm, int (*setDrawOptions)(MTFace *tface, int has_vcol, int matnr))
1083 {
1084         emDM_drawFacesTex_common(dm, setDrawOptions, NULL, NULL);
1085 }
1086
1087 static void emDM_drawMappedFacesTex(void *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
1088 {
1089         emDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
1090 }
1091
1092 static void emDM_drawMappedFacesGLSL(void *dm,
1093                int (*setMaterial)(int, void *attribs),
1094                int (*setDrawOptions)(void *userData, int index), void *userData) 
1095 {
1096         EditMeshDerivedMesh *emdm= dm;
1097         EditMesh *em= emdm->em;
1098         float (*vertexCos)[3]= emdm->vertexCos;
1099         float (*vertexNos)[3]= emdm->vertexNos;
1100         EditVert *eve;
1101         EditFace *efa;
1102         DMVertexAttribs attribs;
1103         GPUVertexAttribs gattribs;
1104         MTFace *tf;
1105         int transp, new_transp, orig_transp, tfoffset;
1106         int i, b, matnr, new_matnr, dodraw, layer;
1107
1108         dodraw = 0;
1109         matnr = -1;
1110
1111         transp = GPU_get_material_blend_mode();
1112         orig_transp = transp;
1113         layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE);
1114         tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset;
1115
1116         memset(&attribs, 0, sizeof(attribs));
1117
1118         /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
1119         glShadeModel(GL_SMOOTH);
1120
1121         for (i=0,eve=em->verts.first; eve; eve= eve->next)
1122                 eve->tmp.l = (intptr_t) i++;
1123
1124 #define PASSATTRIB(efa, eve, vert) {                                                                                    \
1125         if(attribs.totorco) {                                                                                                           \
1126                 float *orco = attribs.orco.array[eve->tmp.l];                                                   \
1127                 glVertexAttrib3fvARB(attribs.orco.glIndex, orco);                                               \
1128         }                                                                                                                                                       \
1129         for(b = 0; b < attribs.tottface; b++) {                                                                         \
1130                 MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset);  \
1131                 glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]);                  \
1132         }                                                                                                                                                       \
1133         for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1134                 MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset);                \
1135                 GLubyte col[4];                                                                                                                 \
1136                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1137                 glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1138         }                                                                                                                                                       \
1139         if(attribs.tottang) {                                                                                                           \
1140                 float *tang = attribs.tang.array[i*4 + vert];                                                   \
1141                 glVertexAttrib3fvARB(attribs.tang.glIndex, tang);                                               \
1142         }                                                                                                                                                       \
1143 }
1144
1145         for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
1146                 int drawSmooth= (efa->flag & ME_SMOOTH);
1147
1148                 if(setDrawOptions && !setDrawOptions(userData, i))
1149                         continue;
1150
1151                 new_matnr = efa->mat_nr + 1;
1152                 if(new_matnr != matnr) {
1153                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1154                         if(dodraw)
1155                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1156                 }
1157
1158                 if(tfoffset != -1) {
1159                         tf = (MTFace*)((char*)efa->data)+tfoffset;
1160                         new_transp = tf->transp;
1161
1162                         if(new_transp != transp) {
1163                                 if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
1164                                         GPU_set_material_blend_mode(orig_transp);
1165                                 else
1166                                         GPU_set_material_blend_mode(new_transp);
1167                                 transp = new_transp;
1168                         }
1169                 }
1170
1171                 if(dodraw) {
1172                         glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
1173                         if (!drawSmooth) {
1174                                 if(vertexCos) glNormal3fv(emdm->faceNos[i]);
1175                                 else glNormal3fv(efa->n);
1176
1177                                 PASSATTRIB(efa, efa->v1, 0);
1178                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1179                                 else glVertex3fv(efa->v1->co);
1180
1181                                 PASSATTRIB(efa, efa->v2, 1);
1182                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1183                                 else glVertex3fv(efa->v2->co);
1184
1185                                 PASSATTRIB(efa, efa->v3, 2);
1186                                 if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1187                                 else glVertex3fv(efa->v3->co);
1188
1189                                 if(efa->v4) {
1190                                         PASSATTRIB(efa, efa->v4, 3);
1191                                         if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1192                                         else glVertex3fv(efa->v4->co);
1193                                 }
1194                         } else {
1195                                 PASSATTRIB(efa, efa->v1, 0);
1196                                 if(vertexCos) {
1197                                         glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
1198                                         glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
1199                                 }
1200                                 else {
1201                                         glNormal3fv(efa->v1->no);
1202                                         glVertex3fv(efa->v1->co);
1203                                 }
1204
1205                                 PASSATTRIB(efa, efa->v2, 1);
1206                                 if(vertexCos) {
1207                                         glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
1208                                         glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
1209                                 }
1210                                 else {
1211                                         glNormal3fv(efa->v2->no);
1212                                         glVertex3fv(efa->v2->co);
1213                                 }
1214
1215                                 PASSATTRIB(efa, efa->v3, 2);
1216                                 if(vertexCos) {
1217                                         glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
1218                                         glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
1219                                 }
1220                                 else {
1221                                         glNormal3fv(efa->v3->no);
1222                                         glVertex3fv(efa->v3->co);
1223                                 }
1224
1225                                 if(efa->v4) {
1226                                         PASSATTRIB(efa, efa->v4, 3);
1227                                         if(vertexCos) {
1228                                                 glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
1229                                                 glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
1230                                         }
1231                                         else {
1232                                                 glNormal3fv(efa->v4->no);
1233                                                 glVertex3fv(efa->v4->co);
1234                                         }
1235                                 }
1236                         }
1237                         glEnd();
1238                 }
1239         }
1240 }
1241
1242 static void emDM_drawFacesGLSL(void *dm,
1243                int (*setMaterial)(int, void *attribs))
1244 {
1245         ((DerivedMesh*)dm)->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1246 }
1247
1248 static void emDM_getMinMax(void *dm, float min_r[3], float max_r[3])
1249 {
1250         EditMeshDerivedMesh *emdm= dm;
1251         EditVert *eve;
1252         int i;
1253
1254         if (emdm->em->verts.first) {
1255                 for (i=0,eve= emdm->em->verts.first; eve; i++,eve= eve->next) {
1256                         if (emdm->vertexCos) {
1257                                 DO_MINMAX(emdm->vertexCos[i], min_r, max_r);
1258                         } else {
1259                                 DO_MINMAX(eve->co, min_r, max_r);
1260                         }
1261                 }
1262         } else {
1263                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
1264         }
1265 }
1266 static int emDM_getNumVerts(void *dm)
1267 {
1268         EditMeshDerivedMesh *emdm= dm;
1269
1270         return BLI_countlist(&emdm->em->verts);
1271 }
1272
1273 static int emDM_getNumEdges(void *dm)
1274 {
1275         EditMeshDerivedMesh *emdm= dm;
1276
1277         return BLI_countlist(&emdm->em->edges);
1278 }
1279
1280 static int emDM_getNumTessFaces(void *dm)
1281 {
1282         EditMeshDerivedMesh *emdm= dm;
1283
1284         return BLI_countlist(&emdm->em->faces);
1285 }
1286
1287 static void emDM_getVert(void *dm, int index, MVert *vert_r)
1288 {
1289         EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
1290         int i;
1291
1292         for(i = 0; i < index; ++i) ev = ev->next;
1293
1294         VECCOPY(vert_r->co, ev->co);
1295
1296         vert_r->no[0] = ev->no[0] * 32767.0;
1297         vert_r->no[1] = ev->no[1] * 32767.0;
1298         vert_r->no[2] = ev->no[2] * 32767.0;
1299
1300         /* TODO what to do with vert_r->flag and vert_r->mat_nr? */
1301         vert_r->mat_nr = 0;
1302         vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1303 }
1304
1305 static void emDM_getEdge(void *dm, int index, MEdge *edge_r)
1306 {
1307         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1308         EditEdge *ee = em->edges.first;
1309         EditVert *ev, *v1, *v2;
1310         int i;
1311
1312         for(i = 0; i < index; ++i) ee = ee->next;
1313
1314         edge_r->crease = (unsigned char) (ee->crease*255.0f);
1315         edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1316         /* TODO what to do with edge_r->flag? */
1317         edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1318         if (ee->seam) edge_r->flag |= ME_SEAM;
1319         if (ee->sharp) edge_r->flag |= ME_SHARP;
1320 #if 0
1321         /* this needs setup of f2 field */
1322         if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1323 #endif
1324
1325         /* goddamn, we have to search all verts to find indices */
1326         v1 = ee->v1;
1327         v2 = ee->v2;
1328         for(i = 0, ev = em->verts.first; v1 || v2; i++, ev = ev->next) {
1329                 if(ev == v1) {
1330                         edge_r->v1 = i;
1331                         v1 = NULL;
1332                 }
1333                 if(ev == v2) {
1334                         edge_r->v2 = i;
1335                         v2 = NULL;
1336                 }
1337         }
1338 }
1339
1340 static void emDM_getFace(void *dm, int index, MFace *face_r)
1341 {
1342         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1343         EditFace *ef = em->faces.first;
1344         EditVert *ev, *v1, *v2, *v3, *v4;
1345         int i;
1346
1347         for(i = 0; i < index; ++i) ef = ef->next;
1348
1349         face_r->mat_nr = ef->mat_nr;
1350         face_r->flag = ef->flag;
1351
1352         /* goddamn, we have to search all verts to find indices */
1353         v1 = ef->v1;
1354         v2 = ef->v2;
1355         v3 = ef->v3;
1356         v4 = ef->v4;
1357         if(!v4) face_r->v4 = 0;
1358
1359         for(i = 0, ev = em->verts.first; v1 || v2 || v3 || v4;
1360             i++, ev = ev->next) {
1361                 if(ev == v1) {
1362                         face_r->v1 = i;
1363                         v1 = NULL;
1364                 }
1365                 if(ev == v2) {
1366                         face_r->v2 = i;
1367                         v2 = NULL;
1368                 }
1369                 if(ev == v3) {
1370                         face_r->v3 = i;
1371                         v3 = NULL;
1372                 }
1373                 if(ev == v4) {
1374                         face_r->v4 = i;
1375                         v4 = NULL;
1376                 }
1377         }
1378
1379         test_index_face(face_r, NULL, 0, ef->v4?4:3);
1380 }
1381
1382 static void emDM_copyVertArray(void *dm, MVert *vert_r)
1383 {
1384         EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
1385
1386         for( ; ev; ev = ev->next, ++vert_r) {
1387                 VECCOPY(vert_r->co, ev->co);
1388
1389                 vert_r->no[0] = ev->no[0] * 32767.0;
1390                 vert_r->no[1] = ev->no[1] * 32767.0;
1391                 vert_r->no[2] = ev->no[2] * 32767.0;
1392
1393                 /* TODO what to do with vert_r->flag and vert_r->mat_nr? */
1394                 vert_r->mat_nr = 0;
1395                 vert_r->flag = 0;
1396                 vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
1397         }
1398 }
1399
1400 static void emDM_copyEdgeArray(void *dm, MEdge *edge_r)
1401 {
1402         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1403         EditEdge *ee = em->edges.first;
1404         EditVert *ev;
1405         int i;
1406
1407         /* store vertex indices in tmp union */
1408         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1409                 ev->tmp.l = (intptr_t) i;
1410
1411         for( ; ee; ee = ee->next, ++edge_r) {
1412                 edge_r->crease = (unsigned char) (ee->crease*255.0f);
1413                 edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
1414                 /* TODO what to do with edge_r->flag? */
1415                 edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
1416                 if (ee->seam) edge_r->flag |= ME_SEAM;
1417                 if (ee->sharp) edge_r->flag |= ME_SHARP;
1418 #if 0
1419                 /* this needs setup of f2 field */
1420                 if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
1421 #endif
1422
1423                 edge_r->v1 = (int)ee->v1->tmp.l;
1424                 edge_r->v2 = (int)ee->v2->tmp.l;
1425         }
1426 }
1427
1428 static void emDM_copyFaceArray(void *dm, MFace *face_r)
1429 {
1430         EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
1431         EditFace *ef = em->faces.first;
1432         EditVert *ev;
1433         int i;
1434
1435         /* store vertexes indices in tmp union */
1436         for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
1437                 ev->tmp.l = (intptr_t) i;
1438
1439         for( ; ef; ef = ef->next, ++face_r) {
1440                 face_r->mat_nr = ef->mat_nr;
1441                 face_r->flag = ef->flag;
1442
1443                 face_r->v1 = (int)ef->v1->tmp.l;
1444                 face_r->v2 = (int)ef->v2->tmp.l;
1445                 face_r->v3 = (int)ef->v3->tmp.l;
1446                 if(ef->v4) face_r->v4 = (int)ef->v4->tmp.l;
1447                 else face_r->v4 = 0;
1448
1449                 test_index_face(face_r, NULL, 0, ef->v4?4:3);
1450         }
1451 }
1452
1453 static void *emDM_getFaceDataArray(void *dm, int type)
1454 {
1455         EditMeshDerivedMesh *emdm= dm;
1456         EditMesh *em= emdm->em;
1457         EditFace *efa;
1458         char *data, *emdata;
1459         void *datalayer;
1460         int index, offset, size;
1461
1462         datalayer = DM_get_tessface_data_layer(dm, type);
1463         if(datalayer)
1464                 return datalayer;
1465
1466         /* layers are store per face for editmesh, we convert to a temporary
1467          * data layer array in the derivedmesh when these are requested */
1468         if(type == CD_MTFACE || type == CD_MCOL) {
1469                 index = CustomData_get_layer_index(&em->fdata, type);
1470
1471                 if(index != -1) {
1472                         offset = em->fdata.layers[index].offset;
1473                         size = CustomData_sizeof(type);
1474
1475                         DM_add_tessface_layer(dm, type, CD_CALLOC, NULL);
1476                         index = CustomData_get_layer_index(&emdm->dm.faceData, type);
1477                         emdm->dm.faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
1478
1479                         data = datalayer = DM_get_tessface_data_layer(dm, type);
1480                         for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
1481                                 emdata = CustomData_em_get(&em->fdata, efa->data, type);
1482                                 memcpy(data, emdata, size);
1483                         }
1484                 }
1485         }
1486
1487         return datalayer;
1488 }
1489
1490 static void emDM_release(void *dm)
1491 {
1492         EditMeshDerivedMesh *emdm= dm;
1493
1494         if (DM_release(dm)) {
1495                 if (emdm->vertexCos) {
1496                         MEM_freeN(emdm->vertexCos);
1497                         MEM_freeN(emdm->vertexNos);
1498                         MEM_freeN(emdm->faceNos);
1499                 }
1500
1501                 MEM_freeN(emdm);
1502         }
1503 }
1504
1505 static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
1506                                            float (*vertexCos)[3])
1507 {
1508         EditMeshDerivedMesh *emdm = MEM_callocN(sizeof(*emdm), "emdm");
1509
1510         DM_init(&emdm->dm, BLI_countlist(&em->verts),
1511                          BLI_countlist(&em->edges), BLI_countlist(&em->faces),
1512                          0, 0);
1513
1514         emdm->dm.getMinMax = emDM_getMinMax;
1515
1516         emdm->dm.getNumVerts = emDM_getNumVerts;
1517         emdm->dm.getNumEdges = emDM_getNumEdges;
1518         emdm->dm.getNumTessFaces = emDM_getNumTessFaces;
1519
1520         emdm->dm.getVert = emDM_getVert;
1521         emdm->dm.getEdge = emDM_getEdge;
1522         emdm->dm.getTessFace = emDM_getFace;
1523         emdm->dm.copyVertArray = emDM_copyVertArray;
1524         emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
1525         emdm->dm.copyTessFaceArray = emDM_copyFaceArray;
1526         emdm->dm.getTessFaceDataArray = emDM_getFaceDataArray;
1527
1528         emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
1529         emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
1530         emdm->dm.foreachMappedFaceCenter = emDM_foreachMappedFaceCenter;
1531
1532         emdm->dm.drawEdges = emDM_drawEdges;
1533         emdm->dm.drawMappedEdges = emDM_drawMappedEdges;
1534         emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
1535         emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
1536         emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
1537         emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
1538         emdm->dm.drawFacesTex = emDM_drawFacesTex;
1539         emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
1540         emdm->dm.drawUVEdges = emDM_drawUVEdges;
1541
1542         emdm->dm.release = emDM_release;
1543         
1544         emdm->em = em;
1545         emdm->vertexCos = vertexCos;
1546
1547         if(CustomData_has_layer(&em->vdata, CD_MDEFORMVERT)) {
1548                 EditVert *eve;
1549                 int i;
1550
1551                 DM_add_vert_layer(&emdm->dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
1552
1553                 for(eve = em->verts.first, i = 0; eve; eve = eve->next, ++i)
1554                         DM_set_vert_data(&emdm->dm, i, CD_MDEFORMVERT,
1555                                          CustomData_em_get(&em->vdata, eve->data, CD_MDEFORMVERT));
1556         }
1557
1558         if(vertexCos) {
1559                 EditVert *eve;
1560                 EditFace *efa;
1561                 int totface = BLI_countlist(&em->faces);
1562                 int i;
1563
1564                 for (i=0,eve=em->verts.first; eve; eve= eve->next)
1565                         eve->tmp.l = (intptr_t) i++;
1566
1567                 emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
1568                 emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
1569
1570                 for(i=0, efa= em->faces.first; efa; i++, efa=efa->next) {
1571                         float *v1 = vertexCos[(int) efa->v1->tmp.l];
1572                         float *v2 = vertexCos[(int) efa->v2->tmp.l];
1573                         float *v3 = vertexCos[(int) efa->v3->tmp.l];
1574                         float *no = emdm->faceNos[i];
1575                         
1576                         if(efa->v4) {
1577                                 float *v4 = vertexCos[(int) efa->v4->tmp.l];
1578
1579                                 CalcNormFloat4(v1, v2, v3, v4, no);
1580                                 VecAddf(emdm->vertexNos[(int) efa->v4->tmp.l], emdm->vertexNos[(int) efa->v4->tmp.l], no);
1581                         }
1582                         else {
1583                                 CalcNormFloat(v1, v2, v3, no);
1584                         }
1585
1586                         VecAddf(emdm->vertexNos[(int) efa->v1->tmp.l], emdm->vertexNos[(int) efa->v1->tmp.l], no);
1587                         VecAddf(emdm->vertexNos[(int) efa->v2->tmp.l], emdm->vertexNos[(int) efa->v2->tmp.l], no);
1588                         VecAddf(emdm->vertexNos[(int) efa->v3->tmp.l], emdm->vertexNos[(int) efa->v3->tmp.l], no);
1589                 }
1590
1591                 for(i=0, eve= em->verts.first; eve; i++, eve=eve->next) {
1592                         float *no = emdm->vertexNos[i];
1593                         /* following Mesh convention; we use vertex coordinate itself
1594                          * for normal in this case */
1595                         if (Normalize(no)==0.0) {
1596                                 VECCOPY(no, vertexCos[i]);
1597                                 Normalize(no);
1598                         }
1599                 }
1600         }
1601
1602         return (DerivedMesh*) emdm;
1603 }
1604
1605 /***/
1606
1607 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
1608 {
1609         Mesh *me = ob->data;
1610         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1611         DerivedMesh *dm;
1612
1613         md->scene= scene;
1614         
1615         if (!(md->mode&eModifierMode_Realtime)) return NULL;
1616         if (mti->isDisabled && mti->isDisabled(md)) return NULL;
1617
1618         if (mti->type==eModifierTypeType_OnlyDeform) {
1619                 int numVerts;
1620                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
1621
1622                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
1623                 dm = getMeshDerivedMesh(me, ob, deformedVerts);
1624
1625                 MEM_freeN(deformedVerts);
1626         } else {
1627                 DerivedMesh *tdm = getMeshDerivedMesh(me, ob, NULL);
1628                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
1629
1630                 if(tdm != dm) tdm->release(tdm);
1631         }
1632
1633         return dm;
1634 }
1635
1636 static float *get_editbmesh_orco_verts(BMEditMesh *em)
1637 {
1638         BMIter iter;
1639         BMVert *eve;
1640         float *orco;
1641         int a, totvert;
1642
1643         /* these may not really be the orco's, but it's only for preview.
1644          * could be solver better once, but isn't simple */
1645
1646         totvert= em->bm->totvert;
1647         
1648         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
1649
1650         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1651         for (a=0; eve; eve=BMIter_Step(&iter), a+=3)
1652                 VECCOPY(orco+a, eve->co);
1653         
1654         return orco;
1655 }
1656
1657 /* orco custom data layer */
1658 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em)
1659 {
1660         DerivedMesh *dm;
1661         float (*orco)[3];
1662
1663         if(em) {
1664                 dm= CDDM_from_BMEditMesh(em, me);
1665                 orco= (float(*)[3])get_editbmesh_orco_verts(em);
1666         }
1667         else {
1668                 dm= CDDM_from_mesh(me, ob);
1669                 orco= (float(*)[3])get_mesh_orco_verts(ob);
1670         }
1671
1672         CDDM_apply_vert_coords(dm, orco);
1673         CDDM_calc_normals(dm);
1674         MEM_freeN(orco);
1675
1676         return dm;
1677 }
1678
1679 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm)
1680 {
1681         float (*orco)[3], (*layerorco)[3];
1682         int totvert;
1683
1684         totvert= dm->getNumVerts(dm);
1685
1686         if(orcodm) {
1687                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
1688
1689                 if(orcodm->getNumVerts(orcodm) == totvert)
1690                         orcodm->getVertCos(orcodm, orco);
1691                 else
1692                         dm->getVertCos(dm, orco);
1693         }
1694         else {
1695                 if(em) orco= (float(*)[3])get_editbmesh_orco_verts(em);
1696                 else orco= (float(*)[3])get_mesh_orco_verts(ob);
1697         }
1698
1699         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
1700
1701         if((layerorco = DM_get_vert_data_layer(dm, CD_ORCO))) {
1702                 memcpy(layerorco, orco, sizeof(float)*totvert);
1703                 MEM_freeN(orco);
1704         }
1705         else
1706                 DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, orco);
1707 }
1708
1709 /* weight paint colors */
1710
1711 /* Something of a hack, at the moment deal with weightpaint
1712  * by tucking into colors during modifier eval, only in
1713  * wpaint mode. Works ok but need to make sure recalc
1714  * happens on enter/exit wpaint.
1715  */
1716
1717 void weight_to_rgb(float input, float *fr, float *fg, float *fb)
1718 {
1719         float blend;
1720         
1721         blend= ((input/2.0f)+0.5f);
1722         
1723         if (input<=0.25f){      // blue->cyan
1724                 *fr= 0.0f;
1725                 *fg= blend*input*4.0f;
1726                 *fb= blend;
1727         }
1728         else if (input<=0.50f){ // cyan->green
1729                 *fr= 0.0f;
1730                 *fg= blend;
1731                 *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
1732         }
1733         else if (input<=0.75){  // green->yellow
1734                 *fr= blend * ((input-0.50f)*4.0f);
1735                 *fg= blend;
1736                 *fb= 0.0f;
1737         }
1738         else if (input<=1.0){ // yellow->red
1739                 *fr= blend;
1740                 *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
1741                 *fb= 0.0f;
1742         }
1743 }
1744
1745 static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, unsigned char *col)
1746 {
1747         Mesh *me = ob->data;
1748         float colf[4], input = 0.0f;
1749         int i;
1750
1751         if (me->dvert) {
1752                 for (i=0; i<me->dvert[vert].totweight; i++)
1753                         if (me->dvert[vert].dw[i].def_nr==ob->actdef-1)
1754                                 input+=me->dvert[vert].dw[i].weight;            
1755         }
1756
1757         CLAMP(input, 0.0f, 1.0f);
1758         
1759         if(coba)
1760                 do_colorband(coba, input, colf);
1761         else
1762                 weight_to_rgb(input, colf, colf+1, colf+2);
1763         
1764         col[3] = (unsigned char)(colf[0] * 255.0f);
1765         col[2] = (unsigned char)(colf[1] * 255.0f);
1766         col[1] = (unsigned char)(colf[2] * 255.0f);
1767         col[0] = 255;
1768 }
1769
1770 static ColorBand *stored_cb= NULL;
1771
1772 void vDM_ColorBand_store(ColorBand *coba)
1773 {
1774         stored_cb= coba;
1775 }
1776
1777 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm)
1778 {
1779         Mesh *me = ob->data;
1780         MFace *mf = dm->getTessFaceArray(dm);
1781         DMFaceIter *dfiter;
1782         DMLoopIter *dliter;
1783         ColorBand *coba= stored_cb;     /* warning, not a local var */
1784         unsigned char *wtcol;
1785         unsigned char(*wlcol)[4] = NULL;
1786         BLI_array_declare(wlcol);
1787         int i, totface=dm->getNumTessFaces(dm), totpoly=dm->getNumFaces, totloop;
1788         int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
1789         
1790         wtcol = MEM_callocN (sizeof (unsigned char) * totface*4*4, "weightmap");
1791         
1792         /*first add colors to the tesselation faces*/
1793         memset(wtcol, 0x55, sizeof (unsigned char) * totface*4*4);
1794         for (i=0; i<totface; i++, mf++) {
1795                 calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4]); 
1796                 calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4]); 
1797                 calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4]); 
1798                 if (mf->v4)
1799                         calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4]); 
1800         }
1801         
1802         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, totface);
1803
1804         /*now add to loops, so the data can be passed through the modifier stack*/
1805         totloop = 0;
1806         dfiter = dm->newFaceIter(dm);
1807         for (; !dfiter->done; dfiter->step(dfiter)) {
1808                 dliter = dfiter->getLoopsIter(dfiter);
1809                 for (; !dliter->done; dliter->step(dliter), totloop++) {
1810                         BLI_array_growone(wlcol);
1811                         calc_weightpaint_vert_color(ob, coba, dliter->vindex, &wlcol[totloop]);                  
1812                 }
1813         }
1814
1815         CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wlcol, totloop);
1816
1817         dfiter->free(dfiter);
1818 }
1819
1820 /* new value for useDeform -1  (hack for the gameengine):
1821  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1822  * - don't apply the key
1823  * - apply deform modifiers and input vertexco
1824  */
1825 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1826                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1827                                 int useRenderParams, int useDeform,
1828                                 int needMapping, CustomDataMask dataMask, int index)
1829 {
1830         Mesh *me = ob->data;
1831         ModifierData *firstmd, *md;
1832         LinkNode *datamasks, *curr;
1833         CustomDataMask mask;
1834         float (*deformedVerts)[3] = NULL;
1835         DerivedMesh *dm, *orcodm, *finaldm;
1836         int numVerts = me->totvert;
1837         int required_mode;
1838
1839         md = firstmd = (useDeform<0) ? ob->modifiers.first : modifiers_getVirtualModifierList(ob);
1840
1841         modifiers_clearErrors(ob);
1842
1843         if(useRenderParams) required_mode = eModifierMode_Render;
1844         else required_mode = eModifierMode_Realtime;
1845
1846         /* we always want to keep original indices */
1847         dataMask |= CD_MASK_ORIGINDEX;
1848
1849         datamasks = modifiers_calcDataMasks(ob, md, dataMask, required_mode);
1850         curr = datamasks;
1851
1852         if(deform_r) *deform_r = NULL;
1853         *final_r = NULL;
1854
1855         if(useDeform) {
1856                 if(useDeform > 0 && do_ob_key(scene, ob)) /* shape key makes deform verts */
1857                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1858                 else if(inputVertexCos)
1859                         deformedVerts = inputVertexCos;
1860                 
1861                 /* Apply all leading deforming modifiers */
1862                 for(;md; md = md->next, curr = curr->next) {
1863                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1864
1865                         md->scene= scene;
1866                         
1867                         if(!modifier_isEnabled(md, required_mode)) continue;
1868                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1869
1870                         if(mti->type == eModifierTypeType_OnlyDeform) {
1871                                 if(!deformedVerts)
1872                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1873
1874                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1875                         } else {
1876                                 break;
1877                         }
1878                         
1879                         /* grab modifiers until index i */
1880                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1881                                 break;
1882                 }
1883
1884                 /* Result of all leading deforming modifiers is cached for
1885                  * places that wish to use the original mesh but with deformed
1886                  * coordinates (vpaint, etc.)
1887                  */
1888                 if (deform_r) {
1889                         *deform_r = CDDM_from_mesh(me, ob);
1890
1891                         if(deformedVerts) {
1892                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1893                                 CDDM_calc_normals(*deform_r);
1894                         }
1895                 }
1896         } else {
1897                 /* default behaviour for meshes */
1898                 if(inputVertexCos)
1899                         deformedVerts = inputVertexCos;
1900                 else
1901                         deformedVerts = mesh_getRefKeyCos(me, &numVerts);
1902         }
1903
1904
1905         /* Now apply all remaining modifiers. If useDeform is off then skip
1906          * OnlyDeform ones. 
1907          */
1908         dm = NULL;
1909         orcodm = NULL;
1910
1911         for(;md; md = md->next, curr = curr->next) {
1912                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1913
1914                 md->scene= scene;
1915                 
1916                 if(!modifier_isEnabled(md, required_mode)) continue;
1917                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1918                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1919                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1920                         continue;
1921                 }
1922                 if(needMapping && !modifier_supportsMapping(md)) continue;
1923                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1924
1925                 /* add an orco layer if needed by this modifier */
1926                 if(dm && mti->requiredDataMask) {
1927                         mask = mti->requiredDataMask(ob, md);
1928                         if(mask & CD_MASK_ORCO)
1929                                 add_orco_dm(ob, NULL, dm, orcodm);
1930                 }
1931
1932                 /* How to apply modifier depends on (a) what we already have as
1933                  * a result of previous modifiers (could be a DerivedMesh or just
1934                  * deformed vertices) and (b) what type the modifier is.
1935                  */
1936
1937                 if(mti->type == eModifierTypeType_OnlyDeform) {
1938                         
1939                         /* No existing verts to deform, need to build them. */
1940                         if(!deformedVerts) {
1941                                 if(dm) {
1942                                         /* Deforming a derived mesh, read the vertex locations
1943                                          * out of the mesh and deform them. Once done with this
1944                                          * run of deformers verts will be written back.
1945                                          */
1946                                         numVerts = dm->getNumVerts(dm);
1947                                         deformedVerts =
1948                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1949                                         dm->getVertCos(dm, deformedVerts);
1950                                 } else {
1951                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1952                                 }
1953                         }
1954
1955                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1956                 } else {
1957                         DerivedMesh *ndm;
1958
1959                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1960                         if(dm) {
1961                                 if(deformedVerts) {
1962                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1963                                         dm->release(dm);
1964                                         dm = tdm;
1965
1966                                         CDDM_apply_vert_coords(dm, deformedVerts);
1967                                         CDDM_calc_normals(dm);
1968                                 }
1969                         } else {
1970                                 dm = CDDM_from_mesh(me, ob);
1971
1972                                 if(deformedVerts) {
1973                                         CDDM_apply_vert_coords(dm, deformedVerts);
1974                                         CDDM_calc_normals(dm);
1975                                 }
1976
1977                                 if(dataMask & CD_MASK_WEIGHT_MCOL)
1978                                         add_weight_mcol_dm(ob, dm);
1979                         }
1980
1981                         /* create an orco derivedmesh in parallel */
1982                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1983                         if(mask & CD_MASK_ORCO) {
1984                                 if(!orcodm)
1985                                         orcodm= create_orco_dm(ob, me, NULL);
1986
1987                                 mask &= ~CD_MASK_ORCO;
1988                                 DM_set_only_copy(orcodm, mask);
1989                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, !inputVertexCos);
1990
1991                                 if(ndm) {
1992                                         /* if the modifier returned a new dm, release the old one */
1993                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1994                                         orcodm = ndm;
1995                                 }
1996                         }
1997
1998                         /* set the DerivedMesh to only copy needed data */
1999                         DM_set_only_copy(dm, mask);
2000                         
2001                         /* add an origspace layer if needed */
2002                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
2003                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2004                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2005
2006                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, !inputVertexCos);
2007
2008                         if(ndm) {
2009                                 /* if the modifier returned a new dm, release the old one */
2010                                 if(dm && dm != ndm) dm->release(dm);
2011
2012                                 dm = ndm;
2013
2014                                 if(deformedVerts) {
2015                                         if(deformedVerts != inputVertexCos)
2016                                                 MEM_freeN(deformedVerts);
2017
2018                                         deformedVerts = NULL;
2019                                 }
2020                         } 
2021                 }
2022                 
2023                 /* grab modifiers until index i */
2024                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
2025                         break;
2026         }
2027
2028         for(md=firstmd; md; md=md->next)
2029                 modifier_freeTemporaryData(md);
2030
2031         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
2032          * need to apply these back onto the DerivedMesh. If we have no
2033          * DerivedMesh then we need to build one.
2034          */
2035         if(dm && deformedVerts) {
2036                 finaldm = CDDM_copy(dm, 0);
2037
2038                 dm->release(dm);
2039
2040                 CDDM_apply_vert_coords(finaldm, deformedVerts);
2041                 CDDM_calc_normals(finaldm);
2042         } else if(dm) {
2043                 finaldm = dm;
2044         } else {
2045                 finaldm = CDDM_from_mesh(me, ob);
2046
2047                 if(deformedVerts) {
2048                         CDDM_apply_vert_coords(finaldm, deformedVerts);
2049                         CDDM_calc_normals(finaldm);
2050                 }
2051
2052                 if(dataMask & CD_MASK_WEIGHT_MCOL)
2053                         add_weight_mcol_dm(ob, finaldm);
2054         }
2055
2056         /* add an orco layer if needed */
2057         if(dataMask & CD_MASK_ORCO) {
2058                 add_orco_dm(ob, NULL, finaldm, orcodm);
2059
2060                 if(deform_r && *deform_r)
2061                         add_orco_dm(ob, NULL, *deform_r, NULL);
2062         }
2063
2064         *final_r = finaldm;
2065
2066         if(orcodm)
2067                 orcodm->release(orcodm);
2068
2069         if(deformedVerts && deformedVerts != inputVertexCos)
2070                 MEM_freeN(deformedVerts);
2071
2072         BLI_linklist_free(datamasks, NULL);
2073 }
2074
2075 static float (*editbmesh_getVertexCos(BMEditMesh *em, int *numVerts_r))[3]
2076 {
2077         int i, numVerts = *numVerts_r = em->bm->totvert;
2078         float (*cos)[3];
2079         BMIter iter;
2080         BMVert *eve;
2081
2082         cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
2083
2084         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
2085         for (i=0; eve; eve=BMIter_Step(&iter), i++) {
2086                 VECCOPY(cos[i], eve->co);
2087         }
2088
2089         return cos;
2090 }
2091
2092 static int editbmesh_modifier_is_enabled(ModifierData *md, DerivedMesh *dm)
2093 {
2094         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2095         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2096
2097         if(!modifier_isEnabled(md, required_mode)) return 0;
2098         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2099                 modifier_setError(md, "Modifier requires original data, bad stack position.");
2100                 return 0;
2101         }
2102         
2103         return 1;
2104 }
2105
2106 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
2107                                     DerivedMesh **final_r,
2108                                     CustomDataMask dataMask)
2109 {
2110         ModifierData *md;
2111         float (*deformedVerts)[3] = NULL;
2112         CustomDataMask mask;
2113         DerivedMesh *dm, *orcodm = NULL;
2114         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(ob, NULL);
2115         LinkNode *datamasks, *curr;
2116         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2117
2118         modifiers_clearErrors(ob);
2119
2120         if(cage_r && cageIndex == -1) {
2121                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
2122         }
2123
2124         dm = NULL;
2125         md = ob->modifiers.first;
2126         
2127         /* we always want to keep original indices */
2128         dataMask |= CD_MASK_ORIGINDEX;
2129
2130         datamasks = modifiers_calcDataMasks(ob, md, dataMask, required_mode);
2131
2132         curr = datamasks;
2133         for(i = 0; md; i++, md = md->next, curr = curr->next) {
2134                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2135
2136                 md->scene= scene;
2137                 
2138                 if(!editbmesh_modifier_is_enabled(md, dm))
2139                         continue;
2140
2141                 /* add an orco layer if needed by this modifier */
2142                 if(dm && mti->requiredDataMask) {
2143                         mask = mti->requiredDataMask(ob, md);
2144                         if(mask & CD_MASK_ORCO)
2145                                 add_orco_dm(ob, em, dm, orcodm);
2146                 }
2147
2148                 /* How to apply modifier depends on (a) what we already have as
2149                  * a result of previous modifiers (could be a DerivedMesh or just
2150                  * deformed vertices) and (b) what type the modifier is.
2151                  */
2152
2153                 if(mti->type == eModifierTypeType_OnlyDeform) {
2154                         /* No existing verts to deform, need to build them. */
2155                         if(!deformedVerts) {
2156                                 if(dm) {
2157                                         /* Deforming a derived mesh, read the vertex locations
2158                                          * out of the mesh and deform them. Once done with this
2159                                          * run of deformers verts will be written back.
2160                                          */
2161                                         numVerts = dm->getNumVerts(dm);
2162                                         deformedVerts =
2163                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2164                                         dm->getVertCos(dm, deformedVerts);
2165                                 } else {
2166                                         deformedVerts = editbmesh_getVertexCos(em, &numVerts);
2167                                 }
2168                         }
2169
2170                         mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2171                 } else {
2172                         DerivedMesh *ndm;
2173
2174                         /* apply vertex coordinates or build a DerivedMesh as necessary */
2175                         if(dm) {
2176                                 if(deformedVerts) {
2177                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
2178                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
2179                                         dm = tdm;
2180
2181                                         CDDM_apply_vert_coords(dm, deformedVerts);
2182                                         CDDM_calc_normals(dm);
2183                                 } else if(cage_r && dm == *cage_r) {
2184                                         /* dm may be changed by this modifier, so we need to copy it
2185                                          */
2186                                         dm = CDDM_copy(dm, 0);
2187                                 }
2188
2189                         } else {
2190                                 dm = CDDM_from_BMEditMesh(em, ob->data);
2191
2192                                 if(deformedVerts) {
2193                                         CDDM_apply_vert_coords(dm, deformedVerts);
2194                                         CDDM_calc_normals(dm);
2195                                 }
2196                         }
2197
2198                         /* create an orco derivedmesh in parallel */
2199                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
2200                         if(mask & CD_MASK_ORCO) {
2201                                 if(!orcodm)
2202                                         orcodm= create_orco_dm(ob, ob->data, em);
2203
2204                                 mask &= ~CD_MASK_ORCO;
2205                                 DM_set_only_copy(orcodm, mask);
2206                                 ndm = mti->applyModifierEM(md, ob, em, orcodm);
2207
2208                                 if(ndm) {
2209                                         /* if the modifier returned a new dm, release the old one */
2210                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
2211                                         orcodm = ndm;
2212                                 }
2213                         }
2214
2215                         /* set the DerivedMesh to only copy needed data */
2216                         DM_set_only_copy(dm, (CustomDataMask)GET_INT_FROM_POINTER(curr->link));
2217
2218                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
2219                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
2220                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
2221                         
2222                         ndm = mti->applyModifierEM(md, ob, em, dm);
2223
2224                         if (ndm) {
2225                                 if(dm && dm != ndm)
2226                                         dm->release(dm);
2227
2228                                 dm = ndm;
2229
2230                                 if (deformedVerts) {
2231                                         MEM_freeN(deformedVerts);
2232                                         deformedVerts = NULL;
2233                                 }
2234                         }
2235                 }
2236
2237                 if(cage_r && i == cageIndex) {
2238                         if(dm && deformedVerts) {
2239                                 *cage_r = CDDM_copy(dm, 0);
2240                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2241                         } else if(dm) {
2242                                 *cage_r = dm;
2243                         } else {
2244                                 *cage_r =
2245                                     getEditDerivedBMesh(em, ob,
2246                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2247                         }
2248                 }
2249         }
2250
2251         BLI_linklist_free(datamasks, NULL);
2252
2253         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2254          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2255          * then we need to build one.
2256          */
2257         if(dm && deformedVerts) {
2258                 *final_r = CDDM_copy(dm, 0);
2259
2260                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
2261
2262                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2263                 CDDM_calc_normals(*final_r);
2264         } else if (dm) {
2265                 *final_r = dm;
2266         } else if (!deformedVerts && cage_r && *cage_r) {
2267                 *final_r = *cage_r;
2268         } else {
2269                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2270                 deformedVerts = NULL;
2271         }
2272
2273         /* add an orco layer if needed */
2274         if(dataMask & CD_MASK_ORCO)
2275                 add_orco_dm(ob, em, *final_r, orcodm);
2276
2277         if(orcodm)
2278                 orcodm->release(orcodm);
2279
2280         if(deformedVerts)
2281                 MEM_freeN(deformedVerts);
2282 }
2283
2284 static void clear_mesh_caches(Object *ob)
2285 {
2286         Mesh *me= ob->data;
2287
2288                 /* also serves as signal to remake texspace */
2289         if (ob->bb) {
2290                 MEM_freeN(ob->bb);
2291                 ob->bb = NULL;
2292         }
2293         if (me->bb) {
2294                 MEM_freeN(me->bb);
2295                 me->bb = NULL;
2296         }
2297
2298         freedisplist(&ob->disp);
2299
2300         if (ob->derivedFinal) {
2301                 ob->derivedFinal->needsFree = 1;
2302                 ob->derivedFinal->release(ob->derivedFinal);
2303                 ob->derivedFinal= NULL;
2304         }
2305         if (ob->derivedDeform) {
2306                 ob->derivedDeform->needsFree = 1;
2307                 ob->derivedDeform->release(ob->derivedDeform);
2308                 ob->derivedDeform= NULL;
2309         }
2310 }
2311
2312 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
2313 {
2314         Object *obact = scene->basact?scene->basact->object:NULL;
2315         int editing = paint_facesel_test(ob);
2316         int needMapping = editing && (ob==obact);
2317         float min[3], max[3];
2318         
2319         clear_mesh_caches(ob);
2320
2321         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2322                                                 &ob->derivedFinal, 0, 1,
2323                                                 needMapping, dataMask, -1);
2324
2325         INIT_MINMAX(min, max);
2326
2327         ob->derivedFinal->getMinMax(ob->derivedFinal, min, max);
2328
2329         if(!ob->bb)
2330                 ob->bb= MEM_callocN(sizeof(BoundBox), "bb");
2331         boundbox_set_from_min_max(ob->bb, min, max);
2332
2333         ob->derivedFinal->needsFree = 0;
2334         ob->derivedDeform->needsFree = 0;
2335         ob->lastDataMask = dataMask;
2336
2337 }
2338
2339 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2340 {
2341         float min[3], max[3];
2342
2343         clear_mesh_caches(obedit);
2344
2345         if (em->derivedFinal) {
2346                 if (em->derivedFinal!=em->derivedCage) {
2347                         em->derivedFinal->needsFree = 1;
2348                         em->derivedFinal->release(em->derivedFinal);
2349                 }
2350                 em->derivedFinal = NULL;
2351         }
2352         if (em->derivedCage) {
2353                 em->derivedCage->needsFree = 1;
2354                 em->derivedCage->release(em->derivedCage);
2355                 em->derivedCage = NULL;
2356         }
2357
2358         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2359         em->lastDataMask = dataMask;
2360
2361         INIT_MINMAX(min, max);
2362
2363         em->derivedFinal->getMinMax(em->derivedFinal, min, max);
2364
2365         if(!obedit->bb)
2366                 obedit->bb= MEM_callocN(sizeof(BoundBox), "bb");
2367         boundbox_set_from_min_max(obedit->bb, min, max);
2368
2369         em->derivedFinal->needsFree = 0;
2370         em->derivedCage->needsFree = 0;
2371 }
2372
2373 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em, CustomDataMask dataMask)
2374 {
2375         if (em) {
2376                 editbmesh_build_data(scene, ob, em, dataMask);
2377         } else {
2378                 mesh_build_data(scene, ob, dataMask);
2379         }
2380 }
2381
2382 /***/
2383
2384 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2385 {
2386         /* if there's no derived mesh or the last data mask used doesn't include
2387          * the data we need, rebuild the derived mesh
2388          */
2389         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2390                 mesh_build_data(scene, ob, dataMask);
2391
2392         return ob->derivedFinal;
2393 }
2394
2395 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2396 {
2397         /* if there's no derived mesh or the last data mask used doesn't include
2398          * the data we need, rebuild the derived mesh
2399          */
2400         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2401                 mesh_build_data(scene, ob, dataMask);
2402
2403         return ob->derivedDeform;
2404 }
2405
2406 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2407 {
2408         DerivedMesh *final;
2409         
2410         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1);
2411
2412         return final;
2413 }
2414
2415 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2416 {
2417         DerivedMesh *final;
2418         
2419         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index);
2420
2421         return final;
2422 }
2423
2424 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2425 {
2426         DerivedMesh *final;
2427
2428         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1);
2429
2430         return final;
2431 }
2432
2433 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2434                                            CustomDataMask dataMask)
2435 {
2436         DerivedMesh *final;
2437         
2438         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1);
2439
2440         return final;
2441 }
2442
2443 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2444                                             CustomDataMask dataMask)
2445 {
2446         DerivedMesh *final;
2447         
2448         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1);
2449
2450         return final;
2451 }
2452
2453 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2454                                                   float (*vertCos)[3],
2455                                                   CustomDataMask dataMask)
2456 {
2457         DerivedMesh *final;
2458
2459         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1);
2460
2461         return final;
2462 }
2463
2464 /***/
2465
2466 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2467                                                  CustomDataMask dataMask)
2468 {
2469         /* if there's no derived mesh or the last data mask used doesn't include
2470          * the data we need, rebuild the derived mesh
2471          */
2472         if(!em->derivedCage ||
2473            (em->lastDataMask & dataMask) != dataMask)
2474                 editbmesh_build_data(scene, obedit, em, dataMask);
2475
2476         *final_r = em->derivedFinal;
2477         return em->derivedCage;
2478 }
2479
2480 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2481 {
2482         /* if there's no derived mesh or the last data mask used doesn't include
2483          * the data we need, rebuild the derived mesh
2484          */
2485         if(!em->derivedCage ||
2486            (em->lastDataMask & dataMask) != dataMask)
2487                 editbmesh_build_data(scene, obedit, em, dataMask);
2488
2489         return em->derivedCage;
2490 }
2491
2492 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2493 {
2494         return getEditDerivedBMesh(em, obedit, NULL);
2495 }
2496
2497
2498 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2499
2500 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2501 {
2502         float *vec = userData;
2503         
2504         vec+= 6*index;
2505
2506         /* check if we've been here before (normal should not be 0) */
2507         if(vec[3] || vec[4] || vec[5]) return;
2508
2509         VECCOPY(vec, co);
2510         vec+= 3;
2511         if(no_f) {
2512                 VECCOPY(vec, no_f);
2513         }
2514         else {
2515                 VECCOPY(vec, no_s);
2516         }
2517 }
2518
2519 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2520 /* this is needed for all code using vertexgroups (no subsurf support) */
2521 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2522 /* in use now by vertex/weight paint and particle generating */
2523
2524 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2525 {
2526         Mesh *me= ob->data;
2527         DerivedMesh *dm;
2528         float *vertexcosnos;
2529         
2530         /* lets prevent crashing... */
2531         if(ob->type!=OB_MESH || me->totvert==0)
2532                 return NULL;
2533         
2534         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2535         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2536         
2537         if(dm->foreachMappedVert) {
2538                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2539         }
2540         else {
2541                 float *fp= vertexcosnos;
2542                 int a;
2543                 
2544                 for(a=0; a< me->totvert; a++, fp+=6) {
2545                         dm->getVertCo(dm, a, fp);
2546                         dm->getVertNo(dm, a, fp+3);
2547                 }
2548         }
2549         
2550         dm->release(dm);
2551         return vertexcosnos;
2552 }
2553
2554 /* ********* crazyspace *************** */
2555
2556 int editbmesh_get_first_deform_matrices(Object *ob, BMEditMesh *em, float (**deformmats)[3][3], float (**deformcos)[3])
2557 {
2558         ModifierData *md;
2559         DerivedMesh *dm;
2560         int i, a, numleft = 0, numVerts = 0;
2561         int cageIndex = modifiers_getCageIndex(ob, NULL);
2562         float (*defmats)[3][3] = NULL, (*deformedVerts)[3] = NULL;
2563
2564         modifiers_clearErrors(ob);
2565
2566         dm = NULL;
2567         md = ob->modifiers.first;
2568
2569         /* compute the deformation matrices and coordinates for the first
2570            modifiers with on cage editing that are enabled and support computing
2571            deform matrices */
2572         for(i = 0; md && i <= cageIndex; i++, md = md->next) {
2573                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2574
2575                 if(!editbmesh_modifier_is_enabled(md, dm))
2576                         continue;
2577
2578                 if(mti->type==eModifierTypeType_OnlyDeform && mti->deformMatricesEM) {
2579                         if(!defmats) {
2580                                 dm= getEditDerivedBMesh(em, ob, NULL);
2581                                 deformedVerts= editbmesh_getVertexCos(em, &numVerts);
2582                                 defmats= MEM_callocN(sizeof(*defmats)*numVerts, "defmats");
2583
2584                                 for(a=0; a<numVerts; a++)
2585                                         Mat3One(defmats[a]);
2586                         }
2587
2588                         mti->deformMatricesEM(md, ob, em, dm, deformedVerts, defmats,
2589                                 numVerts);
2590                 }
2591                 else
2592                         break;
2593         }
2594
2595         for(; md && i <= cageIndex; md = md->next, i++)
2596                 if(editbmesh_modifier_is_enabled(md, dm) && modifier_isDeformer(md))
2597                         numleft++;
2598
2599         if(dm)
2600                 dm->release(dm);
2601         
2602         *deformmats= defmats;
2603         *deformcos= deformedVerts;
2604
2605         return numleft;
2606 }
2607
2608 /* ******************* GLSL ******************** */
2609
2610 void DM_add_tangent_layer(DerivedMesh *dm)
2611 {
2612         /* mesh vars */
2613         MTFace *mtface, *tf;
2614         MFace *mface, *mf;
2615         MVert *mvert, *v1, *v2, *v3, *v4;
2616         MemArena *arena= NULL;
2617         VertexTangent **vtangents= NULL;
2618         float (*orco)[3]= NULL, (*tangent)[3];
2619         float *uv1, *uv2, *uv3, *uv4, *vtang;
2620         float fno[3], tang[3], uv[4][2];
2621         int i, j, len, mf_vi[4], totvert, totface;
2622
2623         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2624                 return;
2625
2626         /* check we have all the needed layers */
2627         totvert= dm->getNumVerts(dm);
2628         totface= dm->getNumTessFaces(dm);
2629
2630         mvert= dm->getVertArray(dm);
2631         mface= dm->getTessFaceArray(dm);
2632         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2633
2634         if(!mtface) {
2635                 orco= dm->getVertDataArray(dm, CD_ORCO);
2636                 if(!orco)
2637                         return;
2638         }
2639         
2640         /* create tangent layer */
2641         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2642         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2643         
2644         /* allocate some space */
2645         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
2646         BLI_memarena_use_calloc(arena);
2647         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2648         
2649         /* sum tangents at connected vertices */
2650         for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2651                 v1= &mvert[mf->v1];
2652                 v2= &mvert[mf->v2];
2653                 v3= &mvert[mf->v3];
2654
2655                 if (mf->v4) {
2656                         v4= &mvert[mf->v4];
2657                         CalcNormFloat4(v4->co, v3->co, v2->co, v1->co, fno);
2658                 }
2659                 else {
2660                         v4= NULL;
2661                         CalcNormFloat(v3->co, v2->co, v1->co, fno);
2662                 }
2663                 
2664                 if(mtface) {
2665                         uv1= tf->uv[0];
2666                         uv2= tf->uv[1];
2667                         uv3= tf->uv[2];
2668                         uv4= tf->uv[3];
2669                 }
2670                 else {
2671                         uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2672                         spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
2673                         spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
2674                         spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
2675                         if(v4)
2676                                 spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
2677                 }
2678                 
2679                 tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2680                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2681                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2682                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2683                 
2684                 if(mf->v4) {
2685                         v4= &mvert[mf->v4];
2686                         
2687                         tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2688                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2689                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2690                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2691                 }
2692         }
2693         
2694         /* write tangent to layer */
2695         for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2696                 len= (mf->v4)? 4 : 3; 
2697                 
2698                 if(mtface) {
2699                         uv1= tf->uv[0];
2700                         uv2= tf->uv[1];
2701                         uv3= tf->uv[2];
2702                         uv4= tf->uv[3];
2703                 }
2704                 else {
2705                         uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2706                         spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
2707                         spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
2708                         spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
2709                         if(len==4)
2710                                 spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
2711                 }
2712                 
2713                 mf_vi[0]= mf->v1;
2714                 mf_vi[1]= mf->v2;
2715                 mf_vi[2]= mf->v3;
2716                 mf_vi[3]= mf->v4;
2717                 
2718                 for(j=0; j<len; j++) {
2719                         vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2720
2721                         VECCOPY(tangent[j], vtang);
2722                         Normalize(tangent[j]);
2723                 }
2724         }
2725         
2726         BLI_memarena_free(arena);
2727         MEM_freeN(vtangents);
2728 }
2729
2730 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2731 {
2732         CustomData *vdata, *fdata, *tfdata = NULL;
2733         int a, b, layer;
2734
2735         /* From the layers requested by the GLSL shader, figure out which ones are
2736          * actually available for this derivedmesh, and retrieve the pointers */
2737
2738         memset(attribs, 0, sizeof(DMVertexAttribs));
2739
2740         vdata = &dm->vertData;
2741         fdata = &dm->faceData;
2742
2743         /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
2744          * can use offsets instead */
2745         if(dm->release == emDM_release)
2746                 tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
2747         else
2748                 tfdata = fdata;
2749
2750         /* add a tangent layer if necessary */
2751         for(b = 0; b < gattribs->totlayer; b++)
2752                 if(gattribs->layer[b].type == CD_TANGENT)
2753                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2754                                 DM_add_tangent_layer(dm);
2755
2756         for(b = 0; b < gattribs->totlayer; b++) {
2757                 if(gattribs->layer[b].type == CD_MTFACE) {
2758                         /* uv coordinates */
2759                         if(gattribs->layer[b].name[0])
2760                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2761                                         gattribs->layer[b].name);
2762                         else
2763                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2764
2765                         if(layer != -1) {
2766                                 a = attribs->tottface++;
2767
2768                                 attribs->tface[a].array = tfdata->layers[layer].data;
2769                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2770                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2771                         }
2772                 }
2773                 else if(gattribs->layer[b].type == CD_MCOL) {
2774                         /* vertex colors */
2775                         if(gattribs->layer[b].name[0])
2776                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2777                                         gattribs->layer[b].name);
2778                         else
2779                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2780
2781                         if(layer != -1) {
2782                                 a = attribs->totmcol++;
2783
2784                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2785                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2786                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2787                         }
2788                 }
2789                 else if(gattribs->layer[b].type == CD_TANGENT) {
2790                         /* tangents */
2791                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2792
2793                         if(layer != -1) {
2794                                 attribs->tottang = 1;
2795
2796                                 attribs->tang.array = fdata->layers[layer].data;
2797                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2798                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2799                         }
2800                 }
2801                 else if(gattribs->layer[b].type == CD_ORCO) {
2802                         /* original coordinates */
2803                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2804
2805                         if(layer != -1) {
2806                                 attribs->totorco = 1;
2807
2808                                 attribs->orco.array = vdata->layers[layer].data;
2809                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2810                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2811                         }
2812                 }
2813         }
2814 }
2815