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) 2004 by 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/editors/mesh/meshtools.c
31 * meshtools.c: no editmode (violated already :), mirror & join),
32 * tools operating on meshes
35 #include "MEM_guardedalloc.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_key_types.h"
39 #include "DNA_material_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_view3d_types.h"
47 #include "BLI_blenlib.h"
50 #include "BLI_kdtree.h"
51 #include "BKE_context.h"
52 #include "BKE_depsgraph.h"
53 #include "BKE_deform.h"
54 #include "BKE_DerivedMesh.h"
56 #include "BKE_library.h"
59 #include "BKE_material.h"
60 #include "BKE_report.h"
61 #include "BKE_editmesh.h"
62 #include "BKE_multires.h"
65 #include "ED_object.h"
66 #include "ED_view3d.h"
71 /* * ********************** no editmode!!! *********** */
73 /*********************** JOIN ***************************/
75 /* join selected meshes into the active mesh, context sensitive
76 * return 0 if no join is made (error) and 1 if the join is done */
78 int join_mesh_exec(bContext *C, wmOperator *op)
80 Main *bmain = CTX_data_main(C);
81 Scene *scene = CTX_data_scene(C);
82 Object *ob = CTX_data_active_object(C);
83 Material **matar, *ma;
89 Key *key, *nkey = NULL;
90 KeyBlock *kb, *okb, *kbn;
91 float imat[4][4], cmat[4][4], *fp1, *fp2;
92 int a, b, totcol, totmat = 0, totedge = 0, totvert = 0;
93 int totloop = 0, totpoly = 0, vertofs, *matmap = NULL;
94 int i, j, index, haskey = 0, edgeofs, loopofs, polyofs;
96 bDeformGroup *dg, *odg;
98 CustomData vdata, edata, fdata, ldata, pdata;
101 BKE_report(op->reports, RPT_WARNING, "Cannot join while in edit mode");
102 return OPERATOR_CANCELLED;
105 /* ob is the object we are adding geometry to */
106 if (!ob || ob->type != OB_MESH) {
107 BKE_report(op->reports, RPT_WARNING, "Active object is not a mesh");
108 return OPERATOR_CANCELLED;
112 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
114 if (base->object->type == OB_MESH) {
115 me = base->object->data;
117 totvert += me->totvert;
118 totedge += me->totedge;
119 totloop += me->totloop;
120 totpoly += me->totpoly;
121 totmat += base->object->totcol;
123 if (base->object == ob)
126 /* check for shapekeys */
133 /* that way the active object is always selected */
135 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected mesh");
136 return OPERATOR_CANCELLED;
139 /* only join meshes if there are verts to join, there aren't too many, and we only had one mesh selected */
140 me = (Mesh *)ob->data;
143 if (totvert == 0 || totvert == me->totvert) {
144 BKE_report(op->reports, RPT_WARNING, "No mesh data to join");
145 return OPERATOR_CANCELLED;
148 if (totvert > MESH_MAX_VERTS) {
149 BKE_reportf(op->reports, RPT_WARNING, "Joining results in %d vertices, limit is %ld", totvert, MESH_MAX_VERTS);
150 return OPERATOR_CANCELLED;
153 /* remove tessface to ensure we don't hold references to invalid faces */
154 BKE_mesh_tessface_clear(me);
156 /* new material indices and material array */
157 matar = MEM_callocN(sizeof(void *) * totmat, "join_mesh matar");
158 if (totmat) matmap = MEM_callocN(sizeof(int) * totmat, "join_mesh matmap");
161 /* obact materials in new main array, is nicer start! */
162 for (a = 0; a < ob->totcol; a++) {
163 matar[a] = give_current_material(ob, a + 1);
164 id_us_plus((ID *)matar[a]);
165 /* increase id->us : will be lowered later */
168 /* - if destination mesh had shapekeys, move them somewhere safe, and set up placeholders
169 * with arrays that are large enough to hold shapekey data for all meshes
170 * - if destination mesh didn't have shapekeys, but we encountered some in the meshes we're
171 * joining, set up a new keyblock and assign to the mesh
174 /* make a duplicate copy that will only be used here... (must remember to free it!) */
175 nkey = BKE_key_copy(key);
177 /* for all keys in old block, clear data-arrays */
178 for (kb = key->block.first; kb; kb = kb->next) {
179 if (kb->data) MEM_freeN(kb->data);
180 kb->data = MEM_callocN(sizeof(float) * 3 * totvert, "join_shapekey");
181 kb->totelem = totvert;
185 /* add a new key-block and add to the mesh */
186 key = me->key = BKE_key_add((ID *)me);
187 key->type = KEY_RELATIVE;
190 /* first pass over objects - copying materials and vertexgroups across */
191 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
193 /* only act if a mesh, and not the one we're joining to */
194 if ((ob != base->object) && (base->object->type == OB_MESH)) {
195 me = base->object->data;
197 /* Join this object's vertex groups to the base one's */
198 for (dg = base->object->defbase.first; dg; dg = dg->next) {
199 /* See if this group exists in the object (if it doesn't, add it to the end) */
200 if (!defgroup_find_name(ob, dg->name)) {
201 odg = MEM_callocN(sizeof(bDeformGroup), "join deformGroup");
202 memcpy(odg, dg, sizeof(bDeformGroup));
203 BLI_addtail(&ob->defbase, odg);
206 if (ob->defbase.first && ob->actdef == 0)
211 /* Add this object's materials to the base one's if they don't exist already (but only if limits not exceeded yet) */
212 if (totcol < MAXMAT) {
213 for (a = 1; a <= base->object->totcol; a++) {
214 ma = give_current_material(base->object, a);
216 for (b = 0; b < totcol; b++) {
217 if (ma == matar[b]) break;
226 if (totcol >= MAXMAT)
231 /* if this mesh has shapekeys, check if destination mesh already has matching entries too */
232 if (me->key && key) {
233 /* for remapping KeyBlock.relative */
234 int *index_map = MEM_mallocN(sizeof(int) * me->key->totkey, __func__);
235 KeyBlock **kb_map = MEM_mallocN(sizeof(KeyBlock *) * me->key->totkey, __func__);
237 for (kb = me->key->block.first, i = 0; kb; kb = kb->next, i++) {
238 BLI_assert(i < me->key->totkey);
240 kbn = BKE_keyblock_find_name(key, kb->name);
241 /* if key doesn't exist in destination mesh, add it */
243 index_map[i] = BLI_findindex(&key->block, kbn);
246 index_map[i] = key->totkey;
248 kbn = BKE_keyblock_add(key, kb->name);
250 BKE_keyblock_copy_settings(kbn, kb);
252 /* adjust settings to fit (allocate a new data-array) */
253 kbn->data = MEM_callocN(sizeof(float) * 3 * totvert, "joined_shapekey");
254 kbn->totelem = totvert;
256 /* XXX 2.5 Animato */
258 /* also, copy corresponding ipo-curve to ipo-block if applicable */
259 if (me->key->ipo && key->ipo) {
260 /* FIXME... this is a luxury item! */
261 puts("FIXME: ignoring IPO's when joining shapekeys on Meshes for now...");
269 /* remap relative index values */
270 for (kb = me->key->block.first, i = 0; kb; kb = kb->next, i++) {
271 if (LIKELY(kb->relative < me->key->totkey)) { /* sanity check, should always be true */
272 kb_map[i]->relative = index_map[kb->relative];
276 MEM_freeN(index_map);
285 /* setup new data for destination mesh */
286 CustomData_reset(&vdata);
287 CustomData_reset(&edata);
288 CustomData_reset(&fdata);
289 CustomData_reset(&ldata);
290 CustomData_reset(&pdata);
292 mvert = CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
293 medge = CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
294 mloop = CustomData_add_layer(&ldata, CD_MLOOP, CD_CALLOC, NULL, totloop);
295 mpoly = CustomData_add_layer(&pdata, CD_MPOLY, CD_CALLOC, NULL, totpoly);
302 /* inverse transform for all selected meshes in this object */
303 invert_m4_m4(imat, ob->obmat);
305 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
307 /* only join if this is a mesh */
308 if (base->object->type == OB_MESH) {
309 me = base->object->data;
313 /* merge customdata flag */
314 ((Mesh *)ob->data)->cd_flag |= me->cd_flag;
317 CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
318 CustomData_copy_data_named(&me->vdata, &vdata, 0, vertofs, me->totvert);
321 dvert = CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
323 /* NB: vertex groups here are new version */
325 for (i = 0; i < me->totvert; i++) {
326 for (j = 0; j < dvert[i].totweight; j++) {
327 /* Find the old vertex group */
328 odg = BLI_findlink(&base->object->defbase, dvert[i].dw[j].def_nr);
330 /* Search for a match in the new object, and set new index */
331 for (dg = ob->defbase.first, index = 0; dg; dg = dg->next, index++) {
332 if (STREQ(dg->name, odg->name)) {
333 dvert[i].dw[j].def_nr = index;
342 /* if this is the object we're merging into, no need to do anything */
343 if (base->object != ob) {
344 /* watch this: switch matmul order really goes wrong */
345 mul_m4_m4m4(cmat, imat, base->object->obmat);
347 /* transform vertex coordinates into new space */
348 for (a = 0, mv = mvert; a < me->totvert; a++, mv++) {
349 mul_m4_v3(cmat, mv->co);
352 /* for each shapekey in destination mesh:
353 * - if there's a matching one, copy it across (will need to transform vertices into new space...)
354 * - otherwise, just copy own coordinates of mesh (no need to transform vertex coordinates into new space)
357 /* if this mesh has any shapekeys, check first, otherwise just copy coordinates */
358 for (kb = key->block.first; kb; kb = kb->next) {
359 /* get pointer to where to write data for this mesh in shapekey's data array */
360 fp1 = ((float *)kb->data) + (vertofs * 3);
362 /* check if this mesh has such a shapekey */
363 okb = me->key ? BKE_keyblock_find_name(me->key, kb->name) : NULL;
366 /* copy this mesh's shapekey to the destination shapekey (need to transform first) */
367 fp2 = ((float *)(okb->data));
368 for (a = 0; a < me->totvert; a++, fp1 += 3, fp2 += 3) {
369 copy_v3_v3(fp1, fp2);
370 mul_m4_v3(cmat, fp1);
374 /* copy this mesh's vertex coordinates to the destination shapekey */
376 for (a = 0; a < me->totvert; a++, fp1 += 3, mv++) {
377 copy_v3_v3(fp1, mv->co);
384 /* for each shapekey in destination mesh:
385 * - if it was an 'original', copy the appropriate data from nkey
386 * - otherwise, copy across plain coordinates (no need to transform coordinates)
389 for (kb = key->block.first; kb; kb = kb->next) {
390 /* get pointer to where to write data for this mesh in shapekey's data array */
391 fp1 = ((float *)kb->data) + (vertofs * 3);
393 /* check if this was one of the original shapekeys */
394 okb = nkey ? BKE_keyblock_find_name(nkey, kb->name) : NULL;
396 /* copy this mesh's shapekey to the destination shapekey */
397 fp2 = ((float *)(okb->data));
398 for (a = 0; a < me->totvert; a++, fp1 += 3, fp2 += 3) {
399 copy_v3_v3(fp1, fp2);
403 /* copy base-coordinates to the destination shapekey */
405 for (a = 0; a < me->totvert; a++, fp1 += 3, mv++) {
406 copy_v3_v3(fp1, mv->co);
413 /* advance mvert pointer to end of base mesh's data */
414 mvert += me->totvert;
418 CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
419 CustomData_copy_data_named(&me->edata, &edata, 0, edgeofs, me->totedge);
421 for (a = 0; a < me->totedge; a++, medge++) {
422 medge->v1 += vertofs;
423 medge->v2 += vertofs;
428 if (base->object != ob) {
429 MultiresModifierData *mmd;
431 multiresModifier_prepare_join(scene, base->object, ob);
433 if ((mmd = get_multires_modifier(scene, base->object, true))) {
434 ED_object_iter_other(bmain, base->object, true,
435 ED_object_multires_update_totlevels_cb,
440 CustomData_merge(&me->ldata, &ldata, CD_MASK_MESH, CD_DEFAULT, totloop);
441 CustomData_copy_data_named(&me->ldata, &ldata, 0, loopofs, me->totloop);
443 for (a = 0; a < me->totloop; a++, mloop++) {
451 /* make mapping for materials */
452 for (a = 1; a <= base->object->totcol; a++) {
453 ma = give_current_material(base->object, a);
455 for (b = 0; b < totcol; b++) {
456 if (ma == matar[b]) {
464 CustomData_merge(&me->pdata, &pdata, CD_MASK_MESH, CD_DEFAULT, totpoly);
465 CustomData_copy_data_named(&me->pdata, &pdata, 0, polyofs, me->totpoly);
467 for (a = 0; a < me->totpoly; a++, mpoly++) {
468 mpoly->loopstart += loopofs;
469 mpoly->mat_nr = matmap ? matmap[(int)mpoly->mat_nr] : 0;
472 polyofs += me->totpoly;
475 /* these are used for relinking (cannot be set earlier,
476 * or else reattaching goes wrong)
478 vertofs += me->totvert;
479 edgeofs += me->totedge;
480 loopofs += me->totloop;
482 /* free base, now that data is merged */
483 if (base->object != ob)
484 ED_base_object_free_and_unlink(bmain, scene, base);
489 /* return to mesh we're merging to */
492 CustomData_free(&me->vdata, me->totvert);
493 CustomData_free(&me->edata, me->totedge);
494 CustomData_free(&me->ldata, me->totloop);
495 CustomData_free(&me->pdata, me->totpoly);
497 me->totvert = totvert;
498 me->totedge = totedge;
499 me->totloop = totloop;
500 me->totpoly = totpoly;
507 /* tessface data removed above, no need to update */
508 BKE_mesh_update_customdata_pointers(me, false);
510 /* update normals in case objects with non-uniform scale are joined */
511 BKE_mesh_calc_normals(me);
513 /* old material array */
514 for (a = 1; a <= ob->totcol; a++) {
519 for (a = 1; a <= me->totcol; a++) {
524 if (ob->mat) MEM_freeN(ob->mat);
525 if (ob->matbits) MEM_freeN(ob->matbits);
526 if (me->mat) MEM_freeN(me->mat);
527 ob->mat = me->mat = NULL;
532 ob->mat = MEM_callocN(sizeof(void *) * totcol, "join obmatar");
533 ob->matbits = MEM_callocN(sizeof(char) * totcol, "join obmatbits");
538 ob->totcol = me->totcol = totcol;
540 if (matmap) MEM_freeN(matmap);
542 /* other mesh users */
543 test_object_materials(bmain, (ID *)me);
545 /* free temp copy of destination shapekeys (if applicable) */
547 /* XXX 2.5 Animato */
549 /* free it's ipo too - both are not actually freed from memory yet as ID-blocks */
551 BKE_ipo_free(nkey->ipo);
552 BLI_remlink(&bmain->ipo, nkey->ipo);
553 MEM_freeN(nkey->ipo);
558 BLI_remlink(&bmain->key, nkey);
562 /* ensure newly inserted keys are time sorted */
563 if (key && (key->type != KEY_RELATIVE)) {
568 DAG_relations_tag_update(bmain); // removed objects, need to rebuild dag
571 ED_object_editmode_enter(C, EM_WAITCURSOR);
572 ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
574 /* toggle editmode using lower level functions so this can be called from python */
575 EDBM_mesh_make(scene->toolsettings, ob);
577 EDBM_mesh_free(me->edit_btmesh);
578 MEM_freeN(me->edit_btmesh);
579 me->edit_btmesh = NULL;
580 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
582 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
584 return OPERATOR_FINISHED;
587 /*********************** JOIN AS SHAPES ***************************/
589 /* Append selected meshes vertex locations as shapes of the active mesh,
590 * return 0 if no join is made (error) and 1 of the join is done */
592 int join_mesh_shapes_exec(bContext *C, wmOperator *op)
594 Scene *scene = CTX_data_scene(C);
595 Object *ob = CTX_data_active_object(C);
596 Mesh *me = (Mesh *)ob->data;
598 DerivedMesh *dm = NULL;
601 bool ok = false, nonequal_verts = false;
603 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
605 if (base->object == ob) continue;
607 if (base->object->type == OB_MESH) {
608 selme = (Mesh *)base->object->data;
610 if (selme->totvert == me->totvert)
620 BKE_report(op->reports, RPT_WARNING, "Selected meshes must have equal numbers of vertices");
622 BKE_report(op->reports, RPT_WARNING, "No additional selected meshes with equal vertex count to join");
623 return OPERATOR_CANCELLED;
627 key = me->key = BKE_key_add((ID *)me);
628 key->type = KEY_RELATIVE;
630 /* first key added, so it was the basis. initialize it with the existing mesh */
631 kb = BKE_keyblock_add(key, NULL);
632 BKE_keyblock_convert_from_mesh(me, kb);
635 /* now ready to add new keys from selected meshes */
636 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
638 if (base->object == ob) continue;
640 if (base->object->type == OB_MESH) {
641 selme = (Mesh *)base->object->data;
643 if (selme->totvert == me->totvert) {
644 dm = mesh_get_derived_deform(scene, base->object, CD_MASK_BAREMESH);
648 kb = BKE_keyblock_add(key, base->object->id.name + 2);
650 DM_to_meshkey(dm, me, kb);
658 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
660 return OPERATOR_FINISHED;
663 /* -------------------------------------------------------------------- */
664 /* Mesh Mirror (Spatial) */
666 /** \name Mesh Spatial Mirror API
669 #define KD_THRESH 0.00002f
671 static struct { void *tree; } MirrKdStore = {NULL};
673 /* mode is 's' start, or 'e' end, or 'u' use */
674 /* if end, ob can be NULL */
675 int ED_mesh_mirror_spatial_table(Object *ob, BMEditMesh *em, const float co[3], char mode)
677 if (mode == 'u') { /* use table */
678 if (MirrKdStore.tree == NULL)
679 ED_mesh_mirror_spatial_table(ob, em, NULL, 's');
681 if (MirrKdStore.tree) {
682 KDTreeNearest nearest;
686 i = BLI_kdtree_find_nearest(MirrKdStore.tree, co, &nearest);
689 if (nearest.dist < KD_THRESH) {
696 else if (mode == 's') { /* start table */
700 if (MirrKdStore.tree) /* happens when entering this call without ending it */
701 ED_mesh_mirror_spatial_table(ob, em, co, 'e');
703 if (em && me->edit_btmesh == em) {
704 totvert = em->bm->totvert;
707 totvert = me->totvert;
710 MirrKdStore.tree = BLI_kdtree_new(totvert);
712 if (em && me->edit_btmesh == em) {
718 /* this needs to be valid for index lookups later (callers need) */
719 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
721 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
722 BLI_kdtree_insert(MirrKdStore.tree, i, eve->co);
729 for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
730 BLI_kdtree_insert(MirrKdStore.tree, i, mvert->co);
734 BLI_kdtree_balance(MirrKdStore.tree);
736 else if (mode == 'e') { /* end table */
737 if (MirrKdStore.tree) {
738 BLI_kdtree_free(MirrKdStore.tree);
739 MirrKdStore.tree = NULL;
752 /* -------------------------------------------------------------------- */
753 /* Mesh Mirror (Topology) */
755 /** \name Mesh Topology Mirror API
758 static MirrTopoStore_t mesh_topo_store = {NULL, -1. - 1, -1};
760 /* mode is 's' start, or 'e' end, or 'u' use */
761 /* if end, ob can be NULL */
762 /* note, is supposed return -1 on error, which callers are currently checking for, but is not used so far */
763 int ED_mesh_mirror_topo_table(Object *ob, char mode)
765 if (mode == 'u') { /* use table */
766 if (ED_mesh_mirrtopo_recalc_check(ob->data, ob->mode, &mesh_topo_store)) {
767 ED_mesh_mirror_topo_table(ob, 's');
770 else if (mode == 's') { /* start table */
771 ED_mesh_mirrtopo_init(ob->data, ob->mode, &mesh_topo_store, false);
773 else if (mode == 'e') { /* end table */
774 ED_mesh_mirrtopo_free(&mesh_topo_store);
786 static int mesh_get_x_mirror_vert_spatial(Object *ob, int index)
792 mvert = me->mvert + index;
793 vec[0] = -mvert->co[0];
794 vec[1] = mvert->co[1];
795 vec[2] = mvert->co[2];
797 return ED_mesh_mirror_spatial_table(ob, NULL, vec, 'u');
800 static int mesh_get_x_mirror_vert_topo(Object *ob, int index)
802 if (ED_mesh_mirror_topo_table(ob, 'u') == -1)
805 return mesh_topo_store.index_lookup[index];
808 int mesh_get_x_mirror_vert(Object *ob, int index, const bool use_topology)
811 return mesh_get_x_mirror_vert_topo(ob, index);
814 return mesh_get_x_mirror_vert_spatial(ob, index);
818 static BMVert *editbmesh_get_x_mirror_vert_spatial(Object *ob, BMEditMesh *em, const float co[3])
823 /* ignore nan verts */
824 if ((finite(co[0]) == false) ||
825 (finite(co[1]) == false) ||
826 (finite(co[2]) == false))
835 i = ED_mesh_mirror_spatial_table(ob, em, vec, 'u');
837 return BM_vert_at_index(em->bm, i);
842 static BMVert *editbmesh_get_x_mirror_vert_topo(Object *ob, struct BMEditMesh *em, BMVert *eve, int index)
845 if (ED_mesh_mirror_topo_table(ob, 'u') == -1)
853 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
859 if (index == em->bm->totvert) {
864 poinval = mesh_topo_store.index_lookup[index];
867 return (BMVert *)(poinval);
871 BMVert *editbmesh_get_x_mirror_vert(Object *ob, struct BMEditMesh *em, BMVert *eve, const float co[3], int index, const bool use_topology)
874 return editbmesh_get_x_mirror_vert_topo(ob, em, eve, index);
877 return editbmesh_get_x_mirror_vert_spatial(ob, em, co);
882 * Wrapper for objectmode/editmode.
884 * call #BM_mesh_elem_table_ensure first for editmesh.
886 int ED_mesh_mirror_get_vert(Object *ob, int index)
889 BMEditMesh *em = me->edit_btmesh;
890 bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
894 BMVert *eve, *eve_mirr;
895 eve = BM_vert_at_index(em->bm, index);
896 eve_mirr = editbmesh_get_x_mirror_vert(ob, em, eve, eve->co, index, use_topology);
897 index_mirr = eve_mirr ? BM_elem_index_get(eve_mirr) : -1;
900 index_mirr = mesh_get_x_mirror_vert(ob, index, use_topology);
908 static float *editmesh_get_mirror_uv(BMEditMesh *em, int axis, float *uv, float *mirrCent, float *face_cent)
914 /* ignore nan verts */
915 if (isnan(uv[0]) || !finite(uv[0]) ||
916 isnan(uv[1]) || !finite(uv[1])
922 vec[1] = -((uv[1]) - mirrCent[1]) + mirrCent[1];
924 cent_vec[0] = face_cent[0];
925 cent_vec[1] = -((face_cent[1]) - mirrCent[1]) + mirrCent[1];
928 vec[0] = -((uv[0]) - mirrCent[0]) + mirrCent[0];
931 cent_vec[0] = -((face_cent[0]) - mirrCent[0]) + mirrCent[0];
932 cent_vec[1] = face_cent[1];
935 /* TODO - Optimize */
940 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
941 uv_poly_center(efa, cent, cd_loop_uv_offset);
943 if ( (fabsf(cent[0] - cent_vec[0]) < 0.001f) && (fabsf(cent[1] - cent_vec[1]) < 0.001f) ) {
947 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
948 MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
949 if ( (fabsf(luv->uv[0] - vec[0]) < 0.001f) && (fabsf(luv->uv[1] - vec[1]) < 0.001f) ) {
963 static unsigned int mirror_facehash(const void *ptr)
965 const MFace *mf = ptr;
969 v0 = MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
970 v1 = MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
973 v0 = MIN3(mf->v1, mf->v2, mf->v3);
974 v1 = MAX3(mf->v1, mf->v2, mf->v3);
977 return ((v0 * 39) ^ (v1 * 31));
980 static int mirror_facerotation(MFace *a, MFace *b)
983 if (a->v1 == b->v1 && a->v2 == b->v2 && a->v3 == b->v3 && a->v4 == b->v4)
985 else if (a->v4 == b->v1 && a->v1 == b->v2 && a->v2 == b->v3 && a->v3 == b->v4)
987 else if (a->v3 == b->v1 && a->v4 == b->v2 && a->v1 == b->v3 && a->v2 == b->v4)
989 else if (a->v2 == b->v1 && a->v3 == b->v2 && a->v4 == b->v3 && a->v1 == b->v4)
993 if (a->v1 == b->v1 && a->v2 == b->v2 && a->v3 == b->v3)
995 else if (a->v3 == b->v1 && a->v1 == b->v2 && a->v2 == b->v3)
997 else if (a->v2 == b->v1 && a->v3 == b->v2 && a->v1 == b->v3)
1004 static bool mirror_facecmp(const void *a, const void *b)
1006 return (mirror_facerotation((MFace *)a, (MFace *)b) == -1);
1009 /* BMESH_TODO, convert to MPoly (functions above also) */
1010 int *mesh_get_x_mirror_faces(Object *ob, BMEditMesh *em)
1012 Mesh *me = ob->data;
1013 MVert *mv, *mvert = me->mvert;
1014 MFace mirrormf, *mf, *hashmf, *mface = me->mface;
1016 const bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1017 int *mirrorverts, *mirrorfaces;
1020 mirrorverts = MEM_callocN(sizeof(int) * me->totvert, "MirrorVerts");
1021 mirrorfaces = MEM_callocN(sizeof(int) * 2 * me->totface, "MirrorFaces");
1023 ED_mesh_mirror_spatial_table(ob, em, NULL, 's');
1025 for (a = 0, mv = mvert; a < me->totvert; a++, mv++)
1026 mirrorverts[a] = mesh_get_x_mirror_vert(ob, a, use_topology);
1028 ED_mesh_mirror_spatial_table(ob, em, NULL, 'e');
1030 fhash = BLI_ghash_new_ex(mirror_facehash, mirror_facecmp, "mirror_facehash gh", me->totface);
1031 for (a = 0, mf = mface; a < me->totface; a++, mf++)
1032 BLI_ghash_insert(fhash, mf, mf);
1034 for (a = 0, mf = mface; a < me->totface; a++, mf++) {
1035 mirrormf.v1 = mirrorverts[mf->v3];
1036 mirrormf.v2 = mirrorverts[mf->v2];
1037 mirrormf.v3 = mirrorverts[mf->v1];
1038 mirrormf.v4 = (mf->v4) ? mirrorverts[mf->v4] : 0;
1040 /* make sure v4 is not 0 if a quad */
1041 if (mf->v4 && mirrormf.v4 == 0) {
1042 SWAP(unsigned int, mirrormf.v1, mirrormf.v3);
1043 SWAP(unsigned int, mirrormf.v2, mirrormf.v4);
1046 hashmf = BLI_ghash_lookup(fhash, &mirrormf);
1048 mirrorfaces[a * 2] = hashmf - mface;
1049 mirrorfaces[a * 2 + 1] = mirror_facerotation(&mirrormf, hashmf);
1052 mirrorfaces[a * 2] = -1;
1055 BLI_ghash_free(fhash, NULL, NULL);
1056 MEM_freeN(mirrorverts);
1061 /* selection, vertex and face */
1062 /* returns 0 if not found, otherwise 1 */
1065 * Face selection in object mode,
1066 * currently only weight-paint and vertex-paint use this.
1068 * \return boolean true == Found
1070 bool ED_mesh_pick_face(bContext *C, Object *ob, const int mval[2], unsigned int *index, int size)
1073 Mesh *me = ob->data;
1075 BLI_assert(me && GS(me->id.name) == ID_ME);
1077 if (!me || me->totpoly == 0)
1080 view3d_set_viewcontext(C, &vc);
1083 /* sample rect to increase chances of selecting, so that when clicking
1084 * on an edge in the backbuf, we can still select a face */
1087 *index = ED_view3d_backbuf_sample_rect(&vc, mval, size, 1, me->totpoly + 1, &dummy_dist);
1090 /* sample only on the exact position */
1091 *index = ED_view3d_backbuf_sample(&vc, mval[0], mval[1]);
1094 if ((*index) == 0 || (*index) > (unsigned int)me->totpoly)
1101 static void ed_mesh_pick_face_vert__mpoly_find(
1103 struct ARegion *ar, const float mval[2],
1105 DerivedMesh *dm, MPoly *mp, MLoop *mloop,
1107 float *r_len_best, int *r_v_idx_best)
1110 int j = mp->totloop;
1111 for (ml = &mloop[mp->loopstart]; j--; ml++) {
1112 float co[3], sco[2], len;
1113 const int v_idx = ml->v;
1114 dm->getVertCo(dm, v_idx, co);
1115 if (ED_view3d_project_float_object(ar, co, sco, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1116 len = len_manhattan_v2v2(mval, sco);
1117 if (len < *r_len_best) {
1119 *r_v_idx_best = v_idx;
1125 * Use when the back buffer stores face index values. but we want a vert.
1126 * This gets the face then finds the closest vertex to mval.
1128 bool ED_mesh_pick_face_vert(bContext *C, Object *ob, const int mval[2], unsigned int *index, int size)
1130 unsigned int poly_index;
1131 Mesh *me = ob->data;
1133 BLI_assert(me && GS(me->id.name) == ID_ME);
1135 if (ED_mesh_pick_face(C, ob, mval, &poly_index, size)) {
1136 Scene *scene = CTX_data_scene(C);
1137 struct ARegion *ar = CTX_wm_region(C);
1139 /* derived mesh to find deformed locations */
1140 DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
1142 int v_idx_best = ORIGINDEX_NONE;
1144 /* find the vert closest to 'mval' */
1145 const float mval_f[2] = {UNPACK2(mval)};
1146 float len_best = FLT_MAX;
1150 unsigned int dm_mpoly_tot;
1151 const int *index_mp_to_orig;
1153 dm_mpoly = dm->getPolyArray(dm);
1154 dm_mloop = dm->getLoopArray(dm);
1156 dm_mpoly_tot = dm->getNumPolys(dm);
1158 index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1160 /* tag all verts using this face */
1161 if (index_mp_to_orig) {
1164 for (i = 0; i < dm_mpoly_tot; i++) {
1165 if (index_mp_to_orig[i] == poly_index) {
1166 ed_mesh_pick_face_vert__mpoly_find(
1168 dm, &dm_mpoly[i], dm_mloop,
1169 &len_best, &v_idx_best);
1174 if (poly_index < dm_mpoly_tot) {
1175 ed_mesh_pick_face_vert__mpoly_find(
1177 dm, &dm_mpoly[poly_index], dm_mloop,
1178 &len_best, &v_idx_best);
1182 /* map 'dm -> me' index if possible */
1183 if (v_idx_best != ORIGINDEX_NONE) {
1184 const int *index_mv_to_orig;
1186 index_mv_to_orig = dm->getVertDataArray(dm, CD_ORIGINDEX);
1187 if (index_mv_to_orig) {
1188 v_idx_best = index_mv_to_orig[v_idx_best];
1194 if ((v_idx_best != ORIGINDEX_NONE) && (v_idx_best < me->totvert)) {
1195 *index = v_idx_best;
1204 * Vertex selection in object mode,
1205 * currently only weight paint uses this.
1207 * \return boolean true == Found
1209 typedef struct VertPickData {
1211 const float *mval_f; /* [2] */
1219 static void ed_mesh_pick_vert__mapFunc(void *userData, int index, const float co[3],
1220 const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
1222 VertPickData *data = userData;
1223 if ((data->mvert[index].flag & ME_HIDE) == 0) {
1226 if (ED_view3d_project_float_object(data->ar, co, sco, V3D_PROJ_TEST_CLIP_DEFAULT) == V3D_PROJ_RET_OK) {
1227 const float len = len_manhattan_v2v2(data->mval_f, sco);
1228 if (len < data->len_best) {
1229 data->len_best = len;
1230 data->v_idx_best = index;
1235 bool ED_mesh_pick_vert(bContext *C, Object *ob, const int mval[2], unsigned int *index, int size, bool use_zbuf)
1238 Mesh *me = ob->data;
1240 BLI_assert(me && GS(me->id.name) == ID_ME);
1242 if (!me || me->totvert == 0)
1245 view3d_set_viewcontext(C, &vc);
1249 /* sample rect to increase chances of selecting, so that when clicking
1250 * on an face in the backbuf, we can still select a vert */
1253 *index = ED_view3d_backbuf_sample_rect(&vc, mval, size, 1, me->totvert + 1, &dummy_dist);
1256 /* sample only on the exact position */
1257 *index = ED_view3d_backbuf_sample(&vc, mval[0], mval[1]);
1260 if ((*index) == 0 || (*index) > (unsigned int)me->totvert)
1266 /* derived mesh to find deformed locations */
1267 DerivedMesh *dm = mesh_get_derived_final(vc.scene, ob, CD_MASK_BAREMESH);
1268 ARegion *ar = vc.ar;
1269 RegionView3D *rv3d = ar->regiondata;
1271 /* find the vert closest to 'mval' */
1272 const float mval_f[2] = {(float)mval[0],
1275 VertPickData data = {NULL};
1277 ED_view3d_init_mats_rv3d(ob, rv3d);
1284 data.mvert = me->mvert;
1286 data.mval_f = mval_f;
1287 data.len_best = FLT_MAX;
1288 data.v_idx_best = -1;
1290 dm->foreachMappedVert(dm, ed_mesh_pick_vert__mapFunc, &data, DM_FOREACH_NOP);
1294 if (data.v_idx_best == -1) {
1298 *index = data.v_idx_best;
1305 MDeformVert *ED_mesh_active_dvert_get_em(Object *ob, BMVert **r_eve)
1307 if (ob->mode & OB_MODE_EDIT && ob->type == OB_MESH && ob->defbase.first) {
1308 Mesh *me = ob->data;
1309 BMesh *bm = me->edit_btmesh->bm;
1310 const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
1312 if (cd_dvert_offset != -1) {
1313 BMVert *eve = BM_mesh_active_vert_get(bm);
1316 if (r_eve) *r_eve = eve;
1317 return BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1322 if (r_eve) *r_eve = NULL;
1326 MDeformVert *ED_mesh_active_dvert_get_ob(Object *ob, int *r_index)
1328 Mesh *me = ob->data;
1329 int index = BKE_mesh_mselect_active_get(me, ME_VSEL);
1330 if (r_index) *r_index = index;
1331 if (index == -1 || me->dvert == NULL) {
1335 return me->dvert + index;
1339 MDeformVert *ED_mesh_active_dvert_get_only(Object *ob)
1341 if (ob->type == OB_MESH) {
1342 if (ob->mode & OB_MODE_EDIT) {
1343 return ED_mesh_active_dvert_get_em(ob, NULL);
1346 return ED_mesh_active_dvert_get_ob(ob, NULL);