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