2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2005 Blender Foundation.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/DerivedMesh.c
36 #include "MEM_guardedalloc.h"
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"
46 #include "BLI_array.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_bitmap.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_linklist.h"
54 #include "BKE_cdderivedmesh.h"
55 #include "BKE_colorband.h"
56 #include "BKE_editmesh.h"
58 #include "BKE_library.h"
59 #include "BKE_material.h"
60 #include "BKE_modifier.h"
62 #include "BKE_mesh_mapping.h"
63 #include "BKE_object.h"
64 #include "BKE_object_deform.h"
65 #include "BKE_paint.h"
66 #include "BKE_multires.h"
67 #include "BKE_bvhutils.h"
68 #include "BKE_deform.h"
69 #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */
71 #ifdef WITH_GAMEENGINE
72 #include "BKE_navmesh_conversion.h"
73 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
76 #include "BLI_sys_types.h" /* for intptr_t support */
78 #include "GPU_buffers.h"
80 #include "GPU_shader.h"
82 #ifdef WITH_OPENSUBDIV
83 # include "BKE_depsgraph.h"
84 # include "DNA_userdef_types.h"
87 /* very slow! enable for testing only! */
88 //#define USE_MODIFIER_VALIDATE
90 #ifdef USE_MODIFIER_VALIDATE
91 # define ASSERT_IS_VALID_DM(dm) (BLI_assert((dm == NULL) || (DM_is_valid(dm) == true)))
93 # define ASSERT_IS_VALID_DM(dm)
97 static ThreadRWMutex loops_cache_lock = PTHREAD_RWLOCK_INITIALIZER;
100 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
101 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
104 /* -------------------------------------------------------------------- */
106 static MVert *dm_getVertArray(DerivedMesh *dm)
108 MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
111 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
112 dm->getNumVerts(dm));
113 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
114 dm->copyVertArray(dm, mvert);
120 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
122 MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
125 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
126 dm->getNumEdges(dm));
127 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
128 dm->copyEdgeArray(dm, medge);
134 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
136 MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
139 int numTessFaces = dm->getNumTessFaces(dm);
142 /* Do not add layer if there's no elements in it, this leads to issues later when
143 * this layer is needed with non-zero size, but currently CD stuff does not check
144 * for requested layer size on creation and just returns layer which was previously
149 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
150 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
151 dm->copyTessFaceArray(dm, mface);
157 static MLoop *dm_getLoopArray(DerivedMesh *dm)
159 MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
162 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
163 dm->getNumLoops(dm));
164 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
165 dm->copyLoopArray(dm, mloop);
171 static MPoly *dm_getPolyArray(DerivedMesh *dm)
173 MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
176 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
177 dm->getNumPolys(dm));
178 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
179 dm->copyPolyArray(dm, mpoly);
185 static MVert *dm_dupVertArray(DerivedMesh *dm)
187 MVert *tmp = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(*tmp),
188 "dm_dupVertArray tmp");
190 if (tmp) dm->copyVertArray(dm, tmp);
195 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
197 MEdge *tmp = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(*tmp),
198 "dm_dupEdgeArray tmp");
200 if (tmp) dm->copyEdgeArray(dm, tmp);
205 static MFace *dm_dupFaceArray(DerivedMesh *dm)
207 MFace *tmp = MEM_malloc_arrayN(dm->getNumTessFaces(dm), sizeof(*tmp),
208 "dm_dupFaceArray tmp");
210 if (tmp) dm->copyTessFaceArray(dm, tmp);
215 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
217 MLoop *tmp = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(*tmp),
218 "dm_dupLoopArray tmp");
220 if (tmp) dm->copyLoopArray(dm, tmp);
225 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
227 MPoly *tmp = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(*tmp),
228 "dm_dupPolyArray tmp");
230 if (tmp) dm->copyPolyArray(dm, tmp);
235 static int dm_getNumLoopTri(DerivedMesh *dm)
237 const int numlooptris = poly_to_tri_count(dm->getNumPolys(dm), dm->getNumLoops(dm));
238 BLI_assert(ELEM(dm->looptris.num, 0, numlooptris));
242 static const MLoopTri *dm_getLoopTriArray(DerivedMesh *dm)
246 BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_READ);
247 looptri = dm->looptris.array;
248 BLI_rw_mutex_unlock(&loops_cache_lock);
250 if (looptri != NULL) {
251 BLI_assert(dm->getNumLoopTri(dm) == dm->looptris.num);
254 BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_WRITE);
255 /* We need to ensure array is still NULL inside mutex-protected code, some other thread might have already
256 * recomputed those looptris. */
257 if (dm->looptris.array == NULL) {
258 dm->recalcLoopTri(dm);
260 looptri = dm->looptris.array;
261 BLI_rw_mutex_unlock(&loops_cache_lock);
266 static CustomData *dm_getVertCData(DerivedMesh *dm)
268 return &dm->vertData;
271 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
273 return &dm->edgeData;
276 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
278 return &dm->faceData;
281 static CustomData *dm_getLoopCData(DerivedMesh *dm)
283 return &dm->loopData;
286 static CustomData *dm_getPolyCData(DerivedMesh *dm)
288 return &dm->polyData;
292 * Utility function to initialize a DerivedMesh's function pointers to
293 * the default implementation (for those functions which have a default)
295 void DM_init_funcs(DerivedMesh *dm)
297 /* default function implementations */
298 dm->getVertArray = dm_getVertArray;
299 dm->getEdgeArray = dm_getEdgeArray;
300 dm->getTessFaceArray = dm_getTessFaceArray;
301 dm->getLoopArray = dm_getLoopArray;
302 dm->getPolyArray = dm_getPolyArray;
303 dm->dupVertArray = dm_dupVertArray;
304 dm->dupEdgeArray = dm_dupEdgeArray;
305 dm->dupTessFaceArray = dm_dupFaceArray;
306 dm->dupLoopArray = dm_dupLoopArray;
307 dm->dupPolyArray = dm_dupPolyArray;
309 dm->getLoopTriArray = dm_getLoopTriArray;
311 /* subtypes handle getting actual data */
312 dm->getNumLoopTri = dm_getNumLoopTri;
314 dm->getVertDataLayout = dm_getVertCData;
315 dm->getEdgeDataLayout = dm_getEdgeCData;
316 dm->getTessFaceDataLayout = dm_getTessFaceCData;
317 dm->getLoopDataLayout = dm_getLoopCData;
318 dm->getPolyDataLayout = dm_getPolyCData;
320 dm->getVertData = DM_get_vert_data;
321 dm->getEdgeData = DM_get_edge_data;
322 dm->getTessFaceData = DM_get_tessface_data;
323 dm->getPolyData = DM_get_poly_data;
324 dm->getVertDataArray = DM_get_vert_data_layer;
325 dm->getEdgeDataArray = DM_get_edge_data_layer;
326 dm->getTessFaceDataArray = DM_get_tessface_data_layer;
327 dm->getPolyDataArray = DM_get_poly_data_layer;
328 dm->getLoopDataArray = DM_get_loop_data_layer;
330 bvhcache_init(&dm->bvhCache);
334 * Utility function to initialize a DerivedMesh for the desired number
335 * of vertices, edges and faces (doesn't allocate memory for them, just
336 * sets up the custom data layers)
339 DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
340 int numTessFaces, int numLoops, int numPolys)
343 dm->numVertData = numVerts;
344 dm->numEdgeData = numEdges;
345 dm->numTessFaceData = numTessFaces;
346 dm->numLoopData = numLoops;
347 dm->numPolyData = numPolys;
352 dm->auto_bump_scale = -1.0f;
355 /* don't use CustomData_reset(...); because we dont want to touch customdata */
356 copy_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
357 copy_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
358 copy_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
359 copy_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
360 copy_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
364 * Utility function to initialize a DerivedMesh for the desired number
365 * of vertices, edges and faces, with a layer setup copied from source
367 void DM_from_template_ex(
368 DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
369 int numVerts, int numEdges, int numTessFaces,
370 int numLoops, int numPolys,
373 CustomData_copy(&source->vertData, &dm->vertData, mask, CD_CALLOC, numVerts);
374 CustomData_copy(&source->edgeData, &dm->edgeData, mask, CD_CALLOC, numEdges);
375 CustomData_copy(&source->faceData, &dm->faceData, mask, CD_CALLOC, numTessFaces);
376 CustomData_copy(&source->loopData, &dm->loopData, mask, CD_CALLOC, numLoops);
377 CustomData_copy(&source->polyData, &dm->polyData, mask, CD_CALLOC, numPolys);
379 dm->cd_flag = source->cd_flag;
382 dm->numVertData = numVerts;
383 dm->numEdgeData = numEdges;
384 dm->numTessFaceData = numTessFaces;
385 dm->numLoopData = numLoops;
386 dm->numPolyData = numPolys;
393 void DM_from_template(
394 DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
395 int numVerts, int numEdges, int numTessFaces,
396 int numLoops, int numPolys)
400 numVerts, numEdges, numTessFaces,
402 CD_MASK_DERIVEDMESH);
405 int DM_release(DerivedMesh *dm)
408 bvhcache_free(&dm->bvhCache);
409 GPU_drawobject_free(dm);
410 CustomData_free(&dm->vertData, dm->numVertData);
411 CustomData_free(&dm->edgeData, dm->numEdgeData);
412 CustomData_free(&dm->faceData, dm->numTessFaceData);
413 CustomData_free(&dm->loopData, dm->numLoopData);
414 CustomData_free(&dm->polyData, dm->numPolyData);
422 MEM_SAFE_FREE(dm->looptris.array);
423 dm->looptris.num = 0;
424 dm->looptris.num_alloc = 0;
429 CustomData_free_temporary(&dm->vertData, dm->numVertData);
430 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
431 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
432 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
433 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
439 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
441 CustomData_free(&target->loopData, source->numLoopData);
442 CustomData_free(&target->polyData, source->numPolyData);
444 CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
445 CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
447 target->numLoopData = source->numLoopData;
448 target->numPolyData = source->numPolyData;
450 if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
454 mloop = source->dupLoopArray(source);
455 mpoly = source->dupPolyArray(source);
456 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
457 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
461 void DM_ensure_normals(DerivedMesh *dm)
463 if (dm->dirty & DM_DIRTY_NORMALS) {
466 BLI_assert((dm->dirty & DM_DIRTY_NORMALS) == 0);
469 static void DM_calc_loop_normals(DerivedMesh *dm, const bool use_split_normals, float split_angle)
471 dm->calcLoopNormals(dm, use_split_normals, split_angle);
472 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
475 /* note: until all modifiers can take MPoly's as input,
476 * use this at the start of modifiers */
477 void DM_ensure_tessface(DerivedMesh *dm)
479 const int numTessFaces = dm->getNumTessFaces(dm);
480 const int numPolys = dm->getNumPolys(dm);
482 if ((numTessFaces == 0) && (numPolys != 0)) {
483 dm->recalcTessellation(dm);
485 if (dm->getNumTessFaces(dm) != 0) {
486 /* printf("info %s: polys -> ngons calculated\n", __func__); */
489 printf("warning %s: could not create tessfaces from %d polygons, dm->type=%u\n",
490 __func__, numPolys, dm->type);
494 else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
495 BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX) || numTessFaces == 0);
496 DM_update_tessface_data(dm);
499 dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
503 * Ensure the array is large enough
505 * /note This function must always be thread-protected by caller. It should only be used by internal code.
507 void DM_ensure_looptri_data(DerivedMesh *dm)
509 const unsigned int totpoly = dm->numPolyData;
510 const unsigned int totloop = dm->numLoopData;
511 const int looptris_num = poly_to_tri_count(totpoly, totloop);
513 BLI_assert(dm->looptris.array_wip == NULL);
515 SWAP(MLoopTri *, dm->looptris.array, dm->looptris.array_wip);
517 if ((looptris_num > dm->looptris.num_alloc) ||
518 (looptris_num < dm->looptris.num_alloc * 2) ||
521 MEM_SAFE_FREE(dm->looptris.array_wip);
522 dm->looptris.num_alloc = 0;
523 dm->looptris.num = 0;
527 if (dm->looptris.array_wip == NULL) {
528 dm->looptris.array_wip = MEM_malloc_arrayN(looptris_num, sizeof(*dm->looptris.array_wip), __func__);
529 dm->looptris.num_alloc = looptris_num;
532 dm->looptris.num = looptris_num;
536 void DM_verttri_from_looptri(MVertTri *verttri, const MLoop *mloop, const MLoopTri *looptri, int looptri_num)
539 for (i = 0; i < looptri_num; i++) {
540 verttri[i].tri[0] = mloop[looptri[i].tri[0]].v;
541 verttri[i].tri[1] = mloop[looptri[i].tri[1]].v;
542 verttri[i].tri[2] = mloop[looptri[i].tri[2]].v;
546 /* Update tessface CD data from loop/poly ones. Needed when not retessellating after modstack evaluation. */
547 /* NOTE: Assumes dm has valid tessellated data! */
548 void DM_update_tessface_data(DerivedMesh *dm)
550 MFace *mf, *mface = dm->getTessFaceArray(dm);
551 MPoly *mp = dm->getPolyArray(dm);
552 MLoop *ml = dm->getLoopArray(dm);
554 CustomData *fdata = dm->getTessFaceDataLayout(dm);
555 CustomData *pdata = dm->getPolyDataLayout(dm);
556 CustomData *ldata = dm->getLoopDataLayout(dm);
558 const int totface = dm->getNumTessFaces(dm);
561 int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
562 unsigned int (*loopindex)[4];
564 /* Should never occure, but better abort than segfault! */
568 CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
570 if (CustomData_has_layer(fdata, CD_MTFACE) ||
571 CustomData_has_layer(fdata, CD_MCOL) ||
572 CustomData_has_layer(fdata, CD_PREVIEW_MCOL) ||
573 CustomData_has_layer(fdata, CD_ORIGSPACE) ||
574 CustomData_has_layer(fdata, CD_TESSLOOPNORMAL) ||
575 CustomData_has_layer(fdata, CD_TANGENT))
577 loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
579 for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
580 const int mf_len = mf->v4 ? 4 : 3;
581 unsigned int *ml_idx = loopindex[mf_idx];
584 /* Find out loop indices. */
585 /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
586 for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
587 const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v);
595 /* NOTE: quad detection issue - fourth vertidx vs fourth loopidx:
596 * Here, our tfaces' fourth vertex index is never 0 for a quad. However, we know our fourth loop index may be
597 * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code).
598 * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test.
600 BKE_mesh_loops_to_tessdata(fdata, ldata, pdata, mface, polyindex, loopindex, totface);
602 MEM_freeN(loopindex);
605 if (G.debug & G_DEBUG)
606 printf("%s: Updated tessellated customdata of dm %p\n", __func__, dm);
608 dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
611 void DM_generate_tangent_tessface_data(DerivedMesh *dm, bool generate)
613 MFace *mf, *mface = dm->getTessFaceArray(dm);
614 MPoly *mp = dm->getPolyArray(dm);
615 MLoop *ml = dm->getLoopArray(dm);
617 CustomData *fdata = dm->getTessFaceDataLayout(dm);
618 CustomData *pdata = dm->getPolyDataLayout(dm);
619 CustomData *ldata = dm->getLoopDataLayout(dm);
621 const int totface = dm->getNumTessFaces(dm);
624 int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
625 unsigned int (*loopindex)[4] = NULL;
627 /* Should never occure, but better abort than segfault! */
632 for (int j = 0; j < ldata->totlayer; j++) {
633 if (ldata->layers[j].type == CD_TANGENT) {
634 CustomData_add_layer_named(fdata, CD_TANGENT, CD_CALLOC, NULL, totface, ldata->layers[j].name);
635 CustomData_bmesh_update_active_layers(fdata, pdata, ldata);
638 loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
639 for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
640 const int mf_len = mf->v4 ? 4 : 3;
641 unsigned int *ml_idx = loopindex[mf_idx];
643 /* Find out loop indices. */
644 /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
645 for (int i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
646 const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v);
655 /* NOTE: quad detection issue - fourth vertidx vs fourth loopidx:
656 * Here, our tfaces' fourth vertex index is never 0 for a quad. However, we know our fourth loop index may be
657 * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code).
658 * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test.
660 BKE_mesh_tangent_loops_to_tessdata(fdata, ldata, mface, polyindex, loopindex, totface, ldata->layers[j].name);
664 MEM_freeN(loopindex);
665 BLI_assert(CustomData_from_bmeshpoly_test(fdata, pdata, ldata, true));
668 if (G.debug & G_DEBUG)
669 printf("%s: Updated tessellated tangents of dm %p\n", __func__, dm);
673 void DM_update_materials(DerivedMesh *dm, Object *ob)
675 int i, totmat = ob->totcol + 1; /* materials start from 1, default material is 0 */
677 if (dm->totmat != totmat) {
679 /* invalidate old materials */
683 dm->mat = MEM_malloc_arrayN(totmat, sizeof(*dm->mat), "DerivedMesh.mat");
686 /* we leave last material as empty - rationale here is being able to index
687 * the materials by using the mf->mat_nr directly and leaving the last
688 * material as NULL in case no materials exist on mesh, so indexing will not fail */
689 for (i = 0; i < totmat - 1; i++) {
690 dm->mat[i] = give_current_material(ob, i + 1);
695 MLoopUV *DM_paint_uvlayer_active_get(DerivedMesh *dm, int mat_nr)
699 BLI_assert(mat_nr < dm->totmat);
701 if (dm->mat[mat_nr] && dm->mat[mat_nr]->texpaintslot &&
702 dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname)
704 uv_base = CustomData_get_layer_named(&dm->loopData, CD_MLOOPUV,
705 dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname);
706 /* This can fail if we have changed the name in the UV layer list and have assigned the old name in the material
709 uv_base = CustomData_get_layer(&dm->loopData, CD_MLOOPUV);
712 uv_base = CustomData_get_layer(&dm->loopData, CD_MLOOPUV);
718 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool take_ownership)
720 /* dm might depend on me, so we need to do everything with a local copy */
722 int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
723 int did_shapekeys = 0;
724 int alloctype = CD_DUPLICATE;
726 if (take_ownership && dm->type == DM_TYPE_CDDM && dm->needsFree) {
727 bool has_any_referenced_layers =
728 CustomData_has_referenced(&dm->vertData) ||
729 CustomData_has_referenced(&dm->edgeData) ||
730 CustomData_has_referenced(&dm->loopData) ||
731 CustomData_has_referenced(&dm->faceData) ||
732 CustomData_has_referenced(&dm->polyData);
733 if (!has_any_referenced_layers) {
734 alloctype = CD_ASSIGN;
738 CustomData_reset(&tmp.vdata);
739 CustomData_reset(&tmp.edata);
740 CustomData_reset(&tmp.fdata);
741 CustomData_reset(&tmp.ldata);
742 CustomData_reset(&tmp.pdata);
744 DM_ensure_normals(dm);
746 totvert = tmp.totvert = dm->getNumVerts(dm);
747 totedge = tmp.totedge = dm->getNumEdges(dm);
748 totloop = tmp.totloop = dm->getNumLoops(dm);
749 totpoly = tmp.totpoly = dm->getNumPolys(dm);
752 CustomData_copy(&dm->vertData, &tmp.vdata, mask, alloctype, totvert);
753 CustomData_copy(&dm->edgeData, &tmp.edata, mask, alloctype, totedge);
754 CustomData_copy(&dm->loopData, &tmp.ldata, mask, alloctype, totloop);
755 CustomData_copy(&dm->polyData, &tmp.pdata, mask, alloctype, totpoly);
756 tmp.cd_flag = dm->cd_flag;
758 if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
763 kb = BLI_findlink(&me->key->block, ob->shapenr - 1);
768 printf("%s: error - could not find active shapekey %d!\n",
769 __func__, ob->shapenr - 1);
775 /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
779 shapekey_layers_to_keyblocks(dm, me, uid);
783 /* copy texture space */
785 BKE_mesh_texspace_copy_from_object(&tmp, ob);
788 /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
789 * we set them here in case they are missing */
790 if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) {
791 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN,
792 (alloctype == CD_ASSIGN) ? dm->getVertArray(dm) : dm->dupVertArray(dm),
795 if (!CustomData_has_layer(&tmp.edata, CD_MEDGE)) {
796 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN,
797 (alloctype == CD_ASSIGN) ? dm->getEdgeArray(dm) : dm->dupEdgeArray(dm),
800 if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
801 tmp.mloop = (alloctype == CD_ASSIGN) ? dm->getLoopArray(dm) : dm->dupLoopArray(dm);
802 tmp.mpoly = (alloctype == CD_ASSIGN) ? dm->getPolyArray(dm) : dm->dupPolyArray(dm);
804 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
805 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
808 /* object had got displacement layer, should copy this layer to save sculpted data */
809 /* NOTE: maybe some other layers should be copied? nazgul */
810 if (CustomData_has_layer(&me->ldata, CD_MDISPS)) {
811 if (totloop == me->totloop) {
812 MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
813 CustomData_add_layer(&tmp.ldata, CD_MDISPS, alloctype, mdisps, totloop);
817 /* yes, must be before _and_ after tessellate */
818 BKE_mesh_update_customdata_pointers(&tmp, false);
820 /* since 2.65 caller must do! */
821 // BKE_mesh_tessface_calc(&tmp);
823 CustomData_free(&me->vdata, me->totvert);
824 CustomData_free(&me->edata, me->totedge);
825 CustomData_free(&me->fdata, me->totface);
826 CustomData_free(&me->ldata, me->totloop);
827 CustomData_free(&me->pdata, me->totpoly);
829 /* ok, this should now use new CD shapekey data,
830 * which should be fed through the modifier
832 if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
833 printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
835 id_us_min(&tmp.key->id);
839 /* Clear selection history */
840 MEM_SAFE_FREE(tmp.mselect);
842 BLI_assert(ELEM(tmp.bb, NULL, me->bb));
848 /* skip the listbase */
849 MEMCPY_STRUCT_OFS(me, &tmp, id.prev);
851 if (take_ownership) {
852 if (alloctype == CD_ASSIGN) {
853 CustomData_free_typemask(&dm->vertData, dm->numVertData, ~mask);
854 CustomData_free_typemask(&dm->edgeData, dm->numEdgeData, ~mask);
855 CustomData_free_typemask(&dm->loopData, dm->numLoopData, ~mask);
856 CustomData_free_typemask(&dm->polyData, dm->numPolyData, ~mask);
862 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
864 int a, totvert = dm->getNumVerts(dm);
868 if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) {
872 if (kb->data) MEM_freeN(kb->data);
873 kb->data = MEM_malloc_arrayN(me->key->elemsize, me->totvert, "kb->data");
874 kb->totelem = totvert;
877 mvert = dm->getVertDataArray(dm, CD_MVERT);
879 for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
880 copy_v3_v3(fp, mvert->co);
885 * set the CD_FLAG_NOCOPY flag in custom data layers where the mask is
886 * zero for the layer type, so only layer types specified by the mask
889 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
891 CustomData_set_only_copy(&dm->vertData, mask);
892 CustomData_set_only_copy(&dm->edgeData, mask);
893 CustomData_set_only_copy(&dm->faceData, mask);
894 /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
895 * weight paint mode when there are modifiers applied, needs further investigation,
896 * see replies to r50969, Campbell */
898 CustomData_set_only_copy(&dm->loopData, mask);
899 CustomData_set_only_copy(&dm->polyData, mask);
903 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
905 CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
908 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
910 CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
913 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
915 CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
918 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
920 CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
923 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
925 CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
928 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
930 BLI_assert(index >= 0 && index < dm->getNumVerts(dm));
931 return CustomData_get(&dm->vertData, index, type);
934 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
936 BLI_assert(index >= 0 && index < dm->getNumEdges(dm));
937 return CustomData_get(&dm->edgeData, index, type);
940 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
942 BLI_assert(index >= 0 && index < dm->getNumTessFaces(dm));
943 return CustomData_get(&dm->faceData, index, type);
946 void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
948 BLI_assert(index >= 0 && index < dm->getNumPolys(dm));
949 return CustomData_get(&dm->polyData, index, type);
953 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
955 if (type == CD_MVERT)
956 return dm->getVertArray(dm);
958 return CustomData_get_layer(&dm->vertData, type);
961 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
963 if (type == CD_MEDGE)
964 return dm->getEdgeArray(dm);
966 return CustomData_get_layer(&dm->edgeData, type);
969 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
971 if (type == CD_MFACE)
972 return dm->getTessFaceArray(dm);
974 return CustomData_get_layer(&dm->faceData, type);
977 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
979 return CustomData_get_layer(&dm->polyData, type);
982 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
984 return CustomData_get_layer(&dm->loopData, type);
987 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
989 CustomData_set(&dm->vertData, index, type, data);
992 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
994 CustomData_set(&dm->edgeData, index, type, data);
997 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
999 CustomData_set(&dm->faceData, index, type, data);
1002 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
1003 int source_index, int dest_index, int count)
1005 CustomData_copy_data(&source->vertData, &dest->vertData,
1006 source_index, dest_index, count);
1009 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
1010 int source_index, int dest_index, int count)
1012 CustomData_copy_data(&source->edgeData, &dest->edgeData,
1013 source_index, dest_index, count);
1016 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
1017 int source_index, int dest_index, int count)
1019 CustomData_copy_data(&source->faceData, &dest->faceData,
1020 source_index, dest_index, count);
1023 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
1024 int source_index, int dest_index, int count)
1026 CustomData_copy_data(&source->loopData, &dest->loopData,
1027 source_index, dest_index, count);
1030 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
1031 int source_index, int dest_index, int count)
1033 CustomData_copy_data(&source->polyData, &dest->polyData,
1034 source_index, dest_index, count);
1037 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
1039 CustomData_free_elem(&dm->vertData, index, count);
1042 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
1044 CustomData_free_elem(&dm->edgeData, index, count);
1047 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
1049 CustomData_free_elem(&dm->faceData, index, count);
1052 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
1054 CustomData_free_elem(&dm->loopData, index, count);
1057 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
1059 CustomData_free_elem(&dm->polyData, index, count);
1063 * interpolates vertex data from the vertices indexed by src_indices in the
1064 * source mesh using the given weights and stores the result in the vertex
1065 * indexed by dest_index in the dest mesh
1067 void DM_interp_vert_data(
1068 DerivedMesh *source, DerivedMesh *dest,
1069 int *src_indices, float *weights,
1070 int count, int dest_index)
1072 CustomData_interp(&source->vertData, &dest->vertData, src_indices,
1073 weights, NULL, count, dest_index);
1077 * interpolates edge data from the edges indexed by src_indices in the
1078 * source mesh using the given weights and stores the result in the edge indexed
1079 * by dest_index in the dest mesh.
1080 * if weights is NULL, all weights default to 1.
1081 * if vert_weights is non-NULL, any per-vertex edge data is interpolated using
1082 * vert_weights[i] multiplied by weights[i].
1084 void DM_interp_edge_data(
1085 DerivedMesh *source, DerivedMesh *dest,
1087 float *weights, EdgeVertWeight *vert_weights,
1088 int count, int dest_index)
1090 CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
1091 weights, (float *)vert_weights, count, dest_index);
1095 * interpolates face data from the faces indexed by src_indices in the
1096 * source mesh using the given weights and stores the result in the face indexed
1097 * by dest_index in the dest mesh.
1098 * if weights is NULL, all weights default to 1.
1099 * if vert_weights is non-NULL, any per-vertex face data is interpolated using
1100 * vert_weights[i] multiplied by weights[i].
1102 void DM_interp_tessface_data(
1103 DerivedMesh *source, DerivedMesh *dest,
1105 float *weights, FaceVertWeight *vert_weights,
1106 int count, int dest_index)
1108 CustomData_interp(&source->faceData, &dest->faceData, src_indices,
1109 weights, (float *)vert_weights, count, dest_index);
1112 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
1114 CustomData_swap_corners(&dm->faceData, index, corner_indices);
1117 void DM_interp_loop_data(
1118 DerivedMesh *source, DerivedMesh *dest,
1120 float *weights, int count, int dest_index)
1122 CustomData_interp(&source->loopData, &dest->loopData, src_indices,
1123 weights, NULL, count, dest_index);
1126 void DM_interp_poly_data(
1127 DerivedMesh *source, DerivedMesh *dest,
1129 float *weights, int count, int dest_index)
1131 CustomData_interp(&source->polyData, &dest->polyData, src_indices,
1132 weights, NULL, count, dest_index);
1135 DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3])
1137 DerivedMesh *dm = CDDM_from_mesh(me);
1143 CDDM_apply_vert_coords(dm, vertCos);
1149 DerivedMesh *mesh_create_derived_for_modifier(
1150 Scene *scene, Object *ob,
1151 ModifierData *md, int build_shapekey_layers)
1153 Mesh *me = ob->data;
1154 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1160 if (!(md->mode & eModifierMode_Realtime)) {
1164 if (mti->isDisabled && mti->isDisabled(md, 0)) {
1168 if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
1169 BKE_keyblock_convert_to_mesh(kb, me);
1172 if (mti->type == eModifierTypeType_OnlyDeform) {
1174 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
1176 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
1177 dm = mesh_create_derived(me, deformedVerts);
1179 if (build_shapekey_layers)
1180 add_shapekey_layers(dm, me, ob);
1182 MEM_freeN(deformedVerts);
1185 DerivedMesh *tdm = mesh_create_derived(me, NULL);
1187 if (build_shapekey_layers)
1188 add_shapekey_layers(tdm, me, ob);
1190 dm = modwrap_applyModifier(md, ob, tdm, 0);
1191 ASSERT_IS_VALID_DM(dm);
1193 if (tdm != dm) tdm->release(tdm);
1199 static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
1206 /* these may not really be the orco's, but it's only for preview.
1207 * could be solver better once, but isn't simple */
1209 orco = MEM_malloc_arrayN(em->bm->totvert, sizeof(float) * 3, "BMEditMesh Orco");
1211 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1212 copy_v3_v3(orco[i], eve->co);
1218 /* orco custom data layer */
1219 static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
1223 if (layer == CD_ORCO) {
1224 /* get original coordinates */
1228 return get_editbmesh_orco_verts(em);
1230 return BKE_mesh_orco_verts_get(ob);
1232 else if (layer == CD_CLOTH_ORCO) {
1233 /* apply shape key for cloth, this should really be solved
1234 * by a more flexible customdata system, but not simple */
1236 ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
1237 KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
1239 if (kb && kb->data) {
1250 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
1257 dm = CDDM_from_editbmesh(em, false, false);
1260 dm = CDDM_from_mesh(me);
1263 orco = get_orco_coords_dm(ob, em, layer, &free);
1266 CDDM_apply_vert_coords(dm, orco);
1267 if (free) MEM_freeN(orco);
1273 static void add_orco_dm(
1274 Object *ob, BMEditMesh *em, DerivedMesh *dm,
1275 DerivedMesh *orcodm, int layer)
1277 float (*orco)[3], (*layerorco)[3];
1280 totvert = dm->getNumVerts(dm);
1283 orco = MEM_calloc_arrayN(totvert, sizeof(float[3]), "dm orco");
1286 if (orcodm->getNumVerts(orcodm) == totvert)
1287 orcodm->getVertCos(orcodm, orco);
1289 dm->getVertCos(dm, orco);
1292 orco = get_orco_coords_dm(ob, em, layer, &free);
1295 if (layer == CD_ORCO)
1296 BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
1298 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1299 DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1300 layerorco = DM_get_vert_data_layer(dm, layer);
1303 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
1304 if (free) MEM_freeN(orco);
1308 /* weight paint colors */
1310 /* Something of a hack, at the moment deal with weightpaint
1311 * by tucking into colors during modifier eval, only in
1312 * wpaint mode. Works ok but need to make sure recalc
1313 * happens on enter/exit wpaint.
1316 void weight_to_rgb(float r_rgb[3], const float weight)
1318 const float blend = ((weight / 2.0f) + 0.5f);
1320 if (weight <= 0.25f) { /* blue->cyan */
1322 r_rgb[1] = blend * weight * 4.0f;
1325 else if (weight <= 0.50f) { /* cyan->green */
1328 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
1330 else if (weight <= 0.75f) { /* green->yellow */
1331 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
1335 else if (weight <= 1.0f) { /* yellow->red */
1337 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
1341 /* exceptional value, unclamped or nan,
1342 * avoid uninitialized memory use */
1349 /* draw_flag's for calc_weightpaint_vert_color */
1351 /* only one of these should be set, keep first (for easy bit-shifting) */
1352 CALC_WP_GROUP_USER_ACTIVE = (1 << 1),
1353 CALC_WP_GROUP_USER_ALL = (1 << 2),
1355 CALC_WP_MULTIPAINT = (1 << 3),
1356 CALC_WP_AUTO_NORMALIZE = (1 << 4),
1357 CALC_WP_MIRROR_X = (1 << 5),
1360 typedef struct DMWeightColorInfo {
1361 const ColorBand *coba;
1362 const char *alert_color;
1363 } DMWeightColorInfo;
1366 static int dm_drawflag_calc(const ToolSettings *ts, const Mesh *me)
1368 return ((ts->multipaint ? CALC_WP_MULTIPAINT : 0) |
1369 /* CALC_WP_GROUP_USER_ACTIVE or CALC_WP_GROUP_USER_ALL */
1370 (1 << ts->weightuser) |
1371 (ts->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0) |
1372 ((me->editflag & ME_EDIT_MIRROR_X) ? CALC_WP_MIRROR_X : 0));
1375 static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcinfo, const float input)
1379 if (dm_wcinfo && dm_wcinfo->coba) {
1380 BKE_colorband_evaluate(dm_wcinfo->coba, input, colf);
1383 weight_to_rgb(colf, input);
1386 /* don't use rgb_float_to_uchar() here because
1387 * the resulting float doesn't need 0-1 clamp check */
1388 r_col[0] = (unsigned char)(colf[0] * 255.0f);
1389 r_col[1] = (unsigned char)(colf[1] * 255.0f);
1390 r_col[2] = (unsigned char)(colf[2] * 255.0f);
1395 static void calc_weightpaint_vert_color(
1396 unsigned char r_col[4],
1397 const MDeformVert *dv,
1398 DMWeightColorInfo *dm_wcinfo,
1399 const int defbase_tot, const int defbase_act,
1400 const bool *defbase_sel, const int defbase_sel_tot,
1401 const int draw_flag)
1405 bool show_alert_color = false;
1407 if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1408 /* Multi-Paint feature */
1409 input = BKE_defvert_multipaint_collective_weight(
1410 dv, defbase_tot, defbase_sel, defbase_sel_tot, (draw_flag & CALC_WP_AUTO_NORMALIZE) != 0);
1412 /* make it black if the selected groups have no weight on a vertex */
1413 if (input == 0.0f) {
1414 show_alert_color = true;
1418 /* default, non tricky behavior */
1419 input = defvert_find_weight(dv, defbase_act);
1421 if (draw_flag & CALC_WP_GROUP_USER_ACTIVE) {
1422 if (input == 0.0f) {
1423 show_alert_color = true;
1426 else if (draw_flag & CALC_WP_GROUP_USER_ALL) {
1427 if (input == 0.0f) {
1428 show_alert_color = defvert_is_weight_zero(dv, defbase_tot);
1433 if (show_alert_color == false) {
1434 CLAMP(input, 0.0f, 1.0f);
1435 weightpaint_color(r_col, dm_wcinfo, input);
1438 copy_v3_v3_char((char *)r_col, dm_wcinfo->alert_color);
1443 static DMWeightColorInfo G_dm_wcinfo;
1445 void vDM_ColorBand_store(const ColorBand *coba, const char alert_color[4])
1447 G_dm_wcinfo.coba = coba;
1448 G_dm_wcinfo.alert_color = alert_color;
1452 * return an array of vertex weight colors, caller must free.
1454 * \note that we could save some memory and allocate RGB only but then we'd need to
1455 * re-arrange the colors when copying to the face since MCol has odd ordering,
1456 * so leave this as is - campbell
1458 static void calc_weightpaint_vert_array(
1459 Object *ob, DerivedMesh *dm, int const draw_flag, DMWeightColorInfo *dm_wcinfo,
1460 unsigned char (*r_wtcol_v)[4])
1462 BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1463 const int numVerts = dm->getNumVerts(dm);
1465 if ((ob->actdef != 0) &&
1466 (CustomData_has_layer(em ? &em->bm->vdata : &dm->vertData, CD_MDEFORMVERT)))
1468 unsigned char (*wc)[4] = r_wtcol_v;
1471 /* variables for multipaint */
1472 const int defbase_tot = BLI_listbase_count(&ob->defbase);
1473 const int defbase_act = ob->actdef - 1;
1475 int defbase_sel_tot = 0;
1476 bool *defbase_sel = NULL;
1478 if (draw_flag & CALC_WP_MULTIPAINT) {
1479 defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_sel_tot);
1481 if (defbase_sel_tot > 1 && (draw_flag & CALC_WP_MIRROR_X)) {
1482 BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_sel_tot);
1486 /* editmesh won't have deform verts unless modifiers require it,
1487 * avoid having to create an array of deform-verts only for drawing
1488 * by reading from the bmesh directly. */
1492 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1493 BLI_assert(cd_dvert_offset != -1);
1495 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1496 const MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1497 calc_weightpaint_vert_color(
1498 (unsigned char *)wc, dv, dm_wcinfo,
1499 defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1504 const MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1505 for (i = numVerts; i != 0; i--, wc++, dv++) {
1506 calc_weightpaint_vert_color(
1507 (unsigned char *)wc, dv, dm_wcinfo,
1508 defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1513 MEM_freeN(defbase_sel);
1517 unsigned char col[4];
1518 if ((ob->actdef == 0) && !BLI_listbase_is_empty(&ob->defbase)) {
1519 /* color-code for missing data (full brightness isn't easy on the eye). */
1520 ARRAY_SET_ITEMS(col, 0xa0, 0, 0xa0, 0xff);
1522 else if (draw_flag & (CALC_WP_GROUP_USER_ACTIVE | CALC_WP_GROUP_USER_ALL)) {
1523 copy_v3_v3_char((char *)col, dm_wcinfo->alert_color);
1527 weightpaint_color(col, dm_wcinfo, 0.0f);
1529 copy_vn_i((int *)r_wtcol_v, numVerts, *((int *)col));
1533 /** return an array of vertex weight colors from given weights, caller must free.
1535 * \note that we could save some memory and allocate RGB only but then we'd need to
1536 * re-arrange the colors when copying to the face since MCol has odd ordering,
1537 * so leave this as is - campbell
1539 static void calc_colors_from_weights_array(
1540 const int num, const float *weights,
1541 unsigned char (*r_wtcol_v)[4])
1543 unsigned char (*wc)[4] = r_wtcol_v;
1546 for (i = 0; i < num; i++, wc++, weights++) {
1547 weightpaint_color((unsigned char *)wc, NULL, *weights);
1551 void DM_update_weight_mcol(
1552 Object *ob, DerivedMesh *dm, int const draw_flag,
1553 float *weights, int num, const int *indices)
1555 BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1556 unsigned char (*wtcol_v)[4];
1557 int numVerts = dm->getNumVerts(dm);
1561 BKE_editmesh_color_ensure(em, BM_VERT);
1562 wtcol_v = em->derivedVertColor;
1565 wtcol_v = MEM_malloc_arrayN(numVerts, sizeof(*wtcol_v), __func__);
1568 /* Weights are given by caller. */
1571 /* If indices is not NULL, it means we do not have weights for all vertices,
1572 * so we must create them (and set them to zero)... */
1574 w = MEM_calloc_arrayN(numVerts, sizeof(float), "Temp weight array DM_update_weight_mcol");
1577 w[indices[i]] = weights[i];
1580 /* Convert float weights to colors. */
1581 calc_colors_from_weights_array(numVerts, w, wtcol_v);
1587 /* No weights given, take them from active vgroup(s). */
1588 calc_weightpaint_vert_array(ob, dm, draw_flag, &G_dm_wcinfo, wtcol_v);
1591 if (dm->type == DM_TYPE_EDITBMESH) {
1592 /* editmesh draw function checks specifically for this */
1595 const int dm_totpoly = dm->getNumPolys(dm);
1596 const int dm_totloop = dm->getNumLoops(dm);
1597 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1598 MLoop *mloop = dm->getLoopArray(dm), *ml;
1599 MPoly *mp = dm->getPolyArray(dm);
1603 /* now add to loops, so the data can be passed through the modifier stack
1604 * If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1606 wtcol_l = MEM_malloc_arrayN(dm_totloop, sizeof(*wtcol_l), __func__);
1607 CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
1611 for (i = 0; i < dm_totpoly; i++, mp++) {
1612 ml = mloop + mp->loopstart;
1614 for (j = 0; j < mp->totloop; j++, ml++, l_index++) {
1615 copy_v4_v4_uchar(&wtcol_l[l_index][0],
1616 &wtcol_v[ml->v][0]);
1621 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1625 static void DM_update_statvis_color(const Scene *scene, Object *ob, DerivedMesh *dm)
1627 BMEditMesh *em = BKE_editmesh_from_object(ob);
1629 BKE_editmesh_statvis_calc(em, dm, &scene->toolsettings->statvis);
1632 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1640 tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1641 for (i = 0; i < tot; i++) {
1642 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1643 float (*cos)[3], (*kbcos)[3];
1645 for (kb = me->key->block.first; kb; kb = kb->next) {
1646 if (kb->uid == layer->uid)
1651 kb = BKE_keyblock_add(me->key, layer->name);
1652 kb->uid = layer->uid;
1656 MEM_freeN(kb->data);
1658 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1659 kb->totelem = dm->numVertData;
1661 kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, 3 * sizeof(float), "kbcos DerivedMesh.c");
1662 if (kb->uid == actshape_uid) {
1663 MVert *mvert = dm->getVertArray(dm);
1665 for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1666 copy_v3_v3(*kbcos, mvert->co);
1670 for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1671 copy_v3_v3(*kbcos, *cos);
1676 for (kb = me->key->block.first; kb; kb = kb->next) {
1677 if (kb->totelem != dm->numVertData) {
1679 MEM_freeN(kb->data);
1681 kb->totelem = dm->numVertData;
1682 kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c");
1683 fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1688 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1697 /* ensure we can use mesh vertex count for derived mesh custom data */
1698 if (me->totvert != dm->getNumVerts(dm)) {
1700 "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1701 __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1705 for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1709 if (me->totvert != kb->totelem) {
1711 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1712 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1713 array = MEM_calloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
1716 array = MEM_malloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
1717 memcpy(array, kb->data, (size_t)me->totvert * 3 * sizeof(float));
1720 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1721 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1723 dm->vertData.layers[ci].uid = kb->uid;
1728 * Called after calculating all modifiers.
1730 * \note tessfaces should already be calculated.
1732 static void dm_ensure_display_normals(DerivedMesh *dm)
1734 /* Note: dm *may* have a poly CD_NORMAL layer (generated by a modifier needing poly normals e.g.).
1735 * We do not use it here, though. And it should be tagged as temp!
1737 /* BLI_assert((CustomData_has_layer(&dm->polyData, CD_NORMAL) == false)); */
1739 if ((dm->type == DM_TYPE_CDDM) &&
1740 ((dm->dirty & DM_DIRTY_NORMALS) || CustomData_has_layer(&dm->polyData, CD_NORMAL) == false))
1742 /* if normals are dirty we want to calculate vertex normals too */
1743 CDDM_calc_normals_mapping_ex(dm, (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
1748 * new value for useDeform -1 (hack for the gameengine):
1750 * - apply only the modifier stack of the object, skipping the virtual modifiers,
1751 * - don't apply the key
1752 * - apply deform modifiers and input vertexco
1754 static void mesh_calc_modifiers(
1755 Scene *scene, Object *ob, float (*inputVertexCos)[3],
1756 const bool useRenderParams, int useDeform,
1757 const bool need_mapping, CustomDataMask dataMask,
1758 const int index, const bool useCache, const bool build_shapekey_layers,
1759 const bool allow_gpu,
1761 DerivedMesh **r_deform, DerivedMesh **r_final)
1763 Mesh *me = ob->data;
1764 ModifierData *firstmd, *md, *previewmd = NULL;
1765 CDMaskLink *datamasks, *curr;
1766 /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1767 CustomDataMask mask, nextmask, previewmask = 0, append_mask = CD_MASK_ORIGINDEX;
1768 float (*deformedVerts)[3] = NULL;
1769 DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1770 int numVerts = me->totvert;
1771 const int required_mode = useRenderParams ? eModifierMode_Render : eModifierMode_Realtime;
1772 bool isPrevDeform = false;
1773 const bool skipVirtualArmature = (useDeform < 0);
1774 MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1775 const bool has_multires = (mmd && mmd->sculptlvl != 0);
1776 bool multires_applied = false;
1777 const bool sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt && !useRenderParams;
1778 const bool sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm) && !useRenderParams;
1779 const int draw_flag = dm_drawflag_calc(scene->toolsettings, me);
1781 /* Generic preview only in object mode! */
1782 const bool do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1783 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1784 const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1786 const bool do_final_wmcol = false;
1787 const bool do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MLOOPCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1788 /* XXX Same as above... For now, only weights preview in WPaint mode. */
1789 const bool do_mod_wmcol = do_init_wmcol;
1791 const bool do_loop_normals = (me->flag & ME_AUTOSMOOTH) != 0;
1792 const float loop_normals_split_angle = me->smoothresh;
1794 VirtualModifierData virtualModifierData;
1796 ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1797 ModifierApplyFlag deform_app_flags = app_flags;
1801 app_flags |= MOD_APPLY_USECACHE;
1803 app_flags |= MOD_APPLY_ALLOW_GPU;
1805 deform_app_flags |= MOD_APPLY_USECACHE;
1807 if (!skipVirtualArmature) {
1808 firstmd = modifiers_getVirtualModifierList(ob, &virtualModifierData);
1811 /* game engine exception */
1812 firstmd = ob->modifiers.first;
1813 if (firstmd && firstmd->type == eModifierType_Armature)
1814 firstmd = firstmd->next;
1819 modifiers_clearErrors(ob);
1821 if (do_mod_wmcol || do_mod_mcol) {
1822 /* Find the last active modifier generating a preview, or NULL if none. */
1823 /* XXX Currently, DPaint modifier just ignores this.
1824 * Needs a stupid hack...
1825 * The whole "modifier preview" thing has to be (re?)designed, anyway! */
1826 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1828 /* even if the modifier doesn't need the data, to make a preview it may */
1831 previewmask = CD_MASK_MDEFORMVERT;
1836 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1846 deformedVerts = inputVertexCos;
1848 /* Apply all leading deforming modifiers */
1849 for (; md; md = md->next, curr = curr->next) {
1850 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1854 if (!modifier_isEnabled(scene, md, required_mode)) {
1858 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) {
1862 if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
1864 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1866 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1872 /* grab modifiers until index i */
1873 if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index))
1877 /* Result of all leading deforming modifiers is cached for
1878 * places that wish to use the original mesh but with deformed
1879 * coordinates (vpaint, etc.)
1882 *r_deform = CDDM_from_mesh(me);
1884 if (build_shapekey_layers)
1885 add_shapekey_layers(dm, me, ob);
1887 if (deformedVerts) {
1888 CDDM_apply_vert_coords(*r_deform, deformedVerts);
1893 /* default behavior for meshes */
1895 deformedVerts = inputVertexCos;
1897 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1901 /* Now apply all remaining modifiers. If useDeform is off then skip
1908 for (; md; md = md->next, curr = curr->next) {
1909 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1913 if (!modifier_isEnabled(scene, md, required_mode)) {
1917 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) {
1921 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1922 modifier_setError(md, "Modifier requires original data, bad stack position");
1927 (!has_multires || multires_applied || sculpt_dyntopo))
1929 bool unsupported = false;
1931 if (md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0) {
1932 /* If multires is on level 0 skip it silently without warning message. */
1933 if (!sculpt_dyntopo) {
1938 if (sculpt_dyntopo && !useRenderParams)
1941 if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1942 unsupported |= (mti->type != eModifierTypeType_OnlyDeform);
1944 unsupported |= multires_applied;
1948 modifier_setError(md, "Not supported in dyntopo");
1950 modifier_setError(md, "Not supported in sculpt mode");
1954 modifier_setError(md, "Hide, Mask and optimized display disabled");
1958 if (need_mapping && !modifier_supportsMapping(md)) {
1962 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) {
1966 /* add an orco layer if needed by this modifier */
1967 if (mti->requiredDataMask)
1968 mask = mti->requiredDataMask(ob, md);
1972 if (dm && (mask & CD_MASK_ORCO))
1973 add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1975 /* How to apply modifier depends on (a) what we already have as
1976 * a result of previous modifiers (could be a DerivedMesh or just
1977 * deformed vertices) and (b) what type the modifier is.
1980 if (mti->type == eModifierTypeType_OnlyDeform) {
1981 /* No existing verts to deform, need to build them. */
1982 if (!deformedVerts) {
1984 /* Deforming a derived mesh, read the vertex locations
1985 * out of the mesh and deform them. Once done with this
1986 * run of deformers verts will be written back.
1988 numVerts = dm->getNumVerts(dm);
1990 MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
1991 dm->getVertCos(dm, deformedVerts);
1994 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1998 /* if this is not the last modifier in the stack then recalculate the normals
1999 * to avoid giving bogus normals to the next modifier see: [#23673] */
2000 if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
2001 /* XXX, this covers bug #23673, but we may need normal calc for other types */
2002 if (dm && dm->type == DM_TYPE_CDDM) {
2003 CDDM_apply_vert_coords(dm, deformedVerts);
2007 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
2012 /* determine which data layers are needed by following modifiers */
2014 nextmask = curr->next->mask;
2016 nextmask = dataMask;
2018 /* apply vertex coordinates or build a DerivedMesh as necessary */
2020 if (deformedVerts) {
2021 DerivedMesh *tdm = CDDM_copy(dm);
2025 CDDM_apply_vert_coords(dm, deformedVerts);
2029 dm = CDDM_from_mesh(me);
2030 ASSERT_IS_VALID_DM(dm);
2032 if (build_shapekey_layers)
2033 add_shapekey_layers(dm, me, ob);
2035 if (deformedVerts) {
2036 CDDM_apply_vert_coords(dm, deformedVerts);
2040 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2042 /* Constructive modifiers need to have an origindex
2043 * otherwise they wont have anywhere to copy the data from.
2045 * Also create ORIGINDEX data if any of the following modifiers
2046 * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
2047 * data by using generic DM_copy_vert_data() functions.
2049 if (need_mapping || (nextmask & CD_MASK_ORIGINDEX)) {
2051 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2052 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2053 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2055 /* Not worth parallelizing this, gives less than 0.1% overall speedup in best of best cases... */
2056 range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
2057 range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
2058 range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
2063 /* set the DerivedMesh to only copy needed data */
2065 /* needMapping check here fixes bug [#28112], otherwise it's
2066 * possible that it won't be copied */
2067 mask |= append_mask;
2068 DM_set_only_copy(dm, mask | (need_mapping ? CD_MASK_ORIGINDEX : 0));
2070 /* add cloth rest shape key if needed */
2071 if (mask & CD_MASK_CLOTH_ORCO)
2072 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
2074 /* add an origspace layer if needed */
2075 if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
2076 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2077 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2078 DM_init_origspace(dm);
2082 ndm = modwrap_applyModifier(md, ob, dm, app_flags);
2083 ASSERT_IS_VALID_DM(ndm);
2086 /* if the modifier returned a new dm, release the old one */
2087 if (dm && dm != ndm) dm->release(dm);
2091 if (deformedVerts) {
2092 if (deformedVerts != inputVertexCos)
2093 MEM_freeN(deformedVerts);
2095 deformedVerts = NULL;
2099 /* create an orco derivedmesh in parallel */
2100 if (nextmask & CD_MASK_ORCO) {
2102 orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
2104 nextmask &= ~CD_MASK_ORCO;
2105 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
2106 (mti->requiredDataMask ?
2107 mti->requiredDataMask(ob, md) : 0));
2109 ndm = modwrap_applyModifier(md, ob, orcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
2110 ASSERT_IS_VALID_DM(ndm);
2113 /* if the modifier returned a new dm, release the old one */
2114 if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2119 /* create cloth orco derivedmesh in parallel */
2120 if (nextmask & CD_MASK_CLOTH_ORCO) {
2122 clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
2124 nextmask &= ~CD_MASK_CLOTH_ORCO;
2125 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
2127 ndm = modwrap_applyModifier(md, ob, clothorcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
2128 ASSERT_IS_VALID_DM(ndm);
2131 /* if the modifier returned a new dm, release the old one */
2132 if (clothorcodm && clothorcodm != ndm) {
2133 clothorcodm->release(clothorcodm);
2139 /* in case of dynamic paint, make sure preview mask remains for following modifiers */
2140 /* XXX Temp and hackish solution! */
2141 if (md->type == eModifierType_DynamicPaint)
2142 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
2143 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
2144 else if ((md == previewmd) && (do_mod_wmcol)) {
2145 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2146 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
2149 dm->deformedOnly = false;
2152 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
2154 /* grab modifiers until index i */
2155 if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index))
2158 if (sculpt_mode && md->type == eModifierType_Multires) {
2159 multires_applied = true;
2163 for (md = firstmd; md; md = md->next)
2164 modifier_freeTemporaryData(md);
2166 /* Yay, we are done. If we have a DerivedMesh and deformed vertices
2167 * need to apply these back onto the DerivedMesh. If we have no
2168 * DerivedMesh then we need to build one.
2170 if (dm && deformedVerts) {
2171 finaldm = CDDM_copy(dm);
2175 CDDM_apply_vert_coords(finaldm, deformedVerts);
2177 #if 0 /* For later nice mod preview! */
2178 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
2180 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
2186 #if 0 /* For later nice mod preview! */
2187 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
2189 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
2193 finaldm = CDDM_from_mesh(me);
2195 if (build_shapekey_layers) {
2196 add_shapekey_layers(finaldm, me, ob);
2199 if (deformedVerts) {
2200 CDDM_apply_vert_coords(finaldm, deformedVerts);
2203 /* In this case, we should never have weight-modifying modifiers in stack... */
2205 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
2208 /* add an orco layer if needed */
2209 if (dataMask & CD_MASK_ORCO) {
2210 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
2212 if (r_deform && *r_deform)
2213 add_orco_dm(ob, NULL, *r_deform, NULL, CD_ORCO);
2216 if (do_loop_normals) {
2217 /* Compute loop normals (note: will compute poly and vert normals as well, if needed!) */
2218 DM_calc_loop_normals(finaldm, do_loop_normals, loop_normals_split_angle);
2221 if (sculpt_dyntopo == false) {
2222 /* watch this! after 2.75a we move to from tessface to looptri (by default) */
2223 if (dataMask & CD_MASK_MFACE) {
2224 DM_ensure_tessface(finaldm);
2227 /* without this, drawing ngon tri's faces will show ugly tessellated face
2228 * normals and will also have to calculate normals on the fly, try avoid
2229 * this where possible since calculating polygon normals isn't fast,
2230 * note that this isn't a problem for subsurf (only quads) or editmode
2231 * which deals with drawing differently.
2233 * Only calc vertex normals if they are flagged as dirty.
2234 * If using loop normals, poly nors have already been computed.
2236 if (!do_loop_normals) {
2237 dm_ensure_display_normals(finaldm);
2241 /* Some modifiers, like datatransfer, may generate those data as temp layer, we do not want to keep them,
2242 * as they are used by display code when available (i.e. even if autosmooth is disabled). */
2243 if (!do_loop_normals && CustomData_has_layer(&finaldm->loopData, CD_NORMAL)) {
2244 CustomData_free_layers(&finaldm->loopData, CD_NORMAL, finaldm->numLoopData);
2247 #ifdef WITH_GAMEENGINE
2248 /* NavMesh - this is a hack but saves having a NavMesh modifier */
2249 if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
2251 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
2252 if (finaldm != tdm) {
2253 finaldm->release(finaldm);
2257 DM_ensure_tessface(finaldm);
2259 #endif /* WITH_GAMEENGINE */
2264 orcodm->release(orcodm);
2266 clothorcodm->release(clothorcodm);
2268 if (deformedVerts && deformedVerts != inputVertexCos)
2269 MEM_freeN(deformedVerts);
2271 BLI_linklist_free((LinkNode *)datamasks, NULL);
2274 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *r_numVerts))[3]
2281 *r_numVerts = em->bm->totvert;
2283 cos = MEM_malloc_arrayN(em->bm->totvert, 3 * sizeof(float), "vertexcos");
2285 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
2286 copy_v3_v3(cos[i], eve->co);
2292 bool editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2294 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2295 const int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2297 if (!modifier_isEnabled(scene, md, required_mode)) {
2301 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2302 modifier_setError(md, "Modifier requires original data, bad stack position");
2309 static void editbmesh_calc_modifiers(
2310 Scene *scene, Object *ob, BMEditMesh *em,
2311 CustomDataMask dataMask,
2313 DerivedMesh **r_cage, DerivedMesh **r_final)
2315 ModifierData *md, *previewmd = NULL;
2316 float (*deformedVerts)[3] = NULL;
2317 CustomDataMask mask = 0, previewmask = 0, append_mask = 0;
2318 DerivedMesh *dm = NULL, *orcodm = NULL;
2319 int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2320 CDMaskLink *datamasks, *curr;
2321 const int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2322 int draw_flag = dm_drawflag_calc(scene->toolsettings, ob->data);
2324 // const bool do_mod_mcol = true; // (ob->mode == OB_MODE_OBJECT);
2325 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
2326 const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
2328 const bool do_final_wmcol = false;
2329 const bool do_init_wmcol = ((((Mesh *)ob->data)->drawflag & ME_DRAWEIGHT) && !do_final_wmcol);
2331 const bool do_init_statvis = ((((Mesh *)ob->data)->drawflag & ME_DRAW_STATVIS) && !do_init_wmcol);
2332 const bool do_mod_wmcol = do_init_wmcol;
2333 VirtualModifierData virtualModifierData;
2335 const bool do_loop_normals = (((Mesh *)(ob->data))->flag & ME_AUTOSMOOTH) != 0;
2336 const float loop_normals_split_angle = ((Mesh *)(ob->data))->smoothresh;
2338 modifiers_clearErrors(ob);
2340 if (r_cage && cageIndex == -1) {
2341 *r_cage = getEditDerivedBMesh(em, ob, dataMask, NULL);
2344 md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
2346 /* copied from mesh_calc_modifiers */
2348 previewmd = modifiers_getLastPreview(scene, md, required_mode);
2349 /* even if the modifier doesn't need the data, to make a preview it may */
2351 previewmask = CD_MASK_MDEFORMVERT;
2355 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
2358 for (i = 0; md; i++, md = md->next, curr = curr->next) {
2359 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2363 if (!editbmesh_modifier_is_enabled(scene, md, dm)) {
2367 /* add an orco layer if needed by this modifier */
2368 if (dm && mti->requiredDataMask) {
2369 mask = mti->requiredDataMask(ob, md);
2370 if (mask & CD_MASK_ORCO)
2371 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2374 /* How to apply modifier depends on (a) what we already have as
2375 * a result of previous modifiers (could be a DerivedMesh or just
2376 * deformed vertices) and (b) what type the modifier is.
2379 if (mti->type == eModifierTypeType_OnlyDeform) {
2380 /* No existing verts to deform, need to build them. */
2381 if (!deformedVerts) {
2383 /* Deforming a derived mesh, read the vertex locations
2384 * out of the mesh and deform them. Once done with this
2385 * run of deformers verts will be written back.
2387 numVerts = dm->getNumVerts(dm);
2389 MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
2390 dm->getVertCos(dm, deformedVerts);
2393 deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
2397 if (mti->deformVertsEM)
2398 modwrap_deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2400 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
2405 /* apply vertex coordinates or build a DerivedMesh as necessary */
2407 if (deformedVerts) {
2408 DerivedMesh *tdm = CDDM_copy(dm);
2409 if (!(r_cage && dm == *r_cage)) {
2414 CDDM_apply_vert_coords(dm, deformedVerts);
2416 else if (r_cage && dm == *r_cage) {
2417 /* dm may be changed by this modifier, so we need to copy it */
2423 dm = CDDM_from_editbmesh(em, false, false);
2424 ASSERT_IS_VALID_DM(dm);
2426 if (deformedVerts) {
2427 CDDM_apply_vert_coords(dm, deformedVerts);
2430 if (do_init_wmcol) {
2431 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2435 /* create an orco derivedmesh in parallel */
2437 if (mask & CD_MASK_ORCO) {
2439 orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
2441 mask &= ~CD_MASK_ORCO;
2442 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2444 if (mti->applyModifierEM) {
2445 ndm = modwrap_applyModifierEM(md, ob, em, orcodm, MOD_APPLY_ORCO);
2448 ndm = modwrap_applyModifier(md, ob, orcodm, MOD_APPLY_ORCO);
2450 ASSERT_IS_VALID_DM(ndm);
2453 /* if the modifier returned a new dm, release the old one */
2454 if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2459 /* set the DerivedMesh to only copy needed data */
2460 mask |= append_mask;
2461 mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
2463 DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2465 if (mask & CD_MASK_ORIGSPACE_MLOOP) {
2466 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2467 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2468 DM_init_origspace(dm);
2472 if (mti->applyModifierEM)
2473 ndm = modwrap_applyModifierEM(md, ob, em, dm, MOD_APPLY_USECACHE | MOD_APPLY_ALLOW_GPU);
2475 ndm = modwrap_applyModifier(md, ob, dm, MOD_APPLY_USECACHE | MOD_APPLY_ALLOW_GPU);
2476 ASSERT_IS_VALID_DM(ndm);
2479 if (dm && dm != ndm)
2484 if (deformedVerts) {
2485 MEM_freeN(deformedVerts);
2486 deformedVerts = NULL;
2490 dm->deformedOnly = false;
2493 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
2494 if ((md == previewmd) && (do_mod_wmcol)) {
2495 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2496 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
2499 if (r_cage && i == cageIndex) {
2500 if (dm && deformedVerts) {
2501 *r_cage = CDDM_copy(dm);
2502 CDDM_apply_vert_coords(*r_cage, deformedVerts);
2508 *r_cage = getEditDerivedBMesh(
2510 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2515 BLI_linklist_free((LinkNode *)datamasks, NULL);
2517 /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2518 * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2519 * then we need to build one.
2521 if (dm && deformedVerts) {
2522 *r_final = CDDM_copy(dm);
2524 if (!(r_cage && dm == *r_cage)) {
2528 CDDM_apply_vert_coords(*r_final, deformedVerts);
2533 else if (!deformedVerts && r_cage && *r_cage) {
2534 /* cage should already have up to date normals */
2537 /* In this case, we should never have weight-modifying modifiers in stack... */
2539 DM_update_weight_mcol(ob, *r_final, draw_flag, NULL, 0, NULL);
2540 if (do_init_statvis)
2541 DM_update_statvis_color(scene, ob, *r_final);
2544 /* this is just a copy of the editmesh, no need to calc normals */
2545 *r_final = getEditDerivedBMesh(em, ob, dataMask, deformedVerts);
2546 deformedVerts = NULL;
2548 /* In this case, we should never have weight-modifying modifiers in stack... */
2550 DM_update_weight_mcol(ob, *r_final, draw_flag, NULL, 0, NULL);
2551 if (do_init_statvis)
2552 DM_update_statvis_color(scene, ob, *r_final);
2555 if (do_loop_normals) {
2556 /* Compute loop normals */
2557 DM_calc_loop_normals(*r_final, do_loop_normals, loop_normals_split_angle);
2558 if (r_cage && *r_cage && (*r_cage != *r_final)) {
2559 DM_calc_loop_normals(*r_cage, do_loop_normals, loop_normals_split_angle);
2563 /* BMESH_ONLY, ensure tessface's used for drawing,
2564 * but don't recalculate if the last modifier in the stack gives us tessfaces
2565 * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2566 * but quiets annoying error messages since tessfaces wont be created. */
2567 if (dataMask & CD_MASK_MFACE) {
2568 if ((*r_final)->type != DM_TYPE_EDITBMESH) {
2569 DM_ensure_tessface(*r_final);
2571 if (r_cage && *r_cage) {
2572 if ((*r_cage)->type != DM_TYPE_EDITBMESH) {
2573 if (*r_cage != *r_final) {
2574 DM_ensure_tessface(*r_cage);
2581 /* same as mesh_calc_modifiers (if using loop normals, poly nors have already been computed). */
2582 if (!do_loop_normals) {
2583 dm_ensure_display_normals(*r_final);
2585 /* Some modifiers, like datatransfer, may generate those data, we do not want to keep them,
2586 * as they are used by display code when available (i.e. even if autosmooth is disabled). */
2587 if (CustomData_has_layer(&(*r_final)->loopData, CD_NORMAL)) {
2588 CustomData_free_layers(&(*r_final)->loopData, CD_NORMAL, (*r_final)->numLoopData);
2590 if (r_cage && CustomData_has_layer(&(*r_cage)->loopData, CD_NORMAL)) {
2591 CustomData_free_layers(&(*r_cage)->loopData, CD_NORMAL, (*r_cage)->numLoopData);
2595 /* add an orco layer if needed */
2596 if (dataMask & CD_MASK_ORCO)
2597 add_orco_dm(ob, em, *r_final, orcodm, CD_ORCO);
2600 orcodm->release(orcodm);
2603 MEM_freeN(deformedVerts);
2606 #ifdef WITH_OPENSUBDIV
2607 /* The idea is to skip CPU-side ORCO calculation when
2608 * we'll be using GPU backend of OpenSubdiv. This is so
2609 * playback performance is kept as high as possible.
2611 static bool calc_modifiers_skip_orco(Scene *scene,
2613 bool use_render_params)
2615 ModifierData *last_md = ob->modifiers.last;
2616 const int required_mode = use_render_params ? eModifierMode_Render : eModifierMode_Realtime;
2617 if (last_md != NULL &&
2618 last_md->type == eModifierType_Subsurf &&
2619 modifier_isEnabled(scene, last_md, required_mode))
2621 if (U.opensubdiv_compute_type == USER_OPENSUBDIV_COMPUTE_NONE) {
2624 else if ((ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)) != 0) {
2627 else if ((DAG_get_eval_flags_for_object(scene, ob) & DAG_EVAL_NEED_CPU) != 0) {
2630 SubsurfModifierData *smd = (SubsurfModifierData *)last_md;
2631 /* TODO(sergey): Deduplicate this with checks from subsurf_ccg.c. */
2632 return smd->use_opensubdiv != 0;
2638 static void mesh_build_data(
2639 Scene *scene, Object *ob, CustomDataMask dataMask,
2640 const bool build_shapekey_layers, const bool need_mapping)
2642 BLI_assert(ob->type == OB_MESH);
2644 BKE_object_free_derived_caches(ob);
2645 BKE_object_sculpt_modifiers_changed(ob);
2647 #ifdef WITH_OPENSUBDIV
2648 if (calc_modifiers_skip_orco(scene, ob, false)) {
2649 dataMask &= ~(CD_MASK_ORCO | CD_MASK_PREVIEW_MCOL);
2653 mesh_calc_modifiers(
2654 scene, ob, NULL, false, 1, need_mapping, dataMask, -1, true, build_shapekey_layers,
2656 &ob->derivedDeform, &ob->derivedFinal);
2658 DM_set_object_boundbox(ob, ob->derivedFinal);
2660 ob->derivedFinal->needsFree = 0;
2661 ob->derivedDeform->needsFree = 0;
2662 ob->lastDataMask = dataMask;
2663 ob->lastNeedMapping = need_mapping;
2665 if ((ob->mode & OB_MODE_ALL_SCULPT) && ob->sculpt) {
2666 /* create PBVH immediately (would be created on the fly too,
2667 * but this avoids waiting on first stroke) */
2669 BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
2672 BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS));
2675 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2677 BKE_object_free_derived_caches(obedit);
2678 BKE_object_sculpt_modifiers_changed(obedit);
2680 BKE_editmesh_free_derivedmesh(em);
2682 #ifdef WITH_OPENSUBDIV
2683 if (calc_modifiers_skip_orco(scene, obedit, false)) {
2684 dataMask &= ~(CD_MASK_ORCO | CD_MASK_PREVIEW_MCOL);
2688 editbmesh_calc_modifiers(
2689 scene, obedit, em, dataMask,
2690 &em->derivedCage, &em->derivedFinal);
2692 DM_set_object_boundbox(obedit, em->derivedFinal);
2694 em->lastDataMask = dataMask;
2695 em->derivedFinal->needsFree = 0;
2696 em->derivedCage->needsFree = 0;
2698 BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS));
2701 static CustomDataMask object_get_datamask(const Scene *scene, Object *ob, bool *r_need_mapping)
2703 Object *actob = scene->basact ? scene->basact->object : NULL;
2704 CustomDataMask mask = ob->customdata_mask;
2706 if (r_need_mapping) {
2707 *r_need_mapping = false;
2711 bool editing = BKE_paint_select_face_test(ob);
2713 /* weight paint and face select need original indices because of selection buffer drawing */
2714 if (r_need_mapping) {
2715 *r_need_mapping = (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT)));
2718 /* check if we need tfaces & mcols due to face select or texture paint */
2719 if ((ob->mode & OB_MODE_TEXTURE_PAINT) || editing) {
2720 mask |= CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL;
2723 /* check if we need mcols due to vertex paint or weightpaint */
2724 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2725 mask |= CD_MASK_MLOOPCOL;
2728 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2729 mask |= CD_MASK_PREVIEW_MLOOPCOL;
2732 if (ob->mode & OB_MODE_EDIT)
2733 mask |= CD_MASK_MVERT_SKIN;
2739 void makeDerivedMesh(
2740 Scene *scene, Object *ob, BMEditMesh *em,
2741 CustomDataMask dataMask, const bool build_shapekey_layers)
2744 dataMask |= object_get_datamask(scene, ob, &need_mapping);
2747 editbmesh_build_data(scene, ob, em, dataMask);
2750 mesh_build_data(scene, ob, dataMask, build_shapekey_layers, need_mapping);
2756 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2758 /* if there's no derived mesh or the last data mask used doesn't include
2759 * the data we need, rebuild the derived mesh
2762 dataMask |= object_get_datamask(scene, ob, &need_mapping);
2764 if (!ob->derivedFinal ||
2765 ((dataMask & ob->lastDataMask) != dataMask) ||
2766 (need_mapping != ob->lastNeedMapping))
2768 mesh_build_data(scene, ob, dataMask, false, need_mapping);
2771 if (ob->derivedFinal) { BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2772 return ob->derivedFinal;
2775 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2777 /* if there's no derived mesh or the last data mask used doesn't include
2778 * the data we need, rebuild the derived mesh
2782 dataMask |= object_get_datamask(scene, ob, &need_mapping);
2784 if (!ob->derivedDeform ||
2785 ((dataMask & ob->lastDataMask) != dataMask) ||
2786 (need_mapping != ob->lastNeedMapping))
2788 mesh_build_data(scene, ob, dataMask, false, need_mapping);
2791 return ob->derivedDeform;
2794 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2798 mesh_calc_modifiers(
2799 scene, ob, NULL, true, 1, false, dataMask, -1, false, false, false,
2805 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2809 mesh_calc_modifiers(
2810 scene, ob, NULL, true, 1, false, dataMask, index, false, false, false,
2816 DerivedMesh *mesh_create_derived_view(
2817 Scene *scene, Object *ob,
2818 CustomDataMask dataMask)
2823 * psys modifier updates particle state when called during dupli-list generation,
2824 * which can lead to wrong transforms. This disables particle system modifier execution.
2826 ob->transflag |= OB_NO_PSYS_UPDATE;
2828 mesh_calc_modifiers(
2829 scene, ob, NULL, false, 1, false, dataMask, -1, false, false, false,
2832 ob->transflag &= ~OB_NO_PSYS_UPDATE;
2837 DerivedMesh *mesh_create_derived_no_deform(
2838 Scene *scene, Object *ob, float (*vertCos)[3],
2839 CustomDataMask dataMask)
2843 mesh_calc_modifiers(
2844 scene, ob, vertCos, false, 0, false, dataMask, -1, false, false, false,
2850 DerivedMesh *mesh_create_derived_no_virtual(
2851 Scene *scene, Object *ob, float (*vertCos)[3],
2852 CustomDataMask dataMask)
2856 mesh_calc_modifiers(
2857 scene, ob, vertCos, false, -1, false, dataMask, -1, false, false, false,
2863 DerivedMesh *mesh_create_derived_physics(
2864 Scene *scene, Object *ob, float (*vertCos)[3],
2865 CustomDataMask dataMask)
2869 mesh_calc_modifiers(
2870 scene, ob, vertCos, false, -1, true, dataMask, -1, false, false, false,
2876 DerivedMesh *mesh_create_derived_no_deform_render(
2877 Scene *scene, Object *ob,
2878 float (*vertCos)[3],
2879 CustomDataMask dataMask)
2883 mesh_calc_modifiers(
2884 scene, ob, vertCos, true, 0, false, dataMask, -1, false, false, false,
2892 DerivedMesh *editbmesh_get_derived_cage_and_final(
2893 Scene *scene, Object *obedit, BMEditMesh *em,
2894 CustomDataMask dataMask,
2896 DerivedMesh **r_final)
2898 /* if there's no derived mesh or the last data mask used doesn't include
2899 * the data we need, rebuild the derived mesh
2901 dataMask |= object_get_datamask(scene, obedit, NULL);
2903 if (!em->derivedCage ||
2904 (em->lastDataMask & dataMask) != dataMask)
2906 editbmesh_build_data(scene, obedit, em, dataMask);
2909 *r_final = em->derivedFinal;
2910 if (em->derivedFinal) { BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2911 return em->derivedCage;
2914 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2916 /* if there's no derived mesh or the last data mask used doesn't include
2917 * the data we need, rebuild the derived mesh
2919 dataMask |= object_get_datamask(scene, obedit, NULL);
2921 if (!em->derivedCage ||
2922 (em->lastDataMask & dataMask) != dataMask)
2924 editbmesh_build_data(scene, obedit, em, dataMask);
2927 return em->derivedCage;
2930 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em, CustomDataMask data_mask)
2932 return getEditDerivedBMesh(em, obedit, data_mask, NULL);
2937 /* get derived mesh from an object, using editbmesh if available. */
2938 DerivedMesh *object_get_derived_final(Object *ob, const bool for_render)
2941 /* TODO(sergey): use proper derived render here in the future. */
2942 return ob->derivedFinal;
2945 /* only return the editmesh if its from this object because
2946 * we don't a mesh from another object's modifier stack: T43122 */
2947 if (ob->type == OB_MESH) {
2948 Mesh *me = ob->data;
2949 BMEditMesh *em = me->edit_btmesh;
2950 if (em && (em->ob == ob)) {
2951 DerivedMesh *dm = em->derivedFinal;
2956 return ob->derivedFinal;
2963 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2965 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2966 const float no_f[3], const short no_s[3])
2968 DMCoNo *co_no = &((DMCoNo *)userData)[index];
2970 /* check if we've been here before (normal should not be 0) */
2971 if (!is_zero_v3(co_no->no)) {
2975 copy_v3_v3(co_no->co, co);
2977 copy_v3_v3(co_no->no, no_f);
2980 normal_short_to_float_v3(co_no->no, no_s);
2984 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2985 /* this is needed for all code using vertexgroups (no subsurf support) */
2986 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2987 /* in use now by vertex/weight paint and particle generating */
2989 DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2991 Mesh *me = ob->data;
2993 DMCoNo *vertexcosnos;
2995 /* lets prevent crashing... */
2996 if (ob->type != OB_MESH || me->totvert == 0)
2999 dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
3001 if (dm->foreachMappedVert) {
3002 vertexcosnos = MEM_calloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
3003 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
3006 DMCoNo *v_co_no = vertexcosnos = MEM_malloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
3008 for (a = 0; a < me->totvert; a++, v_co_no++) {
3009 dm->getVertCo(dm, a, v_co_no->co);
3010 dm->getVertNo(dm, a, v_co_no->no);
3015 return vertexcosnos;
3020 /* same as above but for vert coords */
3022 float (*vertexcos)[3];
3023 BLI_bitmap *vertex_visit;
3026 static void make_vertexcos__mapFunc(
3027 void *userData, int index, const float co[3],
3028 const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
3030 MappedUserData *mappedData = (MappedUserData *)userData;
3032 if (BLI_BITMAP_TEST(mappedData->vertex_visit, index) == 0) {
3033 /* we need coord from prototype vertex, not from copies,
3034 * assume they stored in the beginning of vertex array stored in DM
3035 * (mirror modifier for eg does this) */
3036 copy_v3_v3(mappedData->vertexcos[index], co);
3037 BLI_BITMAP_ENABLE(mappedData->vertex_visit, index);
3041 void mesh_get_mapped_verts_coords(DerivedMesh *dm, float (*r_cos)[3], const int totcos)
3043 if (dm->foreachMappedVert) {
3044 MappedUserData userData;
3045 memset(r_cos, 0, sizeof(*r_cos) * totcos);
3046 userData.vertexcos = r_cos;
3047 userData.vertex_visit = BLI_BITMAP_NEW(totcos, "vertexcos flags");
3048 dm->foreachMappedVert(dm, make_vertexcos__mapFunc, &userData, DM_FOREACH_NOP);
3049 MEM_freeN(userData.vertex_visit);
3053 for (i = 0; i < totcos; i++) {
3054 dm->getVertCo(dm, i, r_cos[i]);
3059 /* ******************* GLSL ******************** */
3061 /** \name Tangent Space Calculation
3064 /* Necessary complexity to handle looptri's as quads for correct tangents */
3065 #define USE_LOOPTRI_DETECT_QUADS
3068 float (*precomputedFaceNormals)[3];
3069 float (*precomputedLoopNormals)[3];
3070 const MLoopTri *looptri;
3071 MLoopUV *mloopuv; /* texture coordinates */
3072 MPoly *mpoly; /* indices */
3073 MLoop *mloop; /* indices */
3074 MVert *mvert; /* vertices & normals */
3076 float (*tangent)[4]; /* destination */
3079 #ifdef USE_LOOPTRI_DETECT_QUADS
3080 /* map from 'fake' face index to looptri,
3081 * quads will point to the first looptri of the quad */
3082 const int *face_as_quad_map;
3083 int num_face_as_quad_map;
3086 } SGLSLMeshToTangent;
3089 #include "mikktspace.h"
3091 static int dm_ts_GetNumFaces(const SMikkTSpaceContext *pContext)
3093 SGLSLMeshToTangent *pMesh = pContext->m_pUserData;
3095 #ifdef USE_LOOPTRI_DETECT_QUADS
3096 return pMesh->num_face_as_quad_map;
3098 return pMesh->numTessFaces;
3102 static int dm_ts_GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
3104 #ifdef USE_LOOPTRI_DETECT_QUADS
3105 SGLSLMeshToTangent *pMesh = pContext->m_pUserData;
3106 if (pMesh->face_as_quad_map) {
3107 const MLoopTri *lt = &pMesh->looptri[pMesh->face_as_quad_map[face_num]];
3108 const MPoly *mp = &pMesh->mpoly[lt->poly];
3109 if (mp->totloop == 4) {
3115 UNUSED_VARS(pContext, face_num);
3120 static void dm_ts_GetPosition(
3121 const SMikkTSpaceContext *pContext, float r_co[3],
3122 const int face_num, const int vert_index)
3124 //assert(vert_index >= 0 && vert_index < 4);
3125 SGLSLMeshToTangent *pMesh = pContext->m_pUserData;
3130 #ifdef USE_LOOPTRI_DETECT_QUADS
3131 if (pMesh->face_as_quad_map) {
3132 lt = &pMesh->looptri[pMesh->face_as_quad_map[face_num]];
3133 const MPoly *mp = &pMesh->mpoly[lt->poly];
3134 if (mp->totloop == 4) {
3135 loop_index = mp->loopstart + vert_index;
3138 /* fall through to regular triangle */
3141 lt = &pMesh->looptri[face_num];
3144 lt = &pMesh->looptri[face_num];
3146 loop_index = lt->tri[vert_index];
3149 co = pMesh->mvert[pMesh->mloop[loop_index].v].co;
3150 copy_v3_v3(r_co, co);
3153 static void dm_ts_GetTextureCoordinate(
3154 const SMikkTSpaceContext *pContext, float r_uv[2],
3155 const int face_num, const int vert_index)
3157 //assert(vert_index >= 0 && vert_index < 4);
3158 SGLSLMeshToTangent *pMesh = pContext->m_pUserData;
3162 #ifdef USE_LOOPTRI_DETECT_QUADS
3163 if (pMesh->face_as_quad_map) {
3164 lt = &pMesh->looptri[pMesh->face_as_quad_map[face_num]];
3165 const MPoly *mp = &pMesh->mpoly[lt->poly];
3166 if (mp->totloop == 4) {
3167 loop_index = mp->loopstart + vert_index;
3170 /* fall through to regular triangle */
3173 lt = &pMesh->looptri[face_num];
3176 lt = &pMesh->looptri[face_num];
3178 loop_index = lt->tri[vert_index];
3181 if (pMesh->mloopuv != NULL) {
3182 const float *uv = pMesh->mloopuv[loop_index].uv;
3183 copy_v2_v2(r_uv, uv);
3186 const float *orco = pMesh->orco[pMesh->mloop[loop_index].v];
3187 map_to_sphere(&r_uv[0], &r_uv[1], orco[0], orco[1], orco[2]);
3191 static void dm_ts_GetNormal(
3192 const SMikkTSpaceContext *pContext, float r_no[3],
3193 const int face_num, const int vert_index)
3195 //assert(vert_index >= 0 && vert_index < 4);
3196 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
3200 #ifdef USE_LOOPTRI_DETECT_QUADS
3201 if (pMesh->face_as_quad_map) {
3202 lt = &pMesh->looptri[pMesh->face_as_quad_map[face_num]];
3203 const MPoly *mp = &pMesh->mpoly[lt->poly];
3204 if (mp->totloop == 4) {
3205 loop_index = mp->loopstart + vert_index;
3208 /* fall through to regular triangle */
3211 lt = &pMesh->looptri[face_num];
3214 lt = &pMesh->looptri[face_num];
3216 loop_index = lt->tri[vert_index];
3219 if (pMesh->precomputedLoopNormals) {
3220 copy_v3_v3(r_no, pMesh->precomputedLoopNormals[loop_index]);
3222 else if ((pMesh->mpoly[lt->poly].flag & ME_SMOOTH) == 0) { /* flat */
3223 if (pMesh->precomputedFaceNormals) {
3224 copy_v3_v3(r_no, pMesh->precomputedFaceNormals[lt->poly]);
3227 #ifdef USE_LOOPTRI_DETECT_QUADS
3228 const MPoly *mp = &pMesh->mpoly[lt->poly];
3229 if (mp->totloop == 4) {
3232 pMesh->mvert[pMesh->mloop[mp->loopstart + 0].v].co,
3233 pMesh->mvert[pMesh->mloop[mp->loopstart + 1].v].co,
3234 pMesh->mvert[pMesh->mloop[mp->loopstart + 2].v].co,
3235 pMesh->mvert[pMesh->mloop[mp->loopstart + 3].v].co);
3242 pMesh->mvert[pMesh->mloop[lt->tri[0]].v].co,
3243 pMesh->mvert[pMesh->mloop[lt->tri[1]].v].co,
3244 pMesh->mvert[pMesh->mloop[lt->tri[2]].v].co);
3249 const short *no = pMesh->mvert[pMesh->mloop[loop_index].v].no;
3250 normal_short_to_float_v3(r_no, no);
3254 static void dm_ts_SetTSpace(
3255 const SMikkTSpaceContext *pContext, const float fvTangent[3], const float fSign,
3256 const int face_num, const int vert_index)
3258 //assert(vert_index >= 0 && vert_index < 4);
3259 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
3263 #ifdef USE_LOOPTRI_DETECT_QUADS
3264 if (pMesh->face_as_quad_map) {
3265 lt = &pMesh->looptri[pMesh->face_as_quad_map[face_num]];
3266 const MPoly *mp = &pMesh->mpoly[lt->poly];
3267 if (mp->totloop == 4) {
3268 loop_index = mp->loopstart + vert_index;
3271 /* fall through to regular triangle */
3274 lt = &pMesh->looptri[face_num];
3277 lt = &pMesh->looptri[face_num];
3279 loop_index = lt->tri[vert_index];
3284 pRes = pMesh->tangent[loop_index];
3285 copy_v3_v3(pRes, fvTangent);
3289 void DM_calc_tangents_names_from_gpu(
3290 const GPUVertexAttribs *gattribs,
3291 char (*tangent_names)[MAX_NAME], int *r_tangent_names_count)
3294 for (int b = 0; b < gattribs->totlayer; b++) {
3295 if (gattribs->layer[b].type == CD_TANGENT) {
3296 strcpy(tangent_names[count++], gattribs->layer[b].name);
3299 *r_tangent_names_count = count;
3302 static void DM_calc_loop_tangents_thread(TaskPool * __restrict UNUSED(pool), void *taskdata, int UNUSED(threadid))
3304 struct SGLSLMeshToTangent *mesh2tangent = taskdata;
3305 /* new computation method */
3307 SMikkTSpaceContext sContext = {NULL};
3308 SMikkTSpaceInterface sInterface = {NULL};
3310 sContext.m_pUserData = mesh2tangent;
3311 sContext.m_pInterface = &sInterface;
3312 sInterface.m_getNumFaces = dm_ts_GetNumFaces;
3313 sInterface.m_getNumVerticesOfFace = dm_ts_GetNumVertsOfFace;
3314 sInterface.m_getPosition = dm_ts_GetPosition;
3315 sInterface.m_getTexCoord = dm_ts_GetTextureCoordinate;
3316 sInterface.m_getNormal = dm_ts_GetNormal;
3317 sInterface.m_setTSpaceBasic = dm_ts_SetTSpace;
3320 genTangSpaceDefault(&sContext);
3324 void DM_add_named_tangent_layer_for_uv(
3325 CustomData *uv_data, CustomData *tan_data, int numLoopData,
3326 const char *layer_name)
3328 if (CustomData_get_named_layer_index(tan_data, CD_TANGENT, layer_name) == -1 &&
3329 CustomData_get_named_layer_index(uv_data, CD_MLOOPUV, layer_name) != -1)
3331 CustomData_add_layer_named(
3332 tan_data, CD_TANGENT, CD_CALLOC, NULL,
3333 numLoopData, layer_name);
3338 * Here we get some useful information such as active uv layer name and search if it is already in tangent_names.
3339 * Also, we calculate tangent_mask that works as a descriptor of tangents state.
3340 * If tangent_mask has changed, then recalculate tangents.
3342 void DM_calc_loop_tangents_step_0(
3343 const CustomData *loopData, bool calc_active_tangent,
3344 const char (*tangent_names)[MAX_NAME], int tangent_names_count,
3345 bool *rcalc_act, bool *rcalc_ren, int *ract_uv_n, int *rren_uv_n,
3346 char *ract_uv_name, char *rren_uv_name, short *rtangent_mask)
3348 /* Active uv in viewport */
3349 int layer_index = CustomData_get_layer_index(loopData, CD_MLOOPUV);
3350 *ract_uv_n = CustomData_get_active_layer(loopData, CD_MLOOPUV);
3351 ract_uv_name[0] = 0;
3352 if (*ract_uv_n != -1) {
3353 strcpy(ract_uv_name, loopData->layers[*ract_uv_n + layer_index].name);
3356 /* Active tangent in render */
3357 *rren_uv_n = CustomData_get_render_layer(loopData, CD_MLOOPUV);
3358 rren_uv_name[0] = 0;
3359 if (*rren_uv_n != -1) {
3360 strcpy(rren_uv_name, loopData->layers[*rren_uv_n + layer_index].name);
3363 /* If active tangent not in tangent_names we take it into account */
3366 for (int i = 0; i < tangent_names_count; i++) {
3367 if (tangent_names[i][0] == 0) {
3368 calc_active_tangent = true;
3371 if (calc_active_tangent) {
3374 for (int i = 0; i < tangent_names_count; i++) {
3375 if (STREQ(ract_uv_name, tangent_names[i]))
3377 if (STREQ(rren_uv_name, tangent_names[i]))
3383 const int uv_layer_num = CustomData_number_of_layers(loopData, CD_MLOOPUV);
3384 for (int n = 0; n < uv_layer_num; n++) {
3385 const char *name = CustomData_get_layer_name(loopData, CD_MLOOPUV, n);
3387 for (int i = 0; i < tangent_names_count; i++) {
3388 if (tangent_names[i][0] && STREQ(tangent_names[i], name)) {
3393 if ((*rcalc_act && ract_uv_name[0] && STREQ(ract_uv_name, name)) ||
3394 (*rcalc_ren && rren_uv_name[0] && STREQ(rren_uv_name, name)))
3399 *rtangent_mask |= 1 << n;
3402 if (uv_layer_num == 0)
3403 *rtangent_mask |= DM_TANGENT_MASK_ORCO;
3406 void DM_calc_loop_tangents(
3407 DerivedMesh *dm, bool calc_active_tangent,
3408 const char (*tangent_names)[MAX_NAME], int tangent_names_count)
3412 bool calc_act = false;
3413 bool calc_ren = false;
3414 char act_uv_name[MAX_NAME];
3415 char ren_uv_name[MAX_NAME];
3416 short tangent_mask = 0;
3417 DM_calc_loop_tangents_step_0(
3418 &dm->loopData, calc_active_tangent, tangent_names, tangent_names_count,
3419 &calc_act, &calc_ren, &act_uv_n, &ren_uv_n, act_uv_name, ren_uv_name, &tangent_mask);
3420 if ((dm->tangent_mask | tangent_mask) != dm->tangent_mask) {
3421 /* Check we have all the needed layers */
3422 MPoly *mpoly = dm->getPolyArray(dm);
3423 const MLoopTri *looptri = dm->getLoopTriArray(dm);
3424 int totface = dm->getNumLoopTri(dm);
3425 /* Allocate needed tangent layers */
3426 for (int i = 0; i < tangent_names_count; i++)
3427 if (tangent_names[i][0])
3428 DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, tangent_names[i]);
3429 if ((tangent_mask & DM_TANGENT_MASK_ORCO) && CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, "") == -1)
3430 CustomData_add_layer_named(&dm->loopData, CD_TANGENT, CD_CALLOC, NULL, dm->numLoopData, "");
3431 if (calc_act && act_uv_name[0])
3432 DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, act_uv_name);
3433 if (calc_ren && ren_uv_name[0])
3434 DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, ren_uv_name);
3436 #ifdef USE_LOOPTRI_DETECT_QUADS
3437 int num_face_as_quad_map;
3438 int *face_as_quad_map = NULL;
3440 /* map faces to quads */
3441 if (totface != dm->getNumPolys(dm)) {
3442 /* over alloc, since we dont know how many ngon or quads we have */
3444 /* map fake face index to looptri */
3445 face_as_quad_map = MEM_malloc_arrayN(totface, sizeof(int), __func__);
3447 for (k = 0, j = 0; j < totface; k++, j++) {
3448 face_as_quad_map[k] = j;
3449 /* step over all quads */
3450 if (mpoly[looptri[j].poly].totloop == 4) {
3451 j++; /* skips the nest looptri */
3454 num_face_as_quad_map = k;
3457 num_face_as_quad_map = totface;
3463 TaskScheduler *scheduler = BLI_task_scheduler_get();
3464 TaskPool *task_pool;
3465 task_pool = BLI_task_pool_create(scheduler, NULL);
3467 dm->tangent_mask = 0;
3468 /* Calculate tangent layers */
3469 SGLSLMeshToTangent data_array[MAX_MTFACE];
3470 const int tangent_layer_num = CustomData_number_of_layers(&dm->loopData, CD_TANGENT);
3471 for (int n = 0; n < tangent_layer_num; n++) {
3472 int index = CustomData_get_layer_index_n(&dm->loopData, CD_TANGENT, n);
3473 BLI_assert(n < MAX_MTFACE);
3474 SGLSLMeshToTangent *mesh2tangent = &data_array[n];
3475 mesh2tangent->numTessFaces = totface;
3476 #ifdef USE_LOOPTRI_DETECT_QUADS
3477 mesh2tangent->face_as_quad_map = face_as_quad_map;