svn merge ^/trunk/blender -r43345:43381
[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 #include "limits.h"
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_array.h"
50 #include "BLI_pbvh.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_linklist.h"
53
54 #include "BKE_cdderivedmesh.h"
55 #include "BKE_displist.h"
56 #include "BKE_key.h"
57 #include "BKE_modifier.h"
58 #include "BKE_mesh.h"
59 #include "BKE_object.h"
60 #include "BKE_paint.h"
61 #include "BKE_texture.h"
62 #include "BKE_multires.h"
63 #include "BKE_armature.h"
64 #include "BKE_particle.h"
65 #include "BKE_tessmesh.h"
66 #include "BKE_bvhutils.h"
67 #include "BKE_deform.h"
68
69 #ifdef WITH_GAMEENGINE
70 #include "BKE_navmesh_conversion.h"
71 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
72 #endif
73
74 #include "BLO_sys_types.h" // for intptr_t support
75
76 #include "GL/glew.h"
77
78 #include "GPU_buffers.h"
79 #include "GPU_draw.h"
80 #include "GPU_extensions.h"
81 #include "GPU_material.h"
82
83 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
84
85 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
86 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
87
88 ///////////////////////////////////
89 ///////////////////////////////////
90
91 static MVert *dm_getVertArray(DerivedMesh *dm)
92 {
93         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
94
95         if (!mvert) {
96                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
97                         dm->getNumVerts(dm));
98                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
99                 dm->copyVertArray(dm, mvert);
100         }
101
102         return mvert;
103 }
104
105 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
106 {
107         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
108
109         if (!medge) {
110                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
111                         dm->getNumEdges(dm));
112                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
113                 dm->copyEdgeArray(dm, medge);
114         }
115
116         return medge;
117 }
118
119 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
120 {
121         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
122
123         if (!mface) {
124                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
125                         dm->getNumTessFaces(dm));
126                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
127                 dm->copyTessFaceArray(dm, mface);
128         }
129
130         return mface;
131 }
132
133 static MLoop *dm_getLoopArray(DerivedMesh *dm)
134 {
135         MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
136
137         if (!mloop) {
138                 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
139                         dm->getNumLoops(dm));
140                 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
141                 dm->copyLoopArray(dm, mloop);
142         }
143
144         return mloop;
145 }
146
147 static MPoly *dm_getPolyArray(DerivedMesh *dm)
148 {
149         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
150
151         if (!mpoly) {
152                 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
153                         dm->getNumPolys(dm));
154                 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
155                 dm->copyPolyArray(dm, mpoly);
156         }
157
158         return mpoly;
159 }
160
161 static MVert *dm_dupVertArray(DerivedMesh *dm)
162 {
163         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
164                                                          "dm_dupVertArray tmp");
165
166         if(tmp) dm->copyVertArray(dm, tmp);
167
168         return tmp;
169 }
170
171 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
172 {
173         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
174                                                          "dm_dupEdgeArray tmp");
175
176         if(tmp) dm->copyEdgeArray(dm, tmp);
177
178         return tmp;
179 }
180
181 static MFace *dm_dupFaceArray(DerivedMesh *dm)
182 {
183         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
184                                                          "dm_dupFaceArray tmp");
185
186         if(tmp) dm->copyTessFaceArray(dm, tmp);
187
188         return tmp;
189 }
190
191 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
192 {
193         MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumLoops(dm),
194                                                          "dm_dupLoopArray tmp");
195
196         if(tmp) dm->copyLoopArray(dm, tmp);
197
198         return tmp;
199 }
200
201 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
202 {
203         MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumPolys(dm),
204                                                          "dm_dupPolyArray tmp");
205
206         if(tmp) dm->copyPolyArray(dm, tmp);
207
208         return tmp;
209 }
210
211 static CustomData *dm_getVertCData(DerivedMesh *dm)
212 {
213         return &dm->vertData;
214 }
215
216 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
217 {
218         return &dm->edgeData;
219 }
220
221 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
222 {
223         return &dm->faceData;
224 }
225
226 static CustomData *dm_getLoopCData(DerivedMesh *dm)
227 {
228         return &dm->loopData;
229 }
230
231 static CustomData *dm_getPolyCData(DerivedMesh *dm)
232 {
233         return &dm->polyData;
234 }
235
236 void DM_init_funcs(DerivedMesh *dm)
237 {
238         /* default function implementations */
239         dm->getVertArray = dm_getVertArray;
240         dm->getEdgeArray = dm_getEdgeArray;
241         dm->getTessFaceArray = dm_getTessFaceArray;
242         dm->getLoopArray = dm_getLoopArray;
243         dm->getPolyArray = dm_getPolyArray;
244         dm->dupVertArray = dm_dupVertArray;
245         dm->dupEdgeArray = dm_dupEdgeArray;
246         dm->dupTessFaceArray = dm_dupFaceArray;
247         dm->dupLoopArray = dm_dupLoopArray;
248         dm->dupPolyArray = dm_dupPolyArray;
249
250         dm->getVertDataLayout = dm_getVertCData;
251         dm->getEdgeDataLayout = dm_getEdgeCData;
252         dm->getTessFaceDataLayout = dm_getTessFaceCData;
253         dm->getLoopDataLayout = dm_getLoopCData;
254         dm->getPolyDataLayout = dm_getPolyCData;
255
256         dm->getVertData = DM_get_vert_data;
257         dm->getEdgeData = DM_get_edge_data;
258         dm->getTessFaceData = DM_get_tessface_data;
259         dm->getVertDataArray = DM_get_vert_data_layer;
260         dm->getEdgeDataArray = DM_get_edge_data_layer;
261         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
262
263         bvhcache_init(&dm->bvhCache);
264 }
265
266 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
267              int numTessFaces, int numLoops, int numPolys)
268 {
269         dm->type = type;
270         dm->numVertData = numVerts;
271         dm->numEdgeData = numEdges;
272         dm->numTessFaceData = numTessFaces;
273         dm->numLoopData = numLoops;
274         dm->numPolyData = numPolys;
275
276         DM_init_funcs(dm);
277         
278         dm->needsFree = 1;
279         dm->auto_bump_scale = -1.0f;
280 }
281
282 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
283                       int numVerts, int numEdges, int numTessFaces,
284                       int numLoops, int numPolys)
285 {
286         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
287                                         CD_CALLOC, numVerts);
288         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
289                                         CD_CALLOC, numEdges);
290         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
291                                         CD_CALLOC, numTessFaces);
292         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
293                         CD_CALLOC, numLoops);
294         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
295                         CD_CALLOC, numPolys);
296
297         dm->type = type;
298         dm->numVertData = numVerts;
299         dm->numEdgeData = numEdges;
300         dm->numTessFaceData = numTessFaces;
301         dm->numLoopData = numLoops;
302         dm->numPolyData = numPolys;
303
304         DM_init_funcs(dm);
305
306         dm->needsFree = 1;
307 }
308
309 int DM_release(DerivedMesh *dm)
310 {
311         if (dm->needsFree) {
312                 bvhcache_free(&dm->bvhCache);
313                 GPU_drawobject_free( dm );
314                 CustomData_free(&dm->vertData, dm->numVertData);
315                 CustomData_free(&dm->edgeData, dm->numEdgeData);
316                 CustomData_free(&dm->faceData, dm->numTessFaceData);
317                 CustomData_free(&dm->loopData, dm->numLoopData);
318                 CustomData_free(&dm->polyData, dm->numPolyData);
319
320                 return 1;
321         }
322         else {
323                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
324                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
325                 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
326                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
327                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
328
329                 return 0;
330         }
331 }
332
333 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
334 {
335         CustomData_free(&target->loopData, source->numLoopData);
336         CustomData_free(&target->polyData, source->numPolyData);
337
338         CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
339         CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
340
341         target->numLoopData = source->numLoopData;
342         target->numPolyData = source->numPolyData;
343
344         if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
345                 MPoly *mpoly;
346                 MLoop *mloop;
347
348                 mloop = source->dupLoopArray(source);
349                 mpoly = source->dupPolyArray(source);
350                 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
351                 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
352         }
353 }
354
355 /* note: until all modifiers can take MPoly's as input,
356  * use this at the start of modifiers  */
357 void DM_ensure_tessface(DerivedMesh *dm)
358 {
359         const int numTessFaces = dm->getNumTessFaces(dm);
360         const int numPolys =     dm->getNumPolys(dm);
361
362         if ( (numTessFaces == 0) && (numPolys != 0)) {
363                 dm->recalcTesselation(dm);
364
365                 if (dm->getNumTessFaces(dm)) {
366                         printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
367                                __func__, numPolys, dm->type);
368                 }
369                 else {
370                         printf("info %s: polys -> ngons calculated\n", __func__);
371                 }
372         }
373 }
374
375 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
376 {
377         /* dm might depend on me, so we need to do everything with a local copy */
378         Mesh tmp = *me;
379         int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
380         int did_shapekeys=0;
381         
382         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
383         memset(&tmp.edata, 0, sizeof(tmp.edata));
384         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
385         memset(&tmp.ldata, 0, sizeof(tmp.ldata));
386         memset(&tmp.pdata, 0, sizeof(tmp.pdata));
387
388         totvert = tmp.totvert = dm->getNumVerts(dm);
389         totedge = tmp.totedge = dm->getNumEdges(dm);
390         totloop = tmp.totloop = dm->getNumLoops(dm);
391         totpoly = tmp.totpoly = dm->getNumPolys(dm);
392
393         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
394         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
395         CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
396         CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
397
398         if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
399                 KeyBlock *kb;
400                 int i=0;
401                 
402                 if (ob) {
403                         for (kb=me->key->block.first; kb; kb=kb->next, i++) {
404                                 if (i == ob->shapenr-1) {
405                                         i = kb->uid;
406                                         break;
407                                 }
408                         }
409                         
410                         if (!kb) {
411                                 printf("%s: error - could not find active shapekey %d!\n",
412                                        __func__, ob->shapenr-1);
413
414                                 i = INT_MAX;
415                         }
416                 } else {
417                         /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
418                         i = INT_MAX;
419                 }
420                 
421                 shapekey_layers_to_keyblocks(dm, me, i);
422                 did_shapekeys = 1;
423         }
424         
425         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
426            we set them here in case they are missing */
427         if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
428                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
429         if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
430                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
431         if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
432                 tmp.mloop = dm->dupLoopArray(dm);
433                 tmp.mpoly = dm->dupPolyArray(dm);
434
435                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
436                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
437         }
438
439         /* object had got displacement layer, should copy this layer to save sculpted data */
440         /* NOTE: maybe some other layers should be copied? nazgul */
441         if(CustomData_has_layer(&me->ldata, CD_MDISPS)) {
442                 if (totloop == me->totloop) {
443                         MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
444                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
445                 }
446         }
447
448         /* yes, must be before _and_ after tesselate */
449         mesh_update_customdata_pointers(&tmp, TRUE);
450
451         tmp.totface = mesh_recalcTesselation(&tmp.fdata, &tmp.ldata, &tmp.pdata, tmp.mvert, tmp.totface, tmp.totloop, tmp.totpoly);
452
453         mesh_update_customdata_pointers(&tmp, TRUE);
454
455
456         CustomData_free(&me->vdata, me->totvert);
457         CustomData_free(&me->edata, me->totedge);
458         CustomData_free(&me->fdata, me->totface);
459         CustomData_free(&me->ldata, me->totloop);
460         CustomData_free(&me->pdata, me->totpoly);
461
462         /*  ok, this should now use new CD shapekey data,
463             which shouuld be fed through the modifier 
464                 stack*/
465         if(tmp.totvert != me->totvert && !did_shapekeys && me->key) {
466                 printf("YEEK! this should be recoded! Shape key loss!!!\n");
467                 if(tmp.key) tmp.key->id.us--;
468                 tmp.key = NULL;
469         }
470
471         *me = tmp;
472 }
473
474 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
475 {
476         int a, totvert = dm->getNumVerts(dm);
477         float *fp;
478         MVert *mvert;
479         
480         if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
481         
482         if(kb->data) MEM_freeN(kb->data);
483         kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
484         kb->totelem= totvert;
485         
486         fp= kb->data;
487         mvert=dm->getVertDataArray(dm, CD_MVERT);
488         
489         for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
490                 copy_v3_v3(fp, mvert->co);
491         }
492 }
493
494 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
495 {
496         CustomData_set_only_copy(&dm->vertData, mask);
497         CustomData_set_only_copy(&dm->edgeData, mask);
498         CustomData_set_only_copy(&dm->faceData, mask);
499 }
500
501 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
502 {
503         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
504 }
505
506 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
507 {
508         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
509 }
510
511 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
512 {
513         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
514 }
515
516 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
517 {
518         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
519 }
520
521 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
522 {
523         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
524 }
525
526 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
527 {
528         return CustomData_get(&dm->vertData, index, type);
529 }
530
531 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
532 {
533         return CustomData_get(&dm->edgeData, index, type);
534 }
535
536 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
537 {
538         return CustomData_get(&dm->faceData, index, type);
539 }
540
541 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
542 {
543         if(type == CD_MVERT)
544                 return dm->getVertArray(dm);
545
546         return CustomData_get_layer(&dm->vertData, type);
547 }
548
549 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
550 {
551         if(type == CD_MEDGE)
552                 return dm->getEdgeArray(dm);
553
554         return CustomData_get_layer(&dm->edgeData, type);
555 }
556
557 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
558 {
559         if (type == CD_MFACE)
560                 return dm->getTessFaceArray(dm);
561
562         return CustomData_get_layer(&dm->faceData, type);
563 }
564
565 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
566 {
567         return CustomData_get_layer(&dm->polyData, type);
568 }
569
570 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
571 {
572         CustomData_set(&dm->vertData, index, type, data);
573 }
574
575 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
576 {
577         CustomData_set(&dm->edgeData, index, type, data);
578 }
579
580 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
581 {
582         CustomData_set(&dm->faceData, index, type, data);
583 }
584
585 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
586                                            int source_index, int dest_index, int count)
587 {
588         CustomData_copy_data(&source->vertData, &dest->vertData,
589                                                  source_index, dest_index, count);
590 }
591
592 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
593                                            int source_index, int dest_index, int count)
594 {
595         CustomData_copy_data(&source->edgeData, &dest->edgeData,
596                                                  source_index, dest_index, count);
597 }
598
599 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
600                                            int source_index, int dest_index, int count)
601 {
602         CustomData_copy_data(&source->faceData, &dest->faceData,
603                                                  source_index, dest_index, count);
604 }
605
606 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
607                        int source_index, int dest_index, int count)
608 {
609         CustomData_copy_data(&source->loopData, &dest->loopData,
610                              source_index, dest_index, count);
611 }
612
613 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
614                        int source_index, int dest_index, int count)
615 {
616         CustomData_copy_data(&source->polyData, &dest->polyData,
617                              source_index, dest_index, count);
618 }
619
620 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
621 {
622         CustomData_free_elem(&dm->vertData, index, count);
623 }
624
625 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
626 {
627         CustomData_free_elem(&dm->edgeData, index, count);
628 }
629
630 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
631 {
632         CustomData_free_elem(&dm->faceData, index, count);
633 }
634
635 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
636 {
637         CustomData_free_elem(&dm->loopData, index, count);
638 }
639
640 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
641 {
642         CustomData_free_elem(&dm->polyData, index, count);
643 }
644
645 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
646                                                  int *src_indices, float *weights,
647                                                  int count, int dest_index)
648 {
649         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
650                                           weights, NULL, count, dest_index);
651 }
652
653 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
654                                                  int *src_indices,
655                                                  float *weights, EdgeVertWeight *vert_weights,
656                                                  int count, int dest_index)
657 {
658         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
659                                           weights, (float*)vert_weights, count, dest_index);
660 }
661
662 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
663                                                  int *src_indices,
664                                                  float *weights, FaceVertWeight *vert_weights,
665                                                  int count, int dest_index)
666 {
667         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
668                                           weights, (float*)vert_weights, count, dest_index);
669 }
670
671 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
672 {
673         CustomData_swap(&dm->faceData, index, corner_indices);
674 }
675
676 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
677                          int *src_indices,
678                          float *weights, int count, int dest_index)
679 {
680         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
681                           weights, NULL, count, dest_index);
682 }
683
684 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
685                          int *src_indices,
686                          float *weights, int count, int dest_index)
687 {
688         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
689                           weights, NULL, count, dest_index);
690 }
691
692 ///
693 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
694 {
695         DerivedMesh *dm = CDDM_from_mesh(me, ob);
696         
697         if(!dm)
698                 return NULL;
699         
700         if (vertCos)
701                 CDDM_apply_vert_coords(dm, vertCos);
702
703         CDDM_calc_normals_mapping(dm);
704
705         return dm;
706 }
707
708 /***/
709
710 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
711         ModifierData *md, int build_shapekey_layers)
712 {
713         Mesh *me = ob->data;
714         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
715         DerivedMesh *dm;
716
717         md->scene= scene;
718         
719         if (!(md->mode&eModifierMode_Realtime)) return NULL;
720         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
721         
722         if (build_shapekey_layers && me->key && ob->shapenr <= BLI_countlist(&me->key->block)) {
723                 key_to_mesh(BLI_findlink(&me->key->block, ob->shapenr-1), me);
724         }
725         
726         if (mti->type==eModifierTypeType_OnlyDeform) {
727                 int numVerts;
728                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
729
730                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
731                 dm = mesh_create_derived(me, ob, deformedVerts);
732
733                 if (build_shapekey_layers)
734                         add_shapekey_layers(dm, me, ob);
735                 
736                 MEM_freeN(deformedVerts);
737         } else {
738                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
739
740                 if (build_shapekey_layers)
741                         add_shapekey_layers(tdm, me, ob);
742                 
743                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
744
745                 if(tdm != dm) tdm->release(tdm);
746         }
747
748         return dm;
749 }
750
751 static float *get_editbmesh_orco_verts(BMEditMesh *em)
752 {
753         BMIter iter;
754         BMVert *eve;
755         float *orco;
756         int a, totvert;
757
758         /* these may not really be the orco's, but it's only for preview.
759          * could be solver better once, but isn't simple */
760
761         totvert= em->bm->totvert;
762         
763         orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
764
765         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
766         for (a=0; eve; eve=BMIter_Step(&iter), a+=3) {
767                 copy_v3_v3(orco+a, eve->co);
768         }
769         
770         return orco;
771 }
772
773 /* orco custom data layer */
774 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
775 {
776         *free= 0;
777
778         if(layer == CD_ORCO) {
779                 /* get original coordinates */
780                 *free= 1;
781
782                 if(em)
783                         return (float(*)[3])get_editbmesh_orco_verts(em);
784                 else
785                         return (float(*)[3])get_mesh_orco_verts(ob);
786         }
787         else if(layer == CD_CLOTH_ORCO) {
788                 /* apply shape key for cloth, this should really be solved
789                    by a more flexible customdata system, but not simple */
790                 if(!em) {
791                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
792                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
793
794                         if(kb->data)
795                                 return kb->data;
796                 }
797
798                 return NULL;
799         }
800
801         return NULL;
802 }
803
804 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
805 {
806         DerivedMesh *dm;
807         float (*orco)[3];
808         int free;
809
810         if(em) dm= CDDM_from_BMEditMesh(em, me, 0);
811         else dm= CDDM_from_mesh(me, ob);
812
813         orco= get_orco_coords_dm(ob, em, layer, &free);
814
815         if(orco) {
816                 CDDM_apply_vert_coords(dm, orco);
817                 if(free) MEM_freeN(orco);
818         }
819
820         CDDM_calc_normals_mapping(dm);
821
822         return dm;
823 }
824
825 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
826                                                 DerivedMesh *orcodm, int layer)
827 {
828         float (*orco)[3], (*layerorco)[3];
829         int totvert, free;
830
831         totvert= dm->getNumVerts(dm);
832
833         if(orcodm) {
834                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
835                 free= 1;
836
837                 if(orcodm->getNumVerts(orcodm) == totvert)
838                         orcodm->getVertCos(orcodm, orco);
839                 else
840                         dm->getVertCos(dm, orco);
841         }
842         else
843                 orco= get_orco_coords_dm(ob, em, layer, &free);
844
845         if(orco) {
846                 if(layer == CD_ORCO)
847                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
848
849                 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
850                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
851                         layerorco = DM_get_vert_data_layer(dm, layer);
852                 }
853
854                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
855                 if(free) MEM_freeN(orco);
856         }
857 }
858
859 /* weight paint colors */
860
861 /* Something of a hack, at the moment deal with weightpaint
862  * by tucking into colors during modifier eval, only in
863  * wpaint mode. Works ok but need to make sure recalc
864  * happens on enter/exit wpaint.
865  */
866
867 void weight_to_rgb(float r_rgb[3], const float weight)
868 {
869         const float blend= ((weight/2.0f)+0.5f);
870
871         if (weight<=0.25f){     // blue->cyan
872                 r_rgb[0]= 0.0f;
873                 r_rgb[1]= blend*weight*4.0f;
874                 r_rgb[2]= blend;
875         }
876         else if (weight<=0.50f){        // cyan->green
877                 r_rgb[0]= 0.0f;
878                 r_rgb[1]= blend;
879                 r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
880         }
881         else if (weight <= 0.75f){      // green->yellow
882                 r_rgb[0]= blend * ((weight-0.50f)*4.0f);
883                 r_rgb[1]= blend;
884                 r_rgb[2]= 0.0f;
885         }
886         else if (weight <= 1.0f){ // yellow->red
887                 r_rgb[0]= blend;
888                 r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
889                 r_rgb[2]= 0.0f;
890         }
891         else {
892                 /* exceptional value, unclamped or nan,
893                  * avoid uninitialized memory use */
894                 r_rgb[0]= 1.0f;
895                 r_rgb[1]= 0.0f;
896                 r_rgb[2]= 1.0f;
897         }
898 }
899
900 /* draw_flag's for calc_weightpaint_vert_color */
901 enum {
902         CALC_WP_MULTIPAINT= (1<<0),
903         CALC_WP_AUTO_NORMALIZE= (1<<1)
904 };
905
906 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
907 {
908         float colf[4];
909
910         if(coba) do_colorband(coba, input, colf);
911         else     weight_to_rgb(colf, input);
912
913         r_col[3] = (unsigned char)(colf[0] * 255.0f);
914         r_col[2] = (unsigned char)(colf[1] * 255.0f);
915         r_col[1] = (unsigned char)(colf[2] * 255.0f);
916         r_col[0] = 255;
917 }
918
919
920 static void calc_weightpaint_vert_color(
921         unsigned char r_col[4],
922         MDeformVert *dv, ColorBand *coba,
923         const int defbase_tot, const int defbase_act,
924         const char *dg_flags,
925         const int selected, const int draw_flag)
926 {
927         float input = 0.0f;
928         
929         int make_black= FALSE;
930
931         if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
932                 int was_a_nonzero= FALSE;
933                 unsigned int i;
934
935                 MDeformWeight *dw= dv->dw;
936                 for (i = dv->totweight; i != 0; i--, dw++) {
937                         /* in multipaint, get the average if auto normalize is inactive
938                          * get the sum if it is active */
939                         if (dw->def_nr < defbase_tot) {
940                                 if (dg_flags[dw->def_nr]) {
941                                         if (dw->weight) {
942                                                 input += dw->weight;
943                                                 was_a_nonzero= TRUE;
944                                         }
945                                 }
946                         }
947                 }
948
949                 /* make it black if the selected groups have no weight on a vertex */
950                 if (was_a_nonzero == FALSE) {
951                         make_black = TRUE;
952                 }
953                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
954                         input /= selected; /* get the average */
955                 }
956         }
957         else {
958                 /* default, non tricky behavior */
959                 input= defvert_find_weight(dv, defbase_act);
960         }
961
962         if (make_black) { /* TODO, theme color */
963                 r_col[3] = 0;
964                 r_col[2] = 0;
965                 r_col[1] = 0;
966                 r_col[0] = 255;
967         }
968         else {
969                 CLAMP(input, 0.0f, 1.0f);
970                 weightpaint_color(r_col, coba, input);
971         }
972 }
973
974 static ColorBand *stored_cb= NULL;
975
976 void vDM_ColorBand_store(ColorBand *coba)
977 {
978         stored_cb= coba;
979 }
980
981 /* return an array of vertex weight colors, caller must free.
982  *
983  * note that we could save some memory and allocate RGB only but then we'd need to
984  * re-arrange the colors when copying to the face since MCol has odd ordering,
985  * so leave this as is - campbell */
986 static unsigned char *calc_weightpaint_vert_array(Object *ob, int const draw_flag, ColorBand *coba)
987 {
988         Mesh *me = ob->data;
989         unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * me->totvert * 4, "weightmap_v");
990
991         if (me->dvert) {
992                 unsigned char *wc = wtcol_v;
993                 MDeformVert *dv= me->dvert;
994                 unsigned int i;
995
996                 /* varisbles for multipaint */
997                 const int defbase_tot = BLI_countlist(&ob->defbase);
998                 const int defbase_act = ob->actdef-1;
999                 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
1000                 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
1001                 /* const int unselected = defbase_tot - selected; */ /* UNUSED */
1002
1003                 for (i = me->totvert; i != 0; i--, wc += 4, dv++) {
1004                         calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
1005                 }
1006
1007                 MEM_freeN(dg_flags);
1008         }
1009         else {
1010                 int col_i;
1011                 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
1012                 fill_vn_i((int *)wtcol_v, me->totvert, col_i);
1013         }
1014
1015         return wtcol_v;
1016 }
1017
1018 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
1019 {
1020         ColorBand *coba= stored_cb;     /* warning, not a local var */
1021         unsigned char *wtcol_v = calc_weightpaint_vert_array(ob, draw_flag, coba);
1022         unsigned char *wtcol_f;
1023         unsigned char(*wtcol_l)[4] = NULL;
1024         BLI_array_declare(wtcol_l);
1025         MFace *mf = dm->getTessFaceArray(dm);
1026         MLoop *mloop = dm->getLoopArray(dm), *ml;
1027         MPoly *mp = dm->getPolyArray(dm);
1028         int i, j, totface=dm->getNumTessFaces(dm), totloop;
1029         int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
1030         unsigned char *wtcol_f_step;
1031
1032         wtcol_f = MEM_mallocN(sizeof (unsigned char) * totface*4*4, "weightmap_f");
1033         wtcol_f_step = wtcol_f;
1034
1035         /*first add colors to the tesselation faces*/
1036         for (i=0; i<totface; i++, mf++, wtcol_f_step += (4 * 4)) {
1037                 /*origindex being NULL means we're operating on original mesh data*/
1038 #if 0
1039                 unsigned int fidx= mf->v4 ? 3:2;
1040
1041 #else   /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
1042                 unsigned int fidx;
1043                 if (mf->v4) {
1044                         fidx = 3;
1045                 }
1046                 else {
1047                         fidx = 2;
1048                         *(int *)(&wtcol_f_step[3 * 4]) = 0;
1049                 }
1050 #endif
1051
1052                 do {
1053                         copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
1054                                         (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
1055                 } while (fidx--);
1056         }
1057
1058         CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol_f, totface);
1059
1060         /*now add to loops, so the data can be passed through the modifier stack*/
1061         totloop = 0;
1062         for (i=0; i<dm->numPolyData; i++, mp++) {
1063                 ml = mloop + mp->loopstart;
1064
1065                 for (j=0; j<mp->totloop; j++, ml++, totloop++) {
1066                         BLI_array_growone(wtcol_l);
1067                         copy_v4_v4_char((char *)&wtcol_l[totloop],
1068                                         (char *)&wtcol_v[4 * (origIndex ? origIndex[ml->v] : ml->v)]);
1069                 }
1070         }
1071
1072         MEM_freeN(wtcol_v);
1073
1074         CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1075 }
1076
1077
1078 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1079 {
1080         KeyBlock *kb;
1081         int i, j, tot;
1082         
1083         if (!me->key)
1084                 return; 
1085         
1086         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1087         for (i=0; i<tot; i++) {
1088                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1089                 float (*cos)[3], (*kbcos)[3];
1090                 
1091                 for (kb=me->key->block.first; kb; kb=kb->next) {
1092                         if (kb->uid == layer->uid)
1093                                 break;
1094                 }
1095                 
1096                 if (!kb) {
1097                         kb = add_keyblock(me->key, layer->name);
1098                         kb->uid = layer->uid;
1099                 }
1100                 
1101                 if (kb->data)
1102                         MEM_freeN(kb->data);
1103                 
1104                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1105                 kb->totelem = dm->numVertData;
1106
1107                 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1108                 if (kb->uid == actshape_uid) {
1109                         MVert *mvert = dm->getVertArray(dm);
1110                         
1111                         for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1112                                 copy_v3_v3(*kbcos, mvert->co);
1113                         }
1114                 } else {
1115                         for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1116                                 copy_v3_v3(*kbcos, *cos);
1117                         }
1118                 }
1119         }
1120         
1121         for (kb=me->key->block.first; kb; kb=kb->next) {
1122                 if (kb->totelem != dm->numVertData) {
1123                         if (kb->data)
1124                                 MEM_freeN(kb->data);
1125                         
1126                         kb->totelem = dm->numVertData;
1127                         kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1128                         fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1129                 }
1130         }
1131 }
1132
1133 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1134 {
1135         KeyBlock *kb;
1136         Key *key = me->key;
1137         int a, b;
1138         
1139         if (!me->key)
1140                 return;
1141         
1142         if (dm->numVertData != me->totvert) {
1143                 printf("error in add_shapekey_layers: dm isn't the same size as me\n");
1144                 return;
1145         }
1146                 
1147         for (a=0, kb=key->block.first; kb; kb=kb->next, a++) {
1148                 float (*cos)[3] = CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_CALLOC, NULL, dm->numVertData, kb->name);
1149                 int ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, a);
1150                 
1151                 dm->vertData.layers[ci].uid = kb->uid;
1152                 if (kb->totelem != dm->numVertData) {
1153                         printf("error in add_shapekey_layers: totelem and totvert don't match");
1154                         continue;
1155                 }
1156                 
1157                 for (b=0; b<kb->totelem; b++, cos++) {
1158                         copy_v3_v3((float *)cos, ((float*)kb->data)+b*3);
1159                 }
1160         }
1161 }
1162
1163 /* new value for useDeform -1  (hack for the gameengine):
1164  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1165  * - don't apply the key
1166  * - apply deform modifiers and input vertexco
1167  */
1168 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1169                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1170                                                                 int useRenderParams, int useDeform,
1171                                                                 int needMapping, CustomDataMask dataMask, 
1172                                                                 int index, int useCache, int build_shapekey_layers)
1173 {
1174         Mesh *me = ob->data;
1175         ModifierData *firstmd, *md;
1176         LinkNode *datamasks, *curr;
1177         CustomDataMask mask, nextmask, append_mask = 0;
1178         float (*deformedVerts)[3] = NULL;
1179         DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1180         int numVerts = me->totvert;
1181         int required_mode;
1182         int isPrevDeform= FALSE;
1183         int skipVirtualArmature = (useDeform < 0);
1184         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1185         int has_multires = mmd != NULL, multires_applied = 0;
1186         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1187
1188         int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1189                         (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1190
1191         if(mmd && !mmd->sculptlvl)
1192                 has_multires = 0;
1193
1194         if(!skipVirtualArmature) {
1195                 firstmd = modifiers_getVirtualModifierList(ob);
1196         }
1197         else {
1198                 /* game engine exception */
1199                 firstmd = ob->modifiers.first;
1200                 if(firstmd && firstmd->type == eModifierType_Armature)
1201                         firstmd = firstmd->next;
1202         }
1203
1204         md = firstmd;
1205
1206         modifiers_clearErrors(ob);
1207
1208         if(useRenderParams) required_mode = eModifierMode_Render;
1209         else required_mode = eModifierMode_Realtime;
1210
1211         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1212         curr = datamasks;
1213
1214         if(deform_r) *deform_r = NULL;
1215         *final_r = NULL;
1216
1217         if(useDeform) {
1218                 if(inputVertexCos)
1219                         deformedVerts = inputVertexCos;
1220                 
1221                 /* Apply all leading deforming modifiers */
1222                 for(;md; md = md->next, curr = curr->next) {
1223                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1224
1225                         md->scene= scene;
1226                         
1227                         if(!modifier_isEnabled(scene, md, required_mode)) continue;
1228                         if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1229
1230                         if(mti->type == eModifierTypeType_OnlyDeform) {
1231                                 if(!deformedVerts)
1232                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1233
1234                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1235                         } else {
1236                                 break;
1237                         }
1238                         
1239                         /* grab modifiers until index i */
1240                         if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1241                                 break;
1242                 }
1243
1244                 /* Result of all leading deforming modifiers is cached for
1245                  * places that wish to use the original mesh but with deformed
1246                  * coordinates (vpaint, etc.)
1247                  */
1248                 if (deform_r) {
1249                         *deform_r = CDDM_from_mesh(me, ob);
1250                          
1251                         if (build_shapekey_layers)
1252                                 add_shapekey_layers(dm, me, ob);
1253                         
1254                         if(deformedVerts) {
1255                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1256                                 CDDM_calc_normals_mapping(*deform_r);
1257                         }
1258                 }
1259         } else {
1260                 /* default behaviour for meshes */
1261                 if(inputVertexCos)
1262                         deformedVerts = inputVertexCos;
1263                 else
1264                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1265         }
1266
1267
1268         /* Now apply all remaining modifiers. If useDeform is off then skip
1269          * OnlyDeform ones. 
1270          */
1271         dm = NULL;
1272         orcodm = NULL;
1273         clothorcodm = NULL;
1274
1275         for(;md; md = md->next, curr = curr->next) {
1276                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1277
1278                 md->scene= scene;
1279
1280                 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1281                 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1282                 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1283                         modifier_setError(md, "Modifier requires original data, bad stack position.");
1284                         continue;
1285                 }
1286                 if(sculpt_mode && (!has_multires || multires_applied)) {
1287                         int unsupported= 0;
1288
1289                         if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1290                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1291
1292                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1293                         unsupported|= multires_applied;
1294
1295                         if(unsupported) {
1296                                 modifier_setError(md, "Not supported in sculpt mode.");
1297                                 continue;
1298                         }
1299                 }
1300                 if(needMapping && !modifier_supportsMapping(md)) continue;
1301                 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1302
1303                 /* add an orco layer if needed by this modifier */
1304                 if(mti->requiredDataMask)
1305                         mask = mti->requiredDataMask(ob, md);
1306                 else
1307                         mask = 0;
1308
1309                 if(dm && (mask & CD_MASK_ORCO))
1310                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1311
1312                 /* How to apply modifier depends on (a) what we already have as
1313                  * a result of previous modifiers (could be a DerivedMesh or just
1314                  * deformed vertices) and (b) what type the modifier is.
1315                  */
1316
1317                 if(mti->type == eModifierTypeType_OnlyDeform) {
1318                         /* No existing verts to deform, need to build them. */
1319                         if(!deformedVerts) {
1320                                 if(dm) {
1321                                         /* Deforming a derived mesh, read the vertex locations
1322                                          * out of the mesh and deform them. Once done with this
1323                                          * run of deformers verts will be written back.
1324                                          */
1325                                         numVerts = dm->getNumVerts(dm);
1326                                         deformedVerts =
1327                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1328                                         dm->getVertCos(dm, deformedVerts);
1329                                 } else {
1330                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1331                                 }
1332                         }
1333
1334                         /* if this is not the last modifier in the stack then recalculate the normals
1335                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1336                         if(isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1337                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1338                                 if(dm && dm->type == DM_TYPE_CDDM) {
1339                                         CDDM_apply_vert_coords(dm, deformedVerts);
1340                                         CDDM_calc_normals_mapping(dm);
1341                                 }
1342                         }
1343
1344                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1345                 } else {
1346                         DerivedMesh *ndm;
1347
1348                         /* determine which data layers are needed by following modifiers */
1349                         if(curr->next)
1350                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1351                         else
1352                                 nextmask= dataMask;
1353
1354                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1355                         if(dm) {
1356                                 if(deformedVerts) {
1357                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1358                                         dm->release(dm);
1359                                         dm = tdm;
1360
1361                                         CDDM_apply_vert_coords(dm, deformedVerts);
1362                                         CDDM_calc_normals_mapping(dm);
1363                                 }
1364                         } else {
1365                                 dm = CDDM_from_mesh(me, ob);
1366
1367                                 if (build_shapekey_layers)
1368                                         add_shapekey_layers(dm, me, ob);
1369
1370                                 if(deformedVerts) {
1371                                         CDDM_apply_vert_coords(dm, deformedVerts);
1372                                         CDDM_calc_normals_mapping(dm);
1373                                 }
1374
1375                                 /* Constructive modifiers need to have an origindex
1376                                  * otherwise they wont have anywhere to copy the data from.
1377                                  *
1378                                  * Also create ORIGINDEX data if any of the following modifiers
1379                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1380                                  * data by using generic DM_copy_vert_data() functions.
1381                                  */
1382                                 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1383                                         /* calc */
1384                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1385                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1386                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1387
1388                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1389                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1390                                         range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1391                                 }
1392
1393                                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1394                                         add_weight_mcol_dm(ob, dm, draw_flag);
1395
1396                         }
1397
1398                         
1399                         /* set the DerivedMesh to only copy needed data */
1400                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1401                         /* needMapping check here fixes bug [#28112], otherwise its
1402                          * possible that it wont be copied */
1403                         mask |= append_mask;
1404                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1405                         
1406                         /* add cloth rest shape key if need */
1407                         if(mask & CD_MASK_CLOTH_ORCO)
1408                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1409
1410                         /* add an origspace layer if needed */
1411                         if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1412                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1413                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1414
1415                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1416
1417                         if(ndm) {
1418                                 /* if the modifier returned a new dm, release the old one */
1419                                 if(dm && dm != ndm) dm->release(dm);
1420
1421                                 dm = ndm;
1422
1423                                 if(deformedVerts) {
1424                                         if(deformedVerts != inputVertexCos)
1425                                                 MEM_freeN(deformedVerts);
1426
1427                                         deformedVerts = NULL;
1428                                 }
1429                         } 
1430
1431                         /* create an orco derivedmesh in parallel */
1432                         if(nextmask & CD_MASK_ORCO) {
1433                                 if(!orcodm)
1434                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1435
1436                                 nextmask &= ~CD_MASK_ORCO;
1437                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1438                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1439
1440                                 if(ndm) {
1441                                         /* if the modifier returned a new dm, release the old one */
1442                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1443                                         orcodm = ndm;
1444                                 }
1445                         }
1446
1447                         /* create cloth orco derivedmesh in parallel */
1448                         if(nextmask & CD_MASK_CLOTH_ORCO) {
1449                                 if(!clothorcodm)
1450                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1451
1452                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1453                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1454                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1455
1456                                 if(ndm) {
1457                                         /* if the modifier returned a new dm, release the old one */
1458                                         if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1459                                         clothorcodm = ndm;
1460                                 }
1461                         }
1462
1463                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1464                         if (md->type == eModifierType_DynamicPaint)
1465                                 append_mask |= CD_MASK_WEIGHT_MCOL;
1466                 }
1467
1468                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1469
1470                 /* grab modifiers until index i */
1471                 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1472                         break;
1473
1474                 if(sculpt_mode && md->type == eModifierType_Multires)
1475                         multires_applied = 1;
1476         }
1477
1478         for(md=firstmd; md; md=md->next)
1479                 modifier_freeTemporaryData(md);
1480
1481         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1482          * need to apply these back onto the DerivedMesh. If we have no
1483          * DerivedMesh then we need to build one.
1484          */
1485         if(dm && deformedVerts) {
1486                 finaldm = CDDM_copy(dm, 0);
1487
1488                 dm->release(dm);
1489
1490                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1491                 CDDM_calc_normals_mapping(finaldm);
1492
1493                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1494                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1495         } else if(dm) {
1496                 finaldm = dm;
1497         } else {
1498                 int recalc_normals= 0;
1499
1500                 finaldm = CDDM_from_mesh(me, ob);
1501                 
1502                 if(build_shapekey_layers) {
1503                         add_shapekey_layers(finaldm, me, ob);
1504                         recalc_normals= 1;
1505                 }
1506                 
1507                 if(deformedVerts) {
1508                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1509                         recalc_normals= 1;
1510                 }
1511
1512                 if(recalc_normals)
1513                         CDDM_calc_normals_mapping(finaldm);
1514                 
1515                 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1516                         add_weight_mcol_dm(ob, finaldm, draw_flag);
1517         }
1518
1519         /* add an orco layer if needed */
1520         if(dataMask & CD_MASK_ORCO) {
1521                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1522
1523                 if(deform_r && *deform_r)
1524                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1525         }
1526
1527 #ifdef WITH_GAMEENGINE
1528         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1529         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1530                 DerivedMesh *tdm;
1531                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1532                 if (finaldm != tdm) {
1533                         finaldm->release(finaldm);
1534                         finaldm= tdm;
1535                 }
1536         }
1537 #endif /* WITH_GAMEENGINE */
1538
1539
1540         /* --------------------------------------------------------------------- */
1541         /* Re-tesselation is necessary to push render data (uvs, textures, colors)
1542          * from loops and polys onto the tessfaces. This may be currently be
1543          * redundantin cases where the render mode doesn't use these inputs, but
1544          * ideally eventually tesselation would happen on-demand, and this is one
1545          * of the primary places it would be needed. */
1546         finaldm->recalcTesselation(finaldm);
1547         /* if we have no modifiers applied we'lll still want the tessface normals
1548          * to be calculated from the polygon noramals,
1549          * 'CDDM_calc_normals_mapping' checks for this case - campbell */
1550         finaldm->calcNormals(finaldm);
1551         /* Need to watch this, it can cause issues, see bug [#29338]             */
1552         /* take care with this block, we really need testing frameworks          */
1553         /* --------------------------------------------------------------------- */
1554
1555
1556         *final_r = finaldm;
1557
1558         if(orcodm)
1559                 orcodm->release(orcodm);
1560         if(clothorcodm)
1561                 clothorcodm->release(clothorcodm);
1562
1563         if(deformedVerts && deformedVerts != inputVertexCos)
1564                 MEM_freeN(deformedVerts);
1565
1566         BLI_linklist_free(datamasks, NULL);
1567 }
1568
1569 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1570 {
1571         int i, numVerts = *numVerts_r = em->bm->totvert;
1572         float (*cos)[3];
1573         BMIter iter;
1574         BMVert *eve;
1575
1576         cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1577
1578         eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1579         for (i=0; eve; eve=BMIter_Step(&iter), i++) {
1580                 copy_v3_v3(cos[i], eve->co);
1581         }
1582
1583         return cos;
1584 }
1585
1586 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1587 {
1588         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1589         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1590
1591         if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1592         if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1593                 modifier_setError(md, "Modifier requires original data, bad stack position.");
1594                 return 0;
1595         }
1596         
1597         return 1;
1598 }
1599
1600 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1601                                                                         DerivedMesh **final_r,
1602                                                                         CustomDataMask dataMask)
1603 {
1604         ModifierData *md;
1605         float (*deformedVerts)[3] = NULL;
1606         CustomDataMask mask;
1607         DerivedMesh *dm, *orcodm = NULL;
1608         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1609         LinkNode *datamasks, *curr;
1610         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1611
1612         modifiers_clearErrors(ob);
1613
1614         if(cage_r && cageIndex == -1) {
1615                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1616         }
1617
1618         dm = NULL;
1619         md = modifiers_getVirtualModifierList(ob);
1620
1621         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1622
1623         curr = datamasks;
1624         for(i = 0; md; i++, md = md->next, curr = curr->next) {
1625                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1626
1627                 md->scene= scene;
1628                 
1629                 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1630                         continue;
1631
1632                 /* add an orco layer if needed by this modifier */
1633                 if(dm && mti->requiredDataMask) {
1634                         mask = mti->requiredDataMask(ob, md);
1635                         if(mask & CD_MASK_ORCO)
1636                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1637                 }
1638
1639                 /* How to apply modifier depends on (a) what we already have as
1640                  * a result of previous modifiers (could be a DerivedMesh or just
1641                  * deformed vertices) and (b) what type the modifier is.
1642                  */
1643
1644                 if(mti->type == eModifierTypeType_OnlyDeform) {
1645                         /* No existing verts to deform, need to build them. */
1646                         if(!deformedVerts) {
1647                                 if(dm) {
1648                                         /* Deforming a derived mesh, read the vertex locations
1649                                          * out of the mesh and deform them. Once done with this
1650                                          * run of deformers verts will be written back.
1651                                          */
1652                                         numVerts = dm->getNumVerts(dm);
1653                                         deformedVerts =
1654                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1655                                         dm->getVertCos(dm, deformedVerts);
1656                                 } else {
1657                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1658                                 }
1659                         }
1660
1661                         if (mti->deformVertsEM)
1662                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1663                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1664                 } else {
1665                         DerivedMesh *ndm;
1666
1667                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1668                         if(dm) {
1669                                 if(deformedVerts) {
1670                                         DerivedMesh *tdm = CDDM_copy(dm, 0);
1671                                         if(!(cage_r && dm == *cage_r)) dm->release(dm);
1672                                         dm = tdm;
1673
1674                                         CDDM_apply_vert_coords(dm, deformedVerts);
1675                                         CDDM_calc_normals_mapping(dm);
1676                                 } else if(cage_r && dm == *cage_r) {
1677                                         /* dm may be changed by this modifier, so we need to copy it
1678                                          */
1679                                         dm = CDDM_copy(dm, 0);
1680                                 }
1681
1682                         } else {
1683                                 dm = CDDM_from_BMEditMesh(em, ob->data, 0);
1684
1685                                 if(deformedVerts) {
1686                                         CDDM_apply_vert_coords(dm, deformedVerts);
1687                                         CDDM_calc_normals_mapping(dm);
1688                                 }
1689                         }
1690
1691                         /* create an orco derivedmesh in parallel */
1692                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1693                         if(mask & CD_MASK_ORCO) {
1694                                 if(!orcodm)
1695                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1696
1697                                 mask &= ~CD_MASK_ORCO;
1698                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1699
1700                                 if (mti->applyModifierEM)
1701                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1702                                 else
1703                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1704
1705                                 if(ndm) {
1706                                         /* if the modifier returned a new dm, release the old one */
1707                                         if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1708                                         orcodm = ndm;
1709                                 }
1710                         }
1711
1712                         /* set the DerivedMesh to only copy needed data */
1713                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1714
1715                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1716
1717                         if(mask & CD_MASK_ORIGSPACE)
1718                                 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1719                                         DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1720                         
1721                         if (mti->applyModifierEM)
1722                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1723                         else
1724                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1725
1726                         if (ndm) {
1727                                 if(dm && dm != ndm)
1728                                         dm->release(dm);
1729
1730                                 dm = ndm;
1731
1732                                 if (deformedVerts) {
1733                                         MEM_freeN(deformedVerts);
1734                                         deformedVerts = NULL;
1735                                 }
1736                         }
1737                 }
1738
1739                 if(cage_r && i == cageIndex) {
1740                         if(dm && deformedVerts) {
1741                                 *cage_r = CDDM_copy(dm, 0);
1742                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1743                         } else if(dm) {
1744                                 *cage_r = dm;
1745                         } else {
1746                                 *cage_r =
1747                                         getEditDerivedBMesh(em, ob,
1748                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1749                         }
1750                 }
1751         }
1752
1753         BLI_linklist_free(datamasks, NULL);
1754
1755         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1756          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1757          * then we need to build one.
1758          */
1759         if(dm && deformedVerts) {
1760                 *final_r = CDDM_copy(dm, 0);
1761
1762                 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1763
1764                 CDDM_apply_vert_coords(*final_r, deformedVerts);
1765                 CDDM_calc_normals_mapping(*final_r);
1766         } else if (dm) {
1767                 *final_r = dm;
1768                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1769         } else if (!deformedVerts && cage_r && *cage_r) {
1770                 *final_r = *cage_r;
1771                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1772         } else {
1773                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1774                 deformedVerts = NULL;
1775                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1776         }
1777
1778         /* add an orco layer if needed */
1779         if(dataMask & CD_MASK_ORCO)
1780                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1781
1782         if(orcodm)
1783                 orcodm->release(orcodm);
1784
1785         if(deformedVerts)
1786                 MEM_freeN(deformedVerts);
1787 }
1788
1789 static void clear_mesh_caches(Object *ob)
1790 {
1791         Mesh *me= ob->data;
1792
1793                 /* also serves as signal to remake texspace */
1794         if (ob->bb) {
1795                 MEM_freeN(ob->bb);
1796                 ob->bb = NULL;
1797         }
1798         if (me->bb) {
1799                 MEM_freeN(me->bb);
1800                 me->bb = NULL;
1801         }
1802
1803         freedisplist(&ob->disp);
1804
1805         if (ob->derivedFinal) {
1806                 ob->derivedFinal->needsFree = 1;
1807                 ob->derivedFinal->release(ob->derivedFinal);
1808                 ob->derivedFinal= NULL;
1809         }
1810         if (ob->derivedDeform) {
1811                 ob->derivedDeform->needsFree = 1;
1812                 ob->derivedDeform->release(ob->derivedDeform);
1813                 ob->derivedDeform= NULL;
1814         }
1815
1816         if(ob->sculpt) {
1817                 object_sculpt_modifiers_changed(ob);
1818         }
1819 }
1820
1821 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1822         int build_shapekey_layers)
1823 {
1824         Object *obact = scene->basact?scene->basact->object:NULL;
1825         int editing = paint_facesel_test(ob);
1826         /* weight paint and face select need original indices because of selection buffer drawing */
1827         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1828
1829         clear_mesh_caches(ob);
1830
1831         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1832                                                 &ob->derivedFinal, 0, 1,
1833                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
1834
1835         DM_set_object_boundbox (ob, ob->derivedFinal);
1836
1837         ob->derivedFinal->needsFree = 0;
1838         ob->derivedDeform->needsFree = 0;
1839         ob->lastDataMask = dataMask;
1840 }
1841
1842 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1843 {
1844         clear_mesh_caches(obedit);
1845
1846         if (em->derivedFinal) {
1847                 if (em->derivedFinal!=em->derivedCage) {
1848                         em->derivedFinal->needsFree = 1;
1849                         em->derivedFinal->release(em->derivedFinal);
1850                 }
1851                 em->derivedFinal = NULL;
1852         }
1853         if (em->derivedCage) {
1854                 em->derivedCage->needsFree = 1;
1855                 em->derivedCage->release(em->derivedCage);
1856                 em->derivedCage = NULL;
1857         }
1858
1859         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1860         DM_set_object_boundbox (obedit, em->derivedFinal);
1861
1862         em->lastDataMask = dataMask;
1863         em->derivedFinal->needsFree = 0;
1864         em->derivedCage->needsFree = 0;
1865 }
1866
1867 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
1868         CustomDataMask dataMask, int build_shapekey_layers)
1869 {
1870         if (em) {
1871                 editbmesh_build_data(scene, ob, em, dataMask);
1872         } else {
1873                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
1874         }
1875 }
1876
1877 /***/
1878
1879 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
1880 {
1881         /* if there's no derived mesh or the last data mask used doesn't include
1882          * the data we need, rebuild the derived mesh
1883          */
1884         if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
1885                 mesh_build_data(scene, ob, dataMask, 0);
1886
1887         return ob->derivedFinal;
1888 }
1889
1890 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
1891 {
1892         /* if there's no derived mesh or the last data mask used doesn't include
1893          * the data we need, rebuild the derived mesh
1894          */
1895         if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
1896                 mesh_build_data(scene, ob, dataMask, 0);
1897
1898         return ob->derivedDeform;
1899 }
1900
1901 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
1902 {
1903         DerivedMesh *final;
1904         
1905         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
1906
1907         return final;
1908 }
1909
1910 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
1911 {
1912         DerivedMesh *final;
1913         
1914         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
1915
1916         return final;
1917 }
1918
1919 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
1920 {
1921         DerivedMesh *final;
1922
1923         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
1924
1925         return final;
1926 }
1927
1928 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
1929                                                                                    CustomDataMask dataMask)
1930 {
1931         DerivedMesh *final;
1932         
1933         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
1934
1935         return final;
1936 }
1937
1938 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
1939                                                                                         CustomDataMask dataMask)
1940 {
1941         DerivedMesh *final;
1942         
1943         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
1944
1945         return final;
1946 }
1947
1948 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
1949                                                                                         CustomDataMask dataMask)
1950 {
1951         DerivedMesh *final;
1952         
1953         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
1954
1955         return final;
1956 }
1957
1958 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
1959                                                                                                   float (*vertCos)[3],
1960                                                                                                   CustomDataMask dataMask)
1961 {
1962         DerivedMesh *final;
1963
1964         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
1965
1966         return final;
1967 }
1968
1969 /***/
1970
1971 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
1972                                                                                                  CustomDataMask dataMask)
1973 {
1974         /* if there's no derived mesh or the last data mask used doesn't include
1975          * the data we need, rebuild the derived mesh
1976          */
1977         if(!em->derivedCage ||
1978            (em->lastDataMask & dataMask) != dataMask)
1979                 editbmesh_build_data(scene, obedit, em, dataMask);
1980
1981         *final_r = em->derivedFinal;
1982         return em->derivedCage;
1983 }
1984
1985 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1986 {
1987         /* if there's no derived mesh or the last data mask used doesn't include
1988          * the data we need, rebuild the derived mesh
1989          */
1990         if(!em->derivedCage ||
1991            (em->lastDataMask & dataMask) != dataMask)
1992                 editbmesh_build_data(scene, obedit, em, dataMask);
1993
1994         return em->derivedCage;
1995 }
1996
1997 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
1998 {
1999         return getEditDerivedBMesh(em, obedit, NULL);
2000 }
2001
2002
2003 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2004
2005 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2006 {
2007         float *vec = userData;
2008         
2009         vec+= 6*index;
2010
2011         /* check if we've been here before (normal should not be 0) */
2012         if(vec[3] || vec[4] || vec[5]) return;
2013
2014         copy_v3_v3(vec, co);
2015         vec+= 3;
2016         if(no_f) {
2017                 copy_v3_v3(vec, no_f);
2018         }
2019         else {
2020                 normal_short_to_float_v3(vec, no_s);
2021         }
2022 }
2023
2024 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2025 /* this is needed for all code using vertexgroups (no subsurf support) */
2026 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2027 /* in use now by vertex/weight paint and particle generating */
2028
2029 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2030 {
2031         Mesh *me= ob->data;
2032         DerivedMesh *dm;
2033         float *vertexcosnos;
2034         
2035         /* lets prevent crashing... */
2036         if(ob->type!=OB_MESH || me->totvert==0)
2037                 return NULL;
2038         
2039         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2040         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2041         
2042         if(dm->foreachMappedVert) {
2043                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2044         }
2045         else {
2046                 float *fp= vertexcosnos;
2047                 int a;
2048                 
2049                 for(a=0; a< me->totvert; a++, fp+=6) {
2050                         dm->getVertCo(dm, a, fp);
2051                         dm->getVertNo(dm, a, fp+3);
2052                 }
2053         }
2054         
2055         dm->release(dm);
2056         return vertexcosnos;
2057 }
2058
2059 /* ******************* GLSL ******************** */
2060
2061 typedef struct
2062 {
2063         float * precomputedFaceNormals;
2064         MTFace * mtface;        // texture coordinates
2065         MFace * mface;          // indices
2066         MVert * mvert;          // vertices & normals
2067         float (*orco)[3];
2068         float (*tangent)[4];    // destination
2069         int numTessFaces;
2070
2071 } SGLSLMeshToTangent;
2072
2073 // interface
2074 #include "mikktspace.h"
2075
2076 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2077 {
2078         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2079         return pMesh->numTessFaces;
2080 }
2081
2082 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2083 {
2084         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2085         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2086 }
2087
2088 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2089 {
2090         //assert(vert_index>=0 && vert_index<4);
2091         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2092         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2093         copy_v3_v3(fPos, co);
2094 }
2095
2096 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2097 {
2098         //assert(vert_index>=0 && vert_index<4);
2099         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2100
2101         if(pMesh->mtface!=NULL) {
2102                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2103                 fUV[0]=uv[0]; fUV[1]=uv[1];
2104         }
2105         else {
2106                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2107                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2108         }
2109 }
2110
2111 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2112 {
2113         //assert(vert_index>=0 && vert_index<4);
2114         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2115
2116         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2117         if(!smoothnormal) {     // flat
2118                 if(pMesh->precomputedFaceNormals) {
2119                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2120                 }
2121                 else {
2122                         MFace *mf= &pMesh->mface[face_num];
2123                         float *p0= pMesh->mvert[mf->v1].co;
2124                         float *p1= pMesh->mvert[mf->v2].co;
2125                         float *p2= pMesh->mvert[mf->v3].co;
2126
2127                         if(mf->v4) {
2128                                 float *p3 = pMesh->mvert[mf->v4].co;
2129                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2130                         }
2131                         else {
2132                                 normal_tri_v3(fNorm, p0, p1, p2);
2133                         }
2134                 }
2135         }
2136         else {
2137                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2138                 normal_short_to_float_v3(fNorm, no);
2139         }
2140 }
2141 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2142 {
2143         //assert(vert_index>=0 && vert_index<4);
2144         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2145         float * pRes = pMesh->tangent[4*face_num+iVert];
2146         copy_v3_v3(pRes, fvTangent);
2147         pRes[3]=fSign;
2148 }
2149
2150
2151 void DM_add_tangent_layer(DerivedMesh *dm)
2152 {
2153         /* mesh vars */
2154         MTFace *mtface, *tf;
2155         MFace *mface, *mf;
2156         MVert *mvert, *v1, *v2, *v3, *v4;
2157         MemArena *arena= NULL;
2158         VertexTangent **vtangents= NULL;
2159         float (*orco)[3]= NULL, (*tangent)[4];
2160         float *uv1, *uv2, *uv3, *uv4, *vtang;
2161         float fno[3], tang[3], uv[4][2];
2162         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2163         float *nors;
2164
2165         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2166                 return;
2167
2168         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2169
2170         /* check we have all the needed layers */
2171         totvert= dm->getNumVerts(dm);
2172         totface= dm->getNumTessFaces(dm);
2173
2174         mvert= dm->getVertArray(dm);
2175         mface= dm->getTessFaceArray(dm);
2176         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2177
2178         if(!mtface) {
2179                 orco= dm->getVertDataArray(dm, CD_ORCO);
2180                 if(!orco)
2181                         return;
2182         }
2183         
2184         /* create tangent layer */
2185         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2186         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2187         
2188         /* allocate some space */
2189         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2190         BLI_memarena_use_calloc(arena);
2191         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2192
2193         // new computation method
2194         iCalcNewMethod = 1;
2195         if(iCalcNewMethod != 0) {
2196                 SGLSLMeshToTangent mesh2tangent= {0};
2197                 SMikkTSpaceContext sContext= {0};
2198                 SMikkTSpaceInterface sInterface= {0};
2199
2200                 mesh2tangent.precomputedFaceNormals = nors;
2201                 mesh2tangent.mtface = mtface;
2202                 mesh2tangent.mface = mface;
2203                 mesh2tangent.mvert = mvert;
2204                 mesh2tangent.orco = orco;
2205                 mesh2tangent.tangent = tangent;
2206                 mesh2tangent.numTessFaces = totface;
2207
2208                 sContext.m_pUserData = &mesh2tangent;
2209                 sContext.m_pInterface = &sInterface;
2210                 sInterface.m_getNumFaces = GetNumFaces;
2211                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2212                 sInterface.m_getPosition = GetPosition;
2213                 sInterface.m_getTexCoord = GetTextureCoordinate;
2214                 sInterface.m_getNormal = GetNormal;
2215                 sInterface.m_setTSpaceBasic = SetTSpace;
2216
2217                 // 0 if failed
2218                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2219         }
2220
2221         if(!iCalcNewMethod) {
2222                 /* sum tangents at connected vertices */
2223                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2224                         v1= &mvert[mf->v1];
2225                         v2= &mvert[mf->v2];
2226                         v3= &mvert[mf->v3];
2227
2228                         if (mf->v4) {
2229                                 v4= &mvert[mf->v4];
2230                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2231                         }
2232                         else {
2233                                 v4= NULL;
2234                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2235                         }
2236                 
2237                         if(mtface) {
2238                                 uv1= tf->uv[0];
2239                                 uv2= tf->uv[1];
2240                                 uv3= tf->uv[2];
2241                                 uv4= tf->uv[3];
2242                         }
2243                         else {
2244                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2245                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2246                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2247                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2248                                 if(v4)
2249                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2250                         }
2251                 
2252                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2253                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2254                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2255                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2256                 
2257                         if(mf->v4) {
2258                                 v4= &mvert[mf->v4];
2259                         
2260                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2261                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2262                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2263                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2264                         }
2265                 }
2266         
2267                 /* write tangent to layer */
2268                 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2269                         len= (mf->v4)? 4 : 3; 
2270
2271                         if(mtface == NULL) {
2272                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2273                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2274                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2275                                 if(len==4)
2276                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2277                         }
2278                 
2279                         mf_vi[0]= mf->v1;
2280                         mf_vi[1]= mf->v2;
2281                         mf_vi[2]= mf->v3;
2282                         mf_vi[3]= mf->v4;
2283                 
2284                         for(j=0; j<len; j++) {
2285                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2286                                 normalize_v3_v3(tangent[j], vtang);
2287                                 ((float *) tangent[j])[3]=1.0f;
2288                         }
2289                 }
2290         }
2291         
2292         BLI_memarena_free(arena);
2293         MEM_freeN(vtangents);
2294 }
2295
2296 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2297 {
2298         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2299         int totface= dm->getNumTessFaces(dm);
2300
2301         MVert * mvert = dm->getVertArray(dm);
2302         MFace * mface = dm->getTessFaceArray(dm);
2303         MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2304
2305         if(mtface)
2306         {
2307                 double dsum = 0.0;
2308                 int nr_accumulated = 0;
2309                 int f;
2310
2311                 for ( f=0; f<totface; f++ )
2312                 {
2313                         {
2314                                 float * verts[4], * tex_coords[4];
2315                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2316                                 int i, is_degenerate;
2317
2318                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2319                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2320                                 if(nr_verts==4)
2321                                 {
2322                                         verts[3]=mvert[mface[f].v4].co;
2323                                         tex_coords[3]=mtface[f].uv[3];
2324                                 }
2325
2326                                 // discard degenerate faces
2327                                 is_degenerate = 0;
2328                                 if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2329                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2330                                 {
2331                                         is_degenerate = 1;
2332                                 }
2333
2334                                 // verify last vertex as well if this is a quad
2335                                 if ( is_degenerate==0 && nr_verts==4 )
2336                                 {
2337                                         if(     equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2338                                                 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2339                                         {
2340                                                 is_degenerate = 1;
2341                                         }
2342
2343                                         // verify the winding is consistent
2344                                         if ( is_degenerate==0 )
2345                                         {
2346                                                 float prev_edge[2];
2347                                                 int is_signed = 0;
2348                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2349
2350                                                 i = 0;
2351                                                 while ( is_degenerate==0 && i<4 )
2352                                                 {
2353                                                         float cur_edge[2], signed_area;
2354                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2355                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2356                                                         if ( i==0 ) is_signed = signed_area<0.0f ? 1 : 0;
2357                                                         else if((is_signed!=0)!=(signed_area<0.0f)) is_degenerate=1;
2358
2359                                                         if ( is_degenerate==0 )
2360                                                         {
2361                                                                 copy_v2_v2(prev_edge, cur_edge);
2362                                                                 ++i;
2363                                                         }
2364                                                 }
2365                                         }
2366                                 }
2367
2368                                 // proceed if not a degenerate face
2369                                 if ( is_degenerate==0 )
2370                                 {
2371                                         int nr_tris_to_pile=0;
2372                                         // quads split at shortest diagonal
2373                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
2374                                         if ( nr_verts==4 )
2375                                         {
2376                                                 float pos_len_diag0, pos_len_diag1;
2377                                                 float vtmp[3];
2378                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2379                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2380                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2381                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2382
2383                                                 if(pos_len_diag1<pos_len_diag0)
2384                                                         offs=1;         // alter split
2385                                                 else if(pos_len_diag0==pos_len_diag1)           // do UV check instead
2386                                                 {
2387                                                         float tex_len_diag0, tex_len_diag1;
2388
2389                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2390                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2391                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2392                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2393
2394                                                         if(tex_len_diag1<tex_len_diag0)
2395                                                         {
2396                                                                 offs=1;         // alter split
2397                                                         }
2398                                                 }
2399                                         }
2400                                         nr_tris_to_pile = nr_verts-2 ;
2401                                         if ( nr_tris_to_pile==1 || nr_tris_to_pile==2 )
2402                                         {
2403                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2404                                                 int t;
2405                                                 for ( t=0; t<nr_tris_to_pile; t++ )
2406                                                 {
2407                                                         float f2x_area_uv;
2408                                                         float * p0 = verts[indices[t*3+0]];
2409                                                         float * p1 = verts[indices[t*3+1]];
2410                                                         float * p2 = verts[indices[t*3+2]];
2411
2412                                                         float edge_t0[2], edge_t1[2];
2413                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2414                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2415
2416                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2417                                                         if ( f2x_area_uv>FLT_EPSILON )
2418                                                         {
2419                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2420                                                                 sub_v3_v3v3(v0, p1, p0);
2421                                                                 sub_v3_v3v3(v1, p2, p0);
2422                                                                 cross_v3_v3v3(norm, v0, v1);
2423
2424                                                                 f2x_surf_area = len_v3(norm);
2425                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
2426
2427                                                                 ++nr_accumulated;
2428                                                                 dsum += (double)(fsurf_ratio);
2429                                                         }
2430                                                 }
2431                                         }
2432                                 }
2433                         }
2434                 }
2435
2436                 // finalize
2437                 {
2438                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2439                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2440                         dm->auto_bump_scale = use_as_render_bump_scale;
2441                 }
2442         }
2443         else
2444         {
2445                 dm->auto_bump_scale = 1.0f;
2446         }
2447 }
2448
2449 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2450 {
2451         CustomData *vdata, *fdata, *tfdata = NULL;
2452         int a, b, layer;
2453
2454         /* From the layers requested by the GLSL shader, figure out which ones are
2455          * actually available for this derivedmesh, and retrieve the pointers */
2456
2457         memset(attribs, 0, sizeof(DMVertexAttribs));
2458
2459         vdata = &dm->vertData;
2460         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2461         
2462         /* calc auto bump scale if necessary */
2463         if(dm->auto_bump_scale<=0.0f)
2464                 DM_calc_auto_bump_scale(dm);
2465
2466         /* add a tangent layer if necessary */
2467         for(b = 0; b < gattribs->totlayer; b++)
2468                 if(gattribs->layer[b].type == CD_TANGENT)
2469                         if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2470                                 DM_add_tangent_layer(dm);
2471
2472         for(b = 0; b < gattribs->totlayer; b++) {
2473                 if(gattribs->layer[b].type == CD_MTFACE) {
2474                         /* uv coordinates */
2475                         if(gattribs->layer[b].name[0])
2476                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2477                                         gattribs->layer[b].name);
2478                         else
2479                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2480
2481                         if(layer != -1) {
2482                                 a = attribs->tottface++;
2483
2484                                 attribs->tface[a].array = tfdata->layers[layer].data;
2485                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2486                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2487                                 /* attribs->tface[a].glTexco = gattribs->layer[b].gltexco; */ /* BMESH_TODO, trunk has this but not bmesh, need to investigate whats going on here - campbell */
2488                         }
2489                         /* BMESH ONLY, may need to get this working?, otherwise remove */
2490                         /* else {
2491                                 int player;
2492                                 CustomData *pdata = dm->getPolyDataLayout(dm);
2493                                 
2494                                 if(gattribs->layer[b].name[0])
2495                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2496                                                 gattribs->layer[b].name);
2497                                 else
2498                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2499                                 
2500                                 if (player != -1) {
2501                                         a = attribs->tottface++;
2502         
2503                                         attribs->tface[a].array = NULL;
2504                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2505                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2506                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2507                                         
2508                                 }
2509                         }
2510                         */
2511                 }
2512                 else if(gattribs->layer[b].type == CD_MCOL) {
2513                         /* vertex colors */
2514                         if(gattribs->layer[b].name[0])
2515                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2516                                         gattribs->layer[b].name);
2517                         else
2518                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2519
2520                         if(layer != -1) {
2521                                 a = attribs->totmcol++;
2522
2523                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2524                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2525                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2526                         }
2527                 }
2528                 else if(gattribs->layer[b].type == CD_TANGENT) {
2529                         /* tangents */
2530                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2531
2532                         if(layer != -1) {
2533                                 attribs->tottang = 1;
2534
2535                                 attribs->tang.array = fdata->layers[layer].data;
2536                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2537                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2538                         }
2539                 }
2540                 else if(gattribs->layer[b].type == CD_ORCO) {
2541                         /* original coordinates */
2542                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2543
2544                         if(layer != -1) {
2545                                 attribs->totorco = 1;
2546
2547                                 attribs->orco.array = vdata->layers[layer].data;
2548                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2549                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2550                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2551                         }
2552                 }
2553         }
2554 }
2555
2556 /* Set object's bounding box based on DerivedMesh min/max data */
2557 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2558 {
2559         float min[3], max[3];
2560
2561         INIT_MINMAX(min, max);
2562
2563         dm->getMinMax(dm, min, max);
2564
2565         if(!ob->bb)
2566                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2567
2568         boundbox_set_from_min_max(ob->bb, min, max);
2569 }
2570
2571 /* --- NAVMESH (begin) --- */
2572 #ifdef WITH_GAMEENGINE
2573
2574 BM_INLINE int navmesh_bit(int a, int b)
2575 {
2576         return (a & (1 << b)) >> b;
2577 }
2578
2579 BM_INLINE void navmesh_intToCol(int i, float col[3])
2580 {
2581         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2582         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2583         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2584         col[0] = 1 - r*63.0f/255.0f;
2585         col[1] = 1 - g*63.0f/255.0f;
2586         col[2] = 1 - b*63.0f/255.0f;
2587 }
2588
2589 static void navmesh_drawColored(DerivedMesh *dm)
2590 {
2591         int a, glmode;
2592         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2593         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2594         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2595         float col[3];
2596
2597         if (!polygonIdx)
2598                 return;
2599
2600         /*
2601         //UI_ThemeColor(TH_WIRE);
2602         glDisable(GL_LIGHTING);
2603         glLineWidth(2.0);
2604         dm->drawEdges(dm, 0, 1);
2605         glLineWidth(1.0);
2606         glEnable(GL_LIGHTING);*/
2607
2608         glDisable(GL_LIGHTING);
2609         /*  if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2610                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2611                 //glShadeModel(GL_SMOOTH);
2612                 glBegin(glmode = GL_QUADS);
2613                 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2614                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2615                         int pi = polygonIdx[a];
2616                         if (pi <= 0) {
2617                                 zero_v3(col);
2618                         }
2619                         else {
2620                                 navmesh_intToCol(pi, col);
2621                         }
2622
2623                         if(new_glmode != glmode) {
2624                                 glEnd();
2625                                 glBegin(glmode = new_glmode);
2626                         }
2627                         glColor3fv(col);
2628                         glVertex3fv(mvert[mface->v1].co);
2629                         glVertex3fv(mvert[mface->v2].co);
2630                         glVertex3fv(mvert[mface->v3].co);
2631                         if(mface->v4) {
2632                                 glVertex3fv(mvert[mface->v4].co);
2633                         }
2634                 }
2635                 glEnd();
2636         }
2637         glEnable(GL_LIGHTING);
2638 }
2639
2640 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2641                         int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
2642                         int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
2643                         void *userData)
2644 {
2645         (void) setDrawOptions;
2646         (void) compareDrawOptions;
2647         (void) userData;
2648
2649         navmesh_drawColored(dm);
2650 }
2651
2652 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2653                                       float (*partial_redraw_planes)[4],
2654                                       int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2655 {
2656         (void) partial_redraw_planes;
2657         (void) setMaterial;
2658
2659         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2660         navmesh_drawColored(dm);
2661 }
2662
2663 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2664 {
2665         DerivedMesh *result;
2666         int maxFaces = dm->getNumPolys(dm);
2667         int *recastData;
2668         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2669         float* verts=NULL;
2670         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2671         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2672         int res;
2673
2674         result = CDDM_copy(dm, 0);
2675         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2676                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2677                 if (sourceRecastData) {
2678                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2679                                                    sourceRecastData, maxFaces, "recastData");
2680                 }
2681         }
2682         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2683
2684         /* note: This is not good design! - really should not be doing this */
2685         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2686         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2687
2688
2689         /* process mesh */
2690         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2691                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2692                                              &trisToFacesMap);
2693         if (res) {
2694                 size_t polyIdx;
2695
2696                 /* invalidate concave polygon */
2697                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2698                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2699                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2700                                 /* set negative polygon idx to all faces */
2701                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
2702                                 unsigned short tbase = dmesh[2];
2703                                 unsigned short tnum = dmesh[3];
2704                                 unsigned short ti;
2705
2706                                 for (ti=0; ti<tnum; ti++) {
2707                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
2708                                         unsigned short faceidx = trisToFacesMap[triidx];
2709                                         if (recastData[faceidx] > 0) {
2710                                                 recastData[faceidx] = -recastData[faceidx];
2711                                         }
2712                                 }
2713                         }
2714                 }
2715         }
2716         else {
2717                 printf("Error during creation polygon infos\n");
2718         }
2719
2720         /* clean up */
2721         if (verts!=NULL)
2722                 MEM_freeN(verts);
2723         if (dtris!=NULL)
2724                 MEM_freeN(dtris);
2725         if (dmeshes!=NULL)
2726                 MEM_freeN(dmeshes);
2727         if (polys!=NULL)
2728                 MEM_freeN(polys);
2729         if (dtrisToPolysMap!=NULL)
2730                 MEM_freeN(dtrisToPolysMap);
2731         if (dtrisToTrisMap!=NULL)
2732                 MEM_freeN(dtrisToTrisMap);
2733         if (trisToFacesMap!=NULL)
2734                 MEM_freeN(trisToFacesMap);
2735
2736         return result;
2737 }
2738
2739 #endif /* WITH_GAMEENGINE */
2740
2741 /* --- NAVMESH (end) --- */