style cleanup: blenkernel
[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] = 0;
1058                 r_col[2] = 0;
1059                 r_col[1] = 0;
1060                 r_col[0] = 255;
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                                 ndm = mti->applyModifier(md, ob, orcodm, app_flags & ~MOD_APPLY_USECACHE);
1656
1657                                 if (ndm) {
1658                                         /* if the modifier returned a new dm, release the old one */
1659                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1660                                         orcodm = ndm;
1661                                 }
1662                         }
1663
1664                         /* create cloth orco derivedmesh in parallel */
1665                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1666                                 if (!clothorcodm)
1667                                         clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1668
1669                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1670                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1671                                 ndm = mti->applyModifier(md, ob, clothorcodm, app_flags & ~MOD_APPLY_USECACHE);
1672
1673                                 if (ndm) {
1674                                         /* if the modifier returned a new dm, release the old one */
1675                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1676                                         clothorcodm = ndm;
1677                                 }
1678                         }
1679
1680                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1681                         /* XXX Temp and hackish solution! */
1682                         if (md->type == eModifierType_DynamicPaint)
1683                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1684                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1685                         else if ((md == previewmd) && (do_mod_wmcol)) {
1686                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1687                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1688                         }
1689                 }
1690
1691                 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1692
1693                 /* grab modifiers until index i */
1694                 if ((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1695                         break;
1696
1697                 if (sculpt_mode && md->type == eModifierType_Multires)
1698                         multires_applied = 1;
1699         }
1700
1701         for (md = firstmd; md; md = md->next)
1702                 modifier_freeTemporaryData(md);
1703
1704         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1705          * need to apply these back onto the DerivedMesh. If we have no
1706          * DerivedMesh then we need to build one.
1707          */
1708         if (dm && deformedVerts) {
1709                 finaldm = CDDM_copy(dm);
1710
1711                 dm->release(dm);
1712
1713                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1714                 CDDM_calc_normals(finaldm);
1715
1716 #if 0 /* For later nice mod preview! */
1717                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1718                 if (do_final_wmcol)
1719                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1720 #endif
1721         }
1722         else if (dm) {
1723                 finaldm = dm;
1724
1725 #if 0 /* For later nice mod preview! */
1726                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1727                 if (do_final_wmcol)
1728                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1729 #endif
1730         }
1731         else {
1732                 int recalc_normals = 0;
1733
1734                 finaldm = CDDM_from_mesh(me, ob);
1735                 
1736                 if (build_shapekey_layers) {
1737                         add_shapekey_layers(finaldm, me, ob);
1738                         recalc_normals = 1;
1739                 }
1740                 
1741                 if (deformedVerts) {
1742                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1743                         recalc_normals = 1;
1744                 }
1745
1746                 if (recalc_normals) {
1747                         CDDM_calc_normals(finaldm);
1748                 }
1749
1750                 /* In this case, we should never have weight-modifying modifiers in stack... */
1751                 if (do_init_wmcol)
1752                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1753         }
1754
1755         /* add an orco layer if needed */
1756         if (dataMask & CD_MASK_ORCO) {
1757                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1758
1759                 if (deform_r && *deform_r)
1760                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1761         }
1762
1763         {
1764                 /* calculating normals can re-calculate tessfaces in some cases */
1765 #if 0
1766                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1767 #endif
1768                 /* --------------------------------------------------------------------- */
1769                 /* First calculate the polygon and vertex normals, re-tessellation
1770                  * copies these into the tessface's normal layer */
1771
1772
1773                 /* comment because this causes a bug when deform is applied after a
1774                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1775                  * it also looks like this isn't even needed since code above recalc's
1776                  * normals - campbell */
1777 #if 0
1778                 finaldm->calcNormals(finaldm);
1779 #endif
1780
1781                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1782                  * from loops and polys onto the tessfaces. This may be currently be
1783                  * redundant in cases where the render mode doesn't use these inputs, but
1784                  * ideally eventually tessellation would happen on-demand, and this is one
1785                  * of the primary places it would be needed. */
1786 #if 0
1787                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
1788 #else
1789                 if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)) */
1790 #endif
1791                 {
1792                         finaldm->recalcTessellation(finaldm);
1793                 }
1794                 /* Even if tessellation is not needed, some modifiers migh have modified CD layers
1795                  * (like mloopcol or mloopuv), hence we have to update those. */
1796                 else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
1797                         /* A tessellation already exists, it should always have a CD_POLYINDEX. */
1798                         BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX));
1799                         DM_update_tessface_data(finaldm);
1800                 }
1801                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1802                 /* take care with this block, we really need testing frameworks          */
1803                 /* --------------------------------------------------------------------- */
1804
1805                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1806                  * normals and will also have to calculate normals on the fly, try avoid
1807                  * this where possible since calculating polygon normals isn't fast,
1808                  * note that this isn't a problem for subsurf (only quads) or editmode
1809                  * which deals with drawing differently.
1810                  *
1811                  * Never calc vertex normals because other code ensures these are up to date.
1812                  */
1813                 if ((finaldm->type == DM_TYPE_CDDM) && (CustomData_has_layer(&finaldm->faceData, CD_NORMAL) == FALSE)) {
1814                         CDDM_calc_normals_mapping_ex(finaldm, TRUE);
1815                 }
1816         }
1817
1818 #ifdef WITH_GAMEENGINE
1819         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1820         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1821                 DerivedMesh *tdm;
1822                 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1823                 if (finaldm != tdm) {
1824                         finaldm->release(finaldm);
1825                         finaldm = tdm;
1826                 }
1827         }
1828 #endif /* WITH_GAMEENGINE */
1829
1830         *final_r = finaldm;
1831
1832         if (orcodm)
1833                 orcodm->release(orcodm);
1834         if (clothorcodm)
1835                 clothorcodm->release(clothorcodm);
1836
1837         if (deformedVerts && deformedVerts != inputVertexCos)
1838                 MEM_freeN(deformedVerts);
1839
1840         BLI_linklist_free((LinkNode *)datamasks, NULL);
1841 }
1842
1843 float (*editbmesh_get_vertex_cos(BMEditMesh * em, int *numVerts_r))[3]
1844 {
1845         int i, numVerts = *numVerts_r = em->bm->totvert;
1846         float (*cos)[3];
1847         BMIter iter;
1848         BMVert *eve;
1849
1850         cos = MEM_mallocN(sizeof(float) * 3 * numVerts, "vertexcos");
1851
1852         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1853         for (i = 0; eve; eve = BM_iter_step(&iter), i++) {
1854                 copy_v3_v3(cos[i], eve->co);
1855         }
1856
1857         return cos;
1858 }
1859
1860 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1861 {
1862         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1863         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1864
1865         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1866         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1867                 modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
1868                 return 0;
1869         }
1870         
1871         return 1;
1872 }
1873
1874 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1875                                      DerivedMesh **final_r,
1876                                      CustomDataMask dataMask)
1877 {
1878         ModifierData *md;
1879         float (*deformedVerts)[3] = NULL;
1880         CustomDataMask mask;
1881         DerivedMesh *dm, *orcodm = NULL;
1882         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1883         CDMaskLink *datamasks, *curr;
1884         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1885
1886         modifiers_clearErrors(ob);
1887
1888         if (cage_r && cageIndex == -1) {
1889                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1890         }
1891
1892         dm = NULL;
1893         md = modifiers_getVirtualModifierList(ob);
1894
1895         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1896
1897         curr = datamasks;
1898         for (i = 0; md; i++, md = md->next, curr = curr->next) {
1899                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1900
1901                 md->scene = scene;
1902                 
1903                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
1904                         continue;
1905
1906                 /* add an orco layer if needed by this modifier */
1907                 if (dm && mti->requiredDataMask) {
1908                         mask = mti->requiredDataMask(ob, md);
1909                         if (mask & CD_MASK_ORCO)
1910                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1911                 }
1912
1913                 /* How to apply modifier depends on (a) what we already have as
1914                  * a result of previous modifiers (could be a DerivedMesh or just
1915                  * deformed vertices) and (b) what type the modifier is.
1916                  */
1917
1918                 if (mti->type == eModifierTypeType_OnlyDeform) {
1919                         /* No existing verts to deform, need to build them. */
1920                         if (!deformedVerts) {
1921                                 if (dm) {
1922                                         /* Deforming a derived mesh, read the vertex locations
1923                                          * out of the mesh and deform them. Once done with this
1924                                          * run of deformers verts will be written back.
1925                                          */
1926                                         numVerts = dm->getNumVerts(dm);
1927                                         deformedVerts =
1928                                             MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1929                                         dm->getVertCos(dm, deformedVerts);
1930                                 }
1931                                 else {
1932                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1933                                 }
1934                         }
1935
1936                         if (mti->deformVertsEM)
1937                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1938                         else
1939                                 mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
1940                 }
1941                 else {
1942                         DerivedMesh *ndm;
1943
1944                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1945                         if (dm) {
1946                                 if (deformedVerts) {
1947                                         DerivedMesh *tdm = CDDM_copy(dm);
1948                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
1949                                         dm = tdm;
1950
1951                                         CDDM_apply_vert_coords(dm, deformedVerts);
1952                                         CDDM_calc_normals(dm);
1953                                 }
1954                                 else if (cage_r && dm == *cage_r) {
1955                                         /* dm may be changed by this modifier, so we need to copy it
1956                                          */
1957                                         dm = CDDM_copy(dm);
1958                                 }
1959
1960                         }
1961                         else {
1962                                 dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
1963
1964                                 if (deformedVerts) {
1965                                         CDDM_apply_vert_coords(dm, deformedVerts);
1966                                         CDDM_calc_normals(dm);
1967                                 }
1968                         }
1969
1970                         /* create an orco derivedmesh in parallel */
1971                         mask = curr->mask;
1972                         if (mask & CD_MASK_ORCO) {
1973                                 if (!orcodm)
1974                                         orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
1975
1976                                 mask &= ~CD_MASK_ORCO;
1977                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1978
1979                                 if (mti->applyModifierEM)
1980                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1981                                 else
1982                                         ndm = mti->applyModifier(md, ob, orcodm, 0);
1983
1984                                 if (ndm) {
1985                                         /* if the modifier returned a new dm, release the old one */
1986                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1987                                         orcodm = ndm;
1988                                 }
1989                         }
1990
1991                         /* set the DerivedMesh to only copy needed data */
1992                         mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
1993
1994                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1995
1996                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
1997                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1998                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1999                                         DM_init_origspace(dm);
2000                                 }
2001                         }
2002                         
2003                         if (mti->applyModifierEM)
2004                                 ndm = mti->applyModifierEM(md, ob, em, dm);
2005                         else
2006                                 ndm = mti->applyModifier(md, ob, dm, 0);
2007
2008                         if (ndm) {
2009                                 if (dm && dm != ndm)
2010                                         dm->release(dm);
2011
2012                                 dm = ndm;
2013
2014                                 if (deformedVerts) {
2015                                         MEM_freeN(deformedVerts);
2016                                         deformedVerts = NULL;
2017                                 }
2018                         }
2019                 }
2020
2021                 if (cage_r && i == cageIndex) {
2022                         if (dm && deformedVerts) {
2023                                 *cage_r = CDDM_copy(dm);
2024                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2025                         }
2026                         else if (dm) {
2027                                 *cage_r = dm;
2028                         }
2029                         else {
2030                                 *cage_r =
2031                                     getEditDerivedBMesh(em, ob,
2032                                                         deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2033                         }
2034                 }
2035         }
2036
2037         BLI_linklist_free((LinkNode *)datamasks, NULL);
2038
2039         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2040          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2041          * then we need to build one.
2042          */
2043         if (dm && deformedVerts) {
2044                 *final_r = CDDM_copy(dm);
2045
2046                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2047
2048                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2049                 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
2050         }
2051         else if (dm) {
2052                 *final_r = dm;
2053                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
2054         }
2055         else if (!deformedVerts && cage_r && *cage_r) {
2056                 /* cage should already have up to date normals */
2057                 *final_r = *cage_r;
2058                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
2059         }
2060         else {
2061                 /* this is just a copy of the editmesh, no need to calc normals */
2062                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2063                 deformedVerts = NULL;
2064         }
2065
2066         /* --- */
2067         /* BMESH_ONLY, ensure tessface's used for drawing,
2068          * but don't recalculate if the last modifier in the stack gives us tessfaces
2069          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2070          * but quiets annoying error messages since tessfaces wont be created. */
2071         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2072                 DM_ensure_tessface(*final_r);
2073         }
2074         if (cage_r) {
2075                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2076                         if (*cage_r != *final_r) {
2077                                 DM_ensure_tessface(*cage_r);
2078                         }
2079                 }
2080         }
2081         /* --- */
2082
2083         /* add an orco layer if needed */
2084         if (dataMask & CD_MASK_ORCO)
2085                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2086
2087         if (orcodm)
2088                 orcodm->release(orcodm);
2089
2090         if (deformedVerts)
2091                 MEM_freeN(deformedVerts);
2092 }
2093
2094 static void clear_mesh_caches(Object *ob)
2095 {
2096         Mesh *me = ob->data;
2097
2098         /* also serves as signal to remake texspace */
2099         if (ob->bb) {
2100                 MEM_freeN(ob->bb);
2101                 ob->bb = NULL;
2102         }
2103         if (me->bb) {
2104                 MEM_freeN(me->bb);
2105                 me->bb = NULL;
2106         }
2107
2108         BKE_displist_free(&ob->disp);
2109
2110         if (ob->derivedFinal) {
2111                 ob->derivedFinal->needsFree = 1;
2112                 ob->derivedFinal->release(ob->derivedFinal);
2113                 ob->derivedFinal = NULL;
2114         }
2115         if (ob->derivedDeform) {
2116                 ob->derivedDeform->needsFree = 1;
2117                 ob->derivedDeform->release(ob->derivedDeform);
2118                 ob->derivedDeform = NULL;
2119         }
2120
2121         if (ob->sculpt) {
2122                 BKE_object_sculpt_modifiers_changed(ob);
2123         }
2124 }
2125
2126 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2127                             int build_shapekey_layers)
2128 {
2129         Object *obact = scene->basact ? scene->basact->object : NULL;
2130         int editing = paint_facesel_test(ob);
2131         /* weight paint and face select need original indices because of selection buffer drawing */
2132         int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2133
2134         clear_mesh_caches(ob);
2135
2136         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2137                             &ob->derivedFinal, 0, 1,
2138                             needMapping, dataMask, -1, 1, build_shapekey_layers);
2139
2140         DM_set_object_boundbox(ob, ob->derivedFinal);
2141
2142         ob->derivedFinal->needsFree = 0;
2143         ob->derivedDeform->needsFree = 0;
2144         ob->lastDataMask = dataMask;
2145
2146         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2147                 /* create PBVH immediately (would be created on the fly too,
2148                  * but this avoids waiting on first stroke) */
2149                 ob->sculpt->pbvh = ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2150         }
2151 }
2152
2153 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2154 {
2155         clear_mesh_caches(obedit);
2156
2157         if (em->derivedFinal) {
2158                 if (em->derivedFinal != em->derivedCage) {
2159                         em->derivedFinal->needsFree = 1;
2160                         em->derivedFinal->release(em->derivedFinal);
2161                 }
2162                 em->derivedFinal = NULL;
2163         }
2164         if (em->derivedCage) {
2165                 em->derivedCage->needsFree = 1;
2166                 em->derivedCage->release(em->derivedCage);
2167                 em->derivedCage = NULL;
2168         }
2169
2170         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2171         DM_set_object_boundbox(obedit, em->derivedFinal);
2172
2173         em->lastDataMask = dataMask;
2174         em->derivedFinal->needsFree = 0;
2175         em->derivedCage->needsFree = 0;
2176 }
2177
2178 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2179                      CustomDataMask dataMask, int build_shapekey_layers)
2180 {
2181         if (em) {
2182                 editbmesh_build_data(scene, ob, em, dataMask);
2183         }
2184         else {
2185                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2186         }
2187 }
2188
2189 /***/
2190
2191 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2192 {
2193         /* if there's no derived mesh or the last data mask used doesn't include
2194          * the data we need, rebuild the derived mesh
2195          */
2196         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2197                 mesh_build_data(scene, ob, dataMask, 0);
2198
2199         return ob->derivedFinal;
2200 }
2201
2202 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2203 {
2204         /* if there's no derived mesh or the last data mask used doesn't include
2205          * the data we need, rebuild the derived mesh
2206          */
2207         if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2208                 mesh_build_data(scene, ob, dataMask, 0);
2209
2210         return ob->derivedDeform;
2211 }
2212
2213 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2214 {
2215         DerivedMesh *final;
2216         
2217         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2218
2219         return final;
2220 }
2221
2222 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2223 {
2224         DerivedMesh *final;
2225         
2226         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2227
2228         return final;
2229 }
2230
2231 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2232 {
2233         DerivedMesh *final;
2234
2235         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2236
2237         return final;
2238 }
2239
2240 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2241                                            CustomDataMask dataMask)
2242 {
2243         DerivedMesh *final;
2244         
2245         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2246
2247         return final;
2248 }
2249
2250 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2251                                             CustomDataMask dataMask)
2252 {
2253         DerivedMesh *final;
2254         
2255         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2256
2257         return final;
2258 }
2259
2260 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2261                                          CustomDataMask dataMask)
2262 {
2263         DerivedMesh *final;
2264         
2265         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2266
2267         return final;
2268 }
2269
2270 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2271                                                   float (*vertCos)[3],
2272                                                   CustomDataMask dataMask)
2273 {
2274         DerivedMesh *final;
2275
2276         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2277
2278         return final;
2279 }
2280
2281 /***/
2282
2283 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2284                                                   CustomDataMask dataMask)
2285 {
2286         /* if there's no derived mesh or the last data mask used doesn't include
2287          * the data we need, rebuild the derived mesh
2288          */
2289         if (!em->derivedCage ||
2290             (em->lastDataMask & dataMask) != dataMask)
2291         {
2292                 editbmesh_build_data(scene, obedit, em, dataMask);
2293         }
2294
2295         *final_r = em->derivedFinal;
2296         return em->derivedCage;
2297 }
2298
2299 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2300 {
2301         /* if there's no derived mesh or the last data mask used doesn't include
2302          * the data we need, rebuild the derived mesh
2303          */
2304         if (!em->derivedCage ||
2305             (em->lastDataMask & dataMask) != dataMask)
2306         {
2307                 editbmesh_build_data(scene, obedit, em, dataMask);
2308         }
2309
2310         return em->derivedCage;
2311 }
2312
2313 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2314 {
2315         return getEditDerivedBMesh(em, obedit, NULL);
2316 }
2317
2318
2319 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2320
2321 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2322                                        const float no_f[3], const short no_s[3])
2323 {
2324         float *vec = userData;
2325         
2326         vec += 6 * index;
2327
2328         /* check if we've been here before (normal should not be 0) */
2329         if (vec[3] || vec[4] || vec[5]) return;
2330
2331         copy_v3_v3(vec, co);
2332         vec += 3;
2333         if (no_f) {
2334                 copy_v3_v3(vec, no_f);
2335         }
2336         else {
2337                 normal_short_to_float_v3(vec, no_s);
2338         }
2339 }
2340
2341 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2342 /* this is needed for all code using vertexgroups (no subsurf support) */
2343 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2344 /* in use now by vertex/weight paint and particle generating */
2345
2346 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2347 {
2348         Mesh *me = ob->data;
2349         DerivedMesh *dm;
2350         float *vertexcosnos;
2351         
2352         /* lets prevent crashing... */
2353         if (ob->type != OB_MESH || me->totvert == 0)
2354                 return NULL;
2355         
2356         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2357         vertexcosnos = MEM_callocN(6 * sizeof(float) * me->totvert, "vertexcosnos map");
2358         
2359         if (dm->foreachMappedVert) {
2360                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2361         }
2362         else {
2363                 float *fp = vertexcosnos;
2364                 int a;
2365                 
2366                 for (a = 0; a < me->totvert; a++, fp += 6) {
2367                         dm->getVertCo(dm, a, fp);
2368                         dm->getVertNo(dm, a, fp + 3);
2369                 }
2370         }
2371         
2372         dm->release(dm);
2373         return vertexcosnos;
2374 }
2375
2376 /* ******************* GLSL ******************** */
2377
2378 typedef struct {
2379         float *precomputedFaceNormals;
2380         MTFace *mtface;     // texture coordinates
2381         MFace *mface;       // indices
2382         MVert *mvert;       // vertices & normals
2383         float (*orco)[3];
2384         float (*tangent)[4];    // destination
2385         int numTessFaces;
2386
2387 } SGLSLMeshToTangent;
2388
2389 // interface
2390 #include "mikktspace.h"
2391
2392 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2393 {
2394         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2395         return pMesh->numTessFaces;
2396 }
2397
2398 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2399 {
2400         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2401         return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2402 }
2403
2404 static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const int face_num, const int vert_index)
2405 {
2406         //assert(vert_index>=0 && vert_index<4);
2407         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2408         const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2409         copy_v3_v3(fPos, co);
2410 }
2411
2412 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[], const int face_num, const int vert_index)
2413 {
2414         //assert(vert_index>=0 && vert_index<4);
2415         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2416
2417         if (pMesh->mtface != NULL) {
2418                 float *uv = pMesh->mtface[face_num].uv[vert_index];
2419                 fUV[0] = uv[0]; fUV[1] = uv[1];
2420         }
2421         else {
2422                 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2423                 map_to_sphere(&fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2424         }
2425 }
2426
2427 static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const int face_num, const int vert_index)
2428 {
2429         //assert(vert_index>=0 && vert_index<4);
2430         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2431
2432         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2433         if (!smoothnormal) {    // flat
2434                 if (pMesh->precomputedFaceNormals) {
2435                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3 * face_num]);
2436                 }
2437                 else {
2438                         MFace *mf = &pMesh->mface[face_num];
2439                         float *p0 = pMesh->mvert[mf->v1].co;
2440                         float *p1 = pMesh->mvert[mf->v2].co;
2441                         float *p2 = pMesh->mvert[mf->v3].co;
2442
2443                         if (mf->v4) {
2444                                 float *p3 = pMesh->mvert[mf->v4].co;
2445                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2446                         }
2447                         else {
2448                                 normal_tri_v3(fNorm, p0, p1, p2);
2449                         }
2450                 }
2451         }
2452         else {
2453                 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2454                 normal_short_to_float_v3(fNorm, no);
2455         }
2456 }
2457 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2458 {
2459         //assert(vert_index>=0 && vert_index<4);
2460         SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2461         float *pRes = pMesh->tangent[4 * face_num + iVert];
2462         copy_v3_v3(pRes, fvTangent);
2463         pRes[3] = fSign;
2464 }
2465
2466
2467 void DM_add_tangent_layer(DerivedMesh *dm)
2468 {
2469         /* mesh vars */
2470         MTFace *mtface, *tf;
2471         MFace *mface, *mf;
2472         MVert *mvert, *v1, *v2, *v3, *v4;
2473         MemArena *arena = NULL;
2474         VertexTangent **vtangents = NULL;
2475         float (*orco)[3] = NULL, (*tangent)[4];
2476         float *uv1, *uv2, *uv3, *uv4, *vtang;
2477         float fno[3], tang[3], uv[4][2];
2478         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2479         float *nors;
2480
2481         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2482                 return;
2483
2484         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2485
2486         /* check we have all the needed layers */
2487         totvert = dm->getNumVerts(dm);
2488         totface = dm->getNumTessFaces(dm);
2489
2490         mvert = dm->getVertArray(dm);
2491         mface = dm->getTessFaceArray(dm);
2492         mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2493
2494         if (!mtface) {
2495                 orco = dm->getVertDataArray(dm, CD_ORCO);
2496                 if (!orco)
2497                         return;
2498         }
2499         
2500         /* create tangent layer */
2501         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2502         tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2503         
2504         /* allocate some space */
2505         arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2506         BLI_memarena_use_calloc(arena);
2507         vtangents = MEM_callocN(sizeof(VertexTangent *) * totvert, "VertexTangent");
2508
2509         // new computation method
2510         iCalcNewMethod = 1;
2511         if (iCalcNewMethod != 0) {
2512                 SGLSLMeshToTangent mesh2tangent = {0};
2513                 SMikkTSpaceContext sContext = {0};
2514                 SMikkTSpaceInterface sInterface = {0};
2515
2516                 mesh2tangent.precomputedFaceNormals = nors;
2517                 mesh2tangent.mtface = mtface;
2518                 mesh2tangent.mface = mface;
2519                 mesh2tangent.mvert = mvert;
2520                 mesh2tangent.orco = orco;
2521                 mesh2tangent.tangent = tangent;
2522                 mesh2tangent.numTessFaces = totface;
2523
2524                 sContext.m_pUserData = &mesh2tangent;
2525                 sContext.m_pInterface = &sInterface;
2526                 sInterface.m_getNumFaces = GetNumFaces;
2527                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2528                 sInterface.m_getPosition = GetPosition;
2529                 sInterface.m_getTexCoord = GetTextureCoordinate;
2530                 sInterface.m_getNormal = GetNormal;
2531                 sInterface.m_setTSpaceBasic = SetTSpace;
2532
2533                 // 0 if failed
2534                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2535         }
2536
2537         if (!iCalcNewMethod) {
2538                 /* sum tangents at connected vertices */
2539                 for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++) {
2540                         v1 = &mvert[mf->v1];
2541                         v2 = &mvert[mf->v2];
2542                         v3 = &mvert[mf->v3];
2543
2544                         if (mf->v4) {
2545                                 v4 = &mvert[mf->v4];
2546                                 normal_quad_v3(fno, v4->co, v3->co, v2->co, v1->co);
2547                         }
2548                         else {
2549                                 v4 = NULL;
2550                                 normal_tri_v3(fno, v3->co, v2->co, v1->co);
2551                         }
2552                 
2553                         if (mtface) {
2554                                 uv1 = tf->uv[0];
2555                                 uv2 = tf->uv[1];
2556                                 uv3 = tf->uv[2];
2557                                 uv4 = tf->uv[3];
2558                         }
2559                         else {
2560                                 uv1 = uv[0]; uv2 = uv[1]; uv3 = uv[2]; uv4 = uv[3];
2561                                 map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2562                                 map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2563                                 map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2564                                 if (v4)
2565                                         map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2566                         }
2567                 
2568                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2569                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2570                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2571                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2572                 
2573                         if (mf->v4) {
2574                                 v4 = &mvert[mf->v4];
2575                         
2576                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2577                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2578                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2579                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2580                         }
2581                 }
2582         
2583                 /* write tangent to layer */
2584                 for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++, tangent += 4) {
2585                         len = (mf->v4) ? 4 : 3;
2586
2587                         if (mtface == NULL) {
2588                                 map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2589                                 map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2590                                 map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2591                                 if (len == 4)
2592                                         map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2593                         }
2594                 
2595                         mf_vi[0] = mf->v1;
2596                         mf_vi[1] = mf->v2;
2597                         mf_vi[2] = mf->v3;
2598                         mf_vi[3] = mf->v4;
2599                 
2600                         for (j = 0; j < len; j++) {
2601                                 vtang = find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2602                                 normalize_v3_v3(tangent[j], vtang);
2603                                 ((float *) tangent[j])[3] = 1.0f;
2604                         }
2605                 }
2606         }
2607         
2608         BLI_memarena_free(arena);
2609         MEM_freeN(vtangents);
2610 }
2611
2612 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2613 {
2614         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2615         int totface = dm->getNumTessFaces(dm);
2616
2617         MVert *mvert = dm->getVertArray(dm);
2618         MFace *mface = dm->getTessFaceArray(dm);
2619         MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2620
2621         if (mtface) {
2622                 double dsum = 0.0;
2623                 int nr_accumulated = 0;
2624                 int f;
2625
2626                 for (f = 0; f < totface; f++) {
2627                         {
2628                                 float *verts[4], *tex_coords[4];
2629                                 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2630                                 int i, is_degenerate;
2631
2632                                 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2633                                 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2634                                 if (nr_verts == 4) {
2635                                         verts[3] = mvert[mface[f].v4].co;
2636                                         tex_coords[3] = mtface[f].uv[3];
2637                                 }
2638
2639                                 // discard degenerate faces
2640                                 is_degenerate = 0;
2641                                 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2642                                     equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2643                                 {
2644                                         is_degenerate = 1;
2645                                 }
2646
2647                                 // verify last vertex as well if this is a quad
2648                                 if (is_degenerate == 0 && nr_verts == 4) {
2649                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2650                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2651                                         {
2652                                                 is_degenerate = 1;
2653                                         }
2654
2655                                         // verify the winding is consistent
2656                                         if (is_degenerate == 0) {
2657                                                 float prev_edge[2];
2658                                                 int is_signed = 0;
2659                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2660
2661                                                 i = 0;
2662                                                 while (is_degenerate == 0 && i < 4) {
2663                                                         float cur_edge[2], signed_area;
2664                                                         sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2665                                                         signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2666
2667                                                         if (i == 0) {
2668                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2669                                                         }
2670                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2671                                                                 is_degenerate = 1;
2672                                                         }
2673
2674                                                         if (is_degenerate == 0) {
2675                                                                 copy_v2_v2(prev_edge, cur_edge);
2676                                                                 i++;
2677                                                         }
2678                                                 }
2679                                         }
2680                                 }
2681
2682                                 // proceed if not a degenerate face
2683                                 if (is_degenerate == 0) {
2684                                         int nr_tris_to_pile = 0;
2685                                         // quads split at shortest diagonal
2686                                         int offs = 0;       // initial triangulation is 0,1,2 and 0, 2, 3
2687                                         if (nr_verts == 4) {
2688                                                 float pos_len_diag0, pos_len_diag1;
2689                                                 float vtmp[3];
2690                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2691                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2692                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2693                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2694
2695                                                 if (pos_len_diag1 < pos_len_diag0) {
2696                                                         offs = 1;     // alter split
2697                                                 }
2698                                                 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2699                                                         float tex_len_diag0, tex_len_diag1;
2700
2701                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2702                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2703                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2704                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2705
2706                                                         if (tex_len_diag1 < tex_len_diag0) {
2707                                                                 offs = 1; /* alter split */
2708                                                         }
2709                                                 }
2710                                         }
2711                                         nr_tris_to_pile = nr_verts - 2;
2712                                         if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2713                                                 const int indices[] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2714                                                 int t;
2715                                                 for (t = 0; t < nr_tris_to_pile; t++) {
2716                                                         float f2x_area_uv;
2717                                                         float *p0 = verts[indices[t * 3 + 0]];
2718                                                         float *p1 = verts[indices[t * 3 + 1]];
2719                                                         float *p2 = verts[indices[t * 3 + 2]];
2720
2721                                                         float edge_t0[2], edge_t1[2];
2722                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2723                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2724
2725                                                         f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2726                                                         if (f2x_area_uv > FLT_EPSILON) {
2727                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2728                                                                 sub_v3_v3v3(v0, p1, p0);
2729                                                                 sub_v3_v3v3(v1, p2, p0);
2730                                                                 cross_v3_v3v3(norm, v0, v1);
2731
2732                                                                 f2x_surf_area = len_v3(norm);
2733                                                                 fsurf_ratio = f2x_surf_area / f2x_area_uv;    // tri area divided by texture area
2734
2735                                                                 nr_accumulated++;
2736                                                                 dsum += (double)(fsurf_ratio);
2737                                                         }
2738                                                 }
2739                                         }
2740                                 }
2741                         }
2742                 }
2743
2744                 // finalize
2745                 {
2746                         const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2747                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);       // use width of average surface ratio as your bump scale
2748                         dm->auto_bump_scale = use_as_render_bump_scale;
2749                 }
2750         }
2751         else {
2752                 dm->auto_bump_scale = 1.0f;
2753         }
2754 }
2755
2756 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2757 {
2758         CustomData *vdata, *fdata, *tfdata = NULL;
2759         int a, b, layer;
2760
2761         /* From the layers requested by the GLSL shader, figure out which ones are
2762          * actually available for this derivedmesh, and retrieve the pointers */
2763
2764         memset(attribs, 0, sizeof(DMVertexAttribs));
2765
2766         vdata = &dm->vertData;
2767         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2768         
2769         /* calc auto bump scale if necessary */
2770         if (dm->auto_bump_scale <= 0.0f)
2771                 DM_calc_auto_bump_scale(dm);
2772
2773         /* add a tangent layer if necessary */
2774         for (b = 0; b < gattribs->totlayer; b++)
2775                 if (gattribs->layer[b].type == CD_TANGENT)
2776                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2777                                 DM_add_tangent_layer(dm);
2778
2779         for (b = 0; b < gattribs->totlayer; b++) {
2780                 if (gattribs->layer[b].type == CD_MTFACE) {
2781                         /* uv coordinates */
2782                         if (dm->type == DM_TYPE_EDITBMESH) {
2783                                 /* exception .. */
2784                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2785
2786                                 if (gattribs->layer[b].name[0])
2787                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2788                                                                                  gattribs->layer[b].name);
2789                                 else
2790                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2791
2792                                 if (layer != -1) {
2793                                         a = attribs->tottface++;
2794
2795                                         attribs->tface[a].array = tfdata->layers[layer].data;
2796                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2797                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2798                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2799                                 }
2800                         }
2801                         else {
2802                                 if (gattribs->layer[b].name[0])
2803                                         layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2804                                                                                  gattribs->layer[b].name);
2805                                 else
2806                                         layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2807
2808                                 if (layer != -1) {
2809                                         a = attribs->tottface++;
2810
2811                                         attribs->tface[a].array = tfdata->layers[layer].data;
2812                                         attribs->tface[a].em_offset = tfdata->layers[layer].offset;
2813                                         attribs->tface[a].gl_index = gattribs->layer[b].glindex;
2814                                         attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
2815                                 }
2816                         }
2817                 }
2818                 else if (gattribs->layer[b].type == CD_MCOL) {
2819                         if (dm->type == DM_TYPE_EDITBMESH) {
2820                                 /* exception .. */
2821                                 CustomData *ldata = dm->getLoopDataLayout(dm);
2822
2823                                 if (gattribs->layer[b].name[0])
2824                                         layer = CustomData_get_named_layer_index(ldata, CD_MLOOPCOL,
2825                                                                                  gattribs->layer[b].name);
2826                                 else
2827                                         layer = CustomData_get_active_layer_index(ldata, CD_MLOOPCOL);
2828
2829                                 if (layer != -1) {
2830                                         a = attribs->totmcol++;
2831
2832                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2833                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2834                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2835                                 }
2836                         }
2837                         else {
2838                                 /* vertex colors */
2839                                 if (gattribs->layer[b].name[0])
2840                                         layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2841                                                                                  gattribs->layer[b].name);
2842                                 else
2843                                         layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2844
2845                                 if (layer != -1) {
2846                                         a = attribs->totmcol++;
2847
2848                                         attribs->mcol[a].array = tfdata->layers[layer].data;
2849                                         attribs->mcol[a].em_offset = tfdata->layers[layer].offset;
2850                                         attribs->mcol[a].gl_index = gattribs->layer[b].glindex;
2851                                 }
2852                         }
2853                 }
2854                 else if (gattribs->layer[b].type == CD_TANGENT) {
2855                         /* tangents */
2856                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2857
2858                         if (layer != -1) {
2859                                 attribs->tottang = 1;
2860
2861                                 attribs->tang.array = fdata->layers[layer].data;
2862                                 attribs->tang.em_offset = fdata->layers[layer].offset;
2863                                 attribs->tang.gl_index = gattribs->layer[b].glindex;
2864                         }
2865                 }
2866                 else if (gattribs->layer[b].type == CD_ORCO) {
2867                         /* original coordinates */
2868                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2869
2870                         if (layer != -1) {
2871                                 attribs->totorco = 1;
2872
2873                                 attribs->orco.array = vdata->layers[layer].data;
2874                                 attribs->orco.em_offset = vdata->layers[layer].offset;
2875                                 attribs->orco.gl_index = gattribs->layer[b].glindex;
2876                                 attribs->orco.gl_texco = gattribs->layer[b].gltexco;
2877                         }
2878                 }
2879         }
2880 }
2881
2882 /* Set object's bounding box based on DerivedMesh min/max data */
2883 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2884 {
2885         float min[3], max[3];
2886
2887         INIT_MINMAX(min, max);
2888
2889         dm->getMinMax(dm, min, max);
2890
2891         if (!ob->bb)
2892                 ob->bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2893
2894         BKE_boundbox_init_from_minmax(ob->bb, min, max);
2895 }
2896
2897 /* --- NAVMESH (begin) --- */
2898 #ifdef WITH_GAMEENGINE
2899
2900 /* BMESH_TODO, navmesh is not working right currently
2901  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2902  *
2903  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2904  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2905  * data from the original me->mpoly layer. - campbell
2906  */
2907
2908
2909 BLI_INLINE int navmesh_bit(int a, int b)
2910 {
2911         return (a & (1 << b)) >> b;
2912 }
2913
2914 BLI_INLINE void navmesh_intToCol(int i, float col[3])
2915 {
2916         int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2917         int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2918         int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2919         col[0] = 1 - r * 63.0f / 255.0f;
2920         col[1] = 1 - g * 63.0f / 255.0f;
2921         col[2] = 1 - b * 63.0f / 255.0f;
2922 }
2923
2924 static void navmesh_drawColored(DerivedMesh *dm)
2925 {
2926         int a, glmode;
2927         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2928         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2929         int *polygonIdx = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
2930         float col[3];
2931
2932         if (!polygonIdx)
2933                 return;
2934
2935 #if 0
2936         //UI_ThemeColor(TH_WIRE);
2937         glDisable(GL_LIGHTING);
2938         glLineWidth(2.0);
2939         dm->drawEdges(dm, 0, 1);
2940         glLineWidth(1.0);
2941         glEnable(GL_LIGHTING);
2942 #endif
2943
2944         glDisable(GL_LIGHTING);
2945         /*  if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2946                 DEBUG_VBO("Using legacy code. drawNavMeshColored\n");
2947                 //glShadeModel(GL_SMOOTH);
2948                 glBegin(glmode = GL_QUADS);
2949                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
2950                         int new_glmode = mface->v4 ? GL_QUADS : GL_TRIANGLES;
2951                         int pi = polygonIdx[a];
2952                         if (pi <= 0) {
2953                                 zero_v3(col);
2954                         }
2955                         else {
2956                                 navmesh_intToCol(pi, col);
2957                         }
2958
2959                         if (new_glmode != glmode) {
2960                                 glEnd();
2961                                 glBegin(glmode = new_glmode);
2962                         }
2963                         glColor3fv(col);
2964                         glVertex3fv(mvert[mface->v1].co);
2965                         glVertex3fv(mvert[mface->v2].co);
2966                         glVertex3fv(mvert[mface->v3].co);
2967                         if (mface->v4) {
2968                                 glVertex3fv(mvert[mface->v4].co);
2969                         }
2970                 }
2971                 glEnd();
2972         }
2973         glEnable(GL_LIGHTING);
2974 }
2975
2976 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2977                                     DMSetDrawOptionsTex setDrawOptions,
2978                                     DMCompareDrawOptions compareDrawOptions,
2979                                     void *userData)
2980 {
2981         (void) setDrawOptions;
2982         (void) compareDrawOptions;
2983         (void) userData;
2984
2985         navmesh_drawColored(dm);
2986 }
2987
2988 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2989                                       float (*partial_redraw_planes)[4],
2990                                       int UNUSED(fast), DMSetMaterial setMaterial)
2991 {
2992         (void) partial_redraw_planes;
2993         (void) setMaterial;
2994
2995         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2996         navmesh_drawColored(dm);
2997 }
2998
2999 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
3000 {
3001         DerivedMesh *result;
3002         int maxFaces = dm->getNumPolys(dm);
3003         int *recastData;
3004         int vertsPerPoly = 0, nverts = 0, ndtris = 0, npolys = 0;
3005         float *verts = NULL;
3006         unsigned short *dtris = NULL, *dmeshes = NULL, *polys = NULL;
3007         int *dtrisToPolysMap = NULL, *dtrisToTrisMap = NULL, *trisToFacesMap = NULL;
3008         int res;
3009
3010         result = CDDM_copy(dm);
3011         if (!CustomData_has_layer(&result->polyData, CD_RECAST)) {
3012                 int *sourceRecastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST);
3013                 if (sourceRecastData) {
3014                         CustomData_add_layer_named(&result->polyData, CD_RECAST, CD_DUPLICATE,
3015                                                    sourceRecastData, maxFaces, "recastData");
3016                 }
3017         }
3018         recastData = (int *)CustomData_get_layer(&result->polyData, CD_RECAST);
3019
3020         /* note: This is not good design! - really should not be doing this */
3021         result->drawFacesTex =  navmesh_DM_drawFacesTex;
3022         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
3023
3024
3025         /* process mesh */
3026         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
3027                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
3028                                              &trisToFacesMap);
3029         if (res) {
3030                 size_t polyIdx;
3031
3032                 /* invalidate concave polygon */
3033                 for (polyIdx = 0; polyIdx < (size_t)npolys; polyIdx++) {
3034                         unsigned short *poly = &polys[polyIdx * 2 * vertsPerPoly];
3035                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
3036                                 /* set negative polygon idx to all faces */
3037                                 unsigned short *dmesh = &dmeshes[4 * polyIdx];
3038                                 unsigned short tbase = dmesh[2];
3039                                 unsigned short tnum = dmesh[3];
3040                                 unsigned short ti;
3041
3042                                 for (ti = 0; ti < tnum; ti++) {
3043                                         unsigned short triidx = dtrisToTrisMap[tbase + ti];
3044                                         unsigned short faceidx = trisToFacesMap[triidx];
3045                                         if (recastData[faceidx] > 0) {
3046                                                 recastData[faceidx] = -recastData[faceidx];
3047                                         }
3048                                 }