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