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