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