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