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