Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / mesh / editmesh_tools.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2004 by Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joseph Eagar
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_tools.c
29  *  \ingroup edmesh
30  */
31
32 #include <stddef.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_key_types.h"
37 #include "DNA_material_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_bitmap.h"
45 #include "BLI_heap_simple.h"
46 #include "BLI_listbase.h"
47 #include "BLI_linklist.h"
48 #include "BLI_linklist_stack.h"
49 #include "BLI_noise.h"
50 #include "BLI_math.h"
51 #include "BLI_rand.h"
52 #include "BLI_sort_utils.h"
53 #include "BLI_string.h"
54
55 #include "BKE_editmesh.h"
56 #include "BKE_context.h"
57 #include "BKE_deform.h"
58 #include "BKE_key.h"
59 #include "BKE_layer.h"
60 #include "BKE_library.h"
61 #include "BKE_main.h"
62 #include "BKE_material.h"
63 #include "BKE_mesh.h"
64 #include "BKE_report.h"
65 #include "BKE_texture.h"
66
67 #include "DEG_depsgraph.h"
68 #include "DEG_depsgraph_build.h"
69
70 #include "BLT_translation.h"
71
72 #include "RNA_define.h"
73 #include "RNA_access.h"
74 #include "RNA_enum_types.h"
75
76 #include "WM_api.h"
77 #include "WM_types.h"
78
79 #include "ED_mesh.h"
80 #include "ED_object.h"
81 #include "ED_screen.h"
82 #include "ED_transform.h"
83 #include "ED_transform_snap_object_context.h"
84 #include "ED_uvedit.h"
85 #include "ED_view3d.h"
86
87 #include "RE_render_ext.h"
88
89 #include "UI_interface.h"
90 #include "UI_resources.h"
91
92 #include "mesh_intern.h"  /* own include */
93
94 #include "bmesh_tools.h"
95
96 #define USE_FACE_CREATE_SEL_EXTEND
97
98 /* -------------------------------------------------------------------- */
99 /** \name Subdivide Operator
100  * \{ */
101
102 static int edbm_subdivide_exec(bContext *C, wmOperator *op)
103 {
104         const int cuts = RNA_int_get(op->ptr, "number_cuts");
105         const float smooth = RNA_float_get(op->ptr, "smoothness");
106         const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f;
107         const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal");
108
109         if (RNA_boolean_get(op->ptr, "ngon") &&
110             RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT)
111         {
112                 RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT);
113         }
114         const int quad_corner_type = RNA_enum_get(op->ptr, "quadcorner");
115         const bool use_quad_tri = !RNA_boolean_get(op->ptr, "ngon");
116         const int seed = RNA_int_get(op->ptr, "seed");
117
118         ViewLayer *view_layer = CTX_data_view_layer(C);
119         uint objects_len = 0;
120         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
121
122         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
123                 Object *obedit = objects[ob_index];
124                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
125
126                 if (!(em->bm->totedgesel || em->bm->totfacesel)) {
127                         continue;
128                 }
129
130                 BM_mesh_esubdivide(
131                         em->bm, BM_ELEM_SELECT,
132                         smooth, SUBD_FALLOFF_LIN, false,
133                         fractal, along_normal,
134                         cuts,
135                         SUBDIV_SELECT_ORIG, quad_corner_type,
136                         use_quad_tri, true, false,
137                         seed);
138
139                 EDBM_update_generic(em, true, true);
140         }
141
142         MEM_freeN(objects);
143
144         return OPERATOR_FINISHED;
145 }
146
147 /* Note, these values must match delete_mesh() event values */
148 static const EnumPropertyItem prop_mesh_cornervert_types[] = {
149         {SUBD_CORNER_INNERVERT,     "INNERVERT", 0,      "Inner Vert", ""},
150         {SUBD_CORNER_PATH,          "PATH", 0,           "Path", ""},
151         {SUBD_CORNER_STRAIGHT_CUT,  "STRAIGHT_CUT", 0,   "Straight Cut", ""},
152         {SUBD_CORNER_FAN,           "FAN", 0,            "Fan", ""},
153         {0, NULL, 0, NULL, NULL}
154 };
155
156 void MESH_OT_subdivide(wmOperatorType *ot)
157 {
158         PropertyRNA *prop;
159
160         /* identifiers */
161         ot->name = "Subdivide";
162         ot->description = "Subdivide selected edges";
163         ot->idname = "MESH_OT_subdivide";
164
165         /* api callbacks */
166         ot->exec = edbm_subdivide_exec;
167         ot->poll = ED_operator_editmesh;
168
169         /* flags */
170         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
171
172         /* properties */
173         prop = RNA_def_int(ot->srna, "number_cuts", 1, 1, 100, "Number of Cuts", "", 1, 10);
174         /* avoid re-using last var because it can cause _very_ high poly meshes and annoy users (or worse crash) */
175         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
176
177         RNA_def_float(ot->srna, "smoothness", 0.0f, 0.0f, 1e3f, "Smoothness", "Smoothness factor", 0.0f, 1.0f);
178
179         WM_operatortype_props_advanced_begin(ot);
180
181         RNA_def_boolean(ot->srna, "ngon", true, "Create N-Gons", "When disabled, newly created faces are limited to 3-4 sided faces");
182         RNA_def_enum(ot->srna, "quadcorner", prop_mesh_cornervert_types, SUBD_CORNER_STRAIGHT_CUT,
183                      "Quad Corner Type", "How to subdivide quad corners (anything other than Straight Cut will prevent ngons)");
184
185         RNA_def_float(ot->srna, "fractal", 0.0f, 0.0f, 1e6f, "Fractal", "Fractal randomness factor", 0.0f, 1000.0f);
186         RNA_def_float(ot->srna, "fractal_along_normal", 0.0f, 0.0f, 1.0f,
187                       "Along Normal", "Apply fractal displacement along normal only", 0.0f, 1.0f);
188         RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Random Seed", "Seed for the random number generator", 0, 255);
189 }
190
191 /** \} */
192
193 /* -------------------------------------------------------------------- */
194 /** \name Edge Ring Subdivide Operator
195  *
196  * Bridge code shares props.
197  *
198  * \{ */
199
200 struct EdgeRingOpSubdProps {
201         int interp_mode;
202         int cuts;
203         float smooth;
204
205         int profile_shape;
206         float profile_shape_factor;
207 };
208
209
210 static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_min, const int cuts_default)
211 {
212         /* Note, these values must match delete_mesh() event values */
213         static const EnumPropertyItem prop_subd_edgering_types[] = {
214                 {SUBD_RING_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
215                 {SUBD_RING_INTERP_PATH, "PATH", 0, "Blend Path", ""},
216                 {SUBD_RING_INTERP_SURF, "SURFACE", 0, "Blend Surface", ""},
217                 {0, NULL, 0, NULL, NULL}
218         };
219
220         PropertyRNA *prop;
221
222         prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, 1000, "Number of Cuts", "", cuts_min, 64);
223         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
224
225         RNA_def_enum(ot->srna, "interpolation", prop_subd_edgering_types, SUBD_RING_INTERP_PATH,
226                      "Interpolation", "Interpolation method");
227
228         RNA_def_float(ot->srna, "smoothness", 1.0f, 0.0f, 1e3f,
229                       "Smoothness", "Smoothness factor", 0.0f, 2.0f);
230
231         /* profile-shape */
232         RNA_def_float(ot->srna, "profile_shape_factor", 0.0f, -1e3f, 1e3f,
233                       "Profile Factor", "How much intermediary new edges are shrunk/expanded", -2.0f, 2.0f);
234
235         prop = RNA_def_property(ot->srna, "profile_shape", PROP_ENUM, PROP_NONE);
236         RNA_def_property_enum_items(prop, rna_enum_proportional_falloff_curve_only_items);
237         RNA_def_property_enum_default(prop, PROP_SMOOTH);
238         RNA_def_property_ui_text(prop, "Profile Shape", "Shape of the profile");
239         RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_CURVE); /* Abusing id_curve :/ */
240 }
241
242 static void mesh_operator_edgering_props_get(wmOperator *op, struct EdgeRingOpSubdProps *op_props)
243 {
244         op_props->interp_mode = RNA_enum_get(op->ptr, "interpolation");
245         op_props->cuts = RNA_int_get(op->ptr, "number_cuts");
246         op_props->smooth = RNA_float_get(op->ptr, "smoothness");
247
248         op_props->profile_shape = RNA_enum_get(op->ptr, "profile_shape");
249         op_props->profile_shape_factor = RNA_float_get(op->ptr, "profile_shape_factor");
250 }
251
252 static int edbm_subdivide_edge_ring_exec(bContext *C, wmOperator *op)
253 {
254
255         ViewLayer *view_layer = CTX_data_view_layer(C);
256         uint objects_len = 0;
257         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
258         struct EdgeRingOpSubdProps op_props;
259
260         mesh_operator_edgering_props_get(op, &op_props);
261
262         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
263                 Object *obedit = objects[ob_index];
264                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
265
266                 if (em->bm->totedgesel == 0) {
267                         continue;
268                 }
269
270                 if (!EDBM_op_callf(
271                         em, op,
272                         "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f "
273                         "profile_shape=%i profile_shape_factor=%f",
274                         BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth,
275                         op_props.profile_shape, op_props.profile_shape_factor))
276                 {
277                         continue;
278                 }
279
280                 EDBM_update_generic(em, true, true);
281         }
282
283         MEM_freeN(objects);
284         return OPERATOR_FINISHED;
285 }
286
287 void MESH_OT_subdivide_edgering(wmOperatorType *ot)
288 {
289         /* identifiers */
290         ot->name = "Subdivide Edge-Ring";
291         ot->idname = "MESH_OT_subdivide_edgering";
292
293         /* api callbacks */
294         ot->exec = edbm_subdivide_edge_ring_exec;
295         ot->poll = ED_operator_editmesh;
296
297         /* flags */
298         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
299
300         /* properties */
301         mesh_operator_edgering_props(ot, 1, 10);
302 }
303
304 /** \} */
305
306 /* -------------------------------------------------------------------- */
307 /** \name Un-Subdivide Operator
308  * \{ */
309
310 static int edbm_unsubdivide_exec(bContext *C, wmOperator *op)
311 {
312         const int iterations = RNA_int_get(op->ptr, "iterations");
313         ViewLayer *view_layer = CTX_data_view_layer(C);
314         uint objects_len = 0;
315         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode(view_layer, CTX_wm_view3d(C), &objects_len);
316         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
317                 Object *obedit = objects[ob_index];
318                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
319
320                 if ((em->bm->totvertsel == 0) &&
321                     (em->bm->totedgesel == 0) &&
322                     (em->bm->totfacesel == 0))
323                 {
324                         continue;
325                 }
326
327                 BMOperator bmop;
328                 EDBM_op_init(em, &bmop, op,
329                        "unsubdivide verts=%hv iterations=%i", BM_ELEM_SELECT, iterations);
330
331                 BMO_op_exec(em->bm, &bmop);
332
333                 if (!EDBM_op_finish(em, &bmop, op, true)) {
334                         continue;
335                 }
336
337                 if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
338                         EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);  /* need to flush vert->face first */
339                 }
340                 EDBM_selectmode_flush(em);
341
342                 EDBM_update_generic(em, true, true);
343         }
344         MEM_freeN(objects);
345
346         return OPERATOR_FINISHED;
347 }
348
349 void MESH_OT_unsubdivide(wmOperatorType *ot)
350 {
351         /* identifiers */
352         ot->name = "Un-Subdivide";
353         ot->description = "UnSubdivide selected edges & faces";
354         ot->idname = "MESH_OT_unsubdivide";
355
356         /* api callbacks */
357         ot->exec = edbm_unsubdivide_exec;
358         ot->poll = ED_operator_editmesh;
359
360         /* flags */
361         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
362
363         /* props */
364         RNA_def_int(ot->srna, "iterations", 2, 1, 1000, "Iterations", "Number of times to unsubdivide", 1, 100);
365 }
366
367 void EDBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em)
368 {
369         Main *bmain = CTX_data_main(C);
370         Object *obedit = em->ob;
371         BMIter iter;
372         BMVert *eve;
373
374         ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
375
376         struct SnapObjectContext *snap_context = ED_transform_snap_object_context_create_view3d(
377                 bmain, CTX_data_scene(C), CTX_data_depsgraph(C), 0,
378                 ar, CTX_wm_view3d(C));
379
380         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
381                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
382                         float mval[2], co_proj[3];
383                         if (ED_view3d_project_float_object(ar, eve->co, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
384                                 if (ED_transform_snap_object_project_view3d(
385                                         snap_context,
386                                         SCE_SNAP_MODE_FACE,
387                                         &(const struct SnapObjectParams){
388                                             .snap_select = SNAP_NOT_ACTIVE,
389                                             .use_object_edit_cage = false,
390                                             .use_occlusion_test = true,
391                                         },
392                                         mval, NULL,
393                                         co_proj, NULL))
394                                 {
395                                         mul_v3_m4v3(eve->co, obedit->imat, co_proj);
396                                 }
397                         }
398                 }
399         }
400
401         ED_transform_snap_object_context_destroy(snap_context);
402 }
403
404 /** \} */
405
406 /* -------------------------------------------------------------------- */
407 /** \name Delete Operator
408  * \{ */
409
410 /* Note, these values must match delete_mesh() event values */
411 enum {
412         MESH_DELETE_VERT      = 0,
413         MESH_DELETE_EDGE      = 1,
414         MESH_DELETE_FACE      = 2,
415         MESH_DELETE_EDGE_FACE = 3,
416         MESH_DELETE_ONLY_FACE = 4,
417 };
418
419 static void edbm_report_delete_info(ReportList *reports, const int totelem_old[3], const int totelem_new[3])
420 {
421         BKE_reportf(reports, RPT_INFO,
422                     "Removed: %d vertices, %d edges, %d faces",
423                     totelem_old[0] - totelem_new[0], totelem_old[1] - totelem_new[1], totelem_old[2] - totelem_new[2]);
424 }
425
426 static int edbm_delete_exec(bContext *C, wmOperator *op)
427 {
428         ViewLayer *view_layer = CTX_data_view_layer(C);
429
430         uint objects_len = 0;
431         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
432         bool changed_multi = false;
433
434         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
435                 Object *obedit = objects[ob_index];
436                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
437                 const int type = RNA_enum_get(op->ptr, "type");
438
439                 switch (type) {
440                         case MESH_DELETE_VERT: /* Erase Vertices */
441                                 if (!(em->bm->totvertsel &&
442                                       EDBM_op_callf(em, op, "delete geom=%hv context=%i", BM_ELEM_SELECT, DEL_VERTS)))
443                                 {
444                                         continue;
445                                 }
446                                 break;
447                         case MESH_DELETE_EDGE: /* Erase Edges */
448                                 if (!(em->bm->totedgesel &&
449                                       EDBM_op_callf(em, op, "delete geom=%he context=%i", BM_ELEM_SELECT, DEL_EDGES)))
450                                 {
451                                         continue;
452                                 }
453                                 break;
454                         case MESH_DELETE_FACE: /* Erase Faces */
455                                 if (!(em->bm->totfacesel &&
456                                       EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_FACES)))
457                                 {
458                                         continue;
459                                 }
460                                 break;
461                         case MESH_DELETE_EDGE_FACE:
462                                 /* Edges and Faces */
463                                 if (!((em->bm->totedgesel || em->bm->totfacesel) &&
464                                       EDBM_op_callf(em, op, "delete geom=%hef context=%i", BM_ELEM_SELECT, DEL_EDGESFACES)))
465                                 {
466                                         continue;
467                                 }
468                                 break;
469                         case MESH_DELETE_ONLY_FACE:
470                                 /* Only faces. */
471                                 if (!(em->bm->totfacesel &&
472                                       EDBM_op_callf(em, op, "delete geom=%hf context=%i", BM_ELEM_SELECT, DEL_ONLYFACES)))
473                                 {
474                                         continue;
475                                 }
476                                 break;
477                         default:
478                                 BLI_assert(0);
479                                 break;
480                 }
481
482                 changed_multi = true;
483
484                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
485
486                 EDBM_update_generic(em, true, true);
487         }
488
489         MEM_freeN(objects);
490
491         return changed_multi ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
492 }
493
494 void MESH_OT_delete(wmOperatorType *ot)
495 {
496         static const EnumPropertyItem prop_mesh_delete_types[] = {
497                 {MESH_DELETE_VERT,      "VERT",      0, "Vertices", ""},
498                 {MESH_DELETE_EDGE,      "EDGE",      0, "Edges", ""},
499                 {MESH_DELETE_FACE,      "FACE",      0, "Faces", ""},
500                 {MESH_DELETE_EDGE_FACE, "EDGE_FACE", 0, "Only Edges & Faces", ""},
501                 {MESH_DELETE_ONLY_FACE, "ONLY_FACE", 0, "Only Faces", ""},
502                 {0, NULL, 0, NULL, NULL}
503         };
504
505         /* identifiers */
506         ot->name = "Delete";
507         ot->description = "Delete selected vertices, edges or faces";
508         ot->idname = "MESH_OT_delete";
509
510         /* api callbacks */
511         ot->invoke = WM_menu_invoke;
512         ot->exec = edbm_delete_exec;
513
514         ot->poll = ED_operator_editmesh;
515
516         /* flags */
517         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
518
519         /* props */
520         ot->prop = RNA_def_enum(ot->srna, "type", prop_mesh_delete_types, MESH_DELETE_VERT,
521                                 "Type", "Method used for deleting mesh data");
522         RNA_def_property_flag(ot->prop, PROP_HIDDEN | PROP_SKIP_SAVE);
523 }
524
525 /** \} */
526
527 /* -------------------------------------------------------------------- */
528 /** \name Delete Loose Operator
529  * \{ */
530
531 static bool bm_face_is_loose(BMFace *f)
532 {
533         BMLoop *l_iter, *l_first;
534
535         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
536         do {
537                 if (!BM_edge_is_boundary(l_iter->e)) {
538                         return false;
539                 }
540         } while ((l_iter = l_iter->next) != l_first);
541
542         return true;
543 }
544
545 static int edbm_delete_loose_exec(bContext *C, wmOperator *op)
546 {
547         ViewLayer *view_layer = CTX_data_view_layer(C);
548         int totelem_old_sel[3];
549         int totelem_old[3];
550
551         uint objects_len = 0;
552         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
553
554         EDBM_mesh_stats_multi(objects, objects_len, totelem_old, totelem_old_sel);
555
556         const bool use_verts = (RNA_boolean_get(op->ptr, "use_verts") && totelem_old_sel[0]);
557         const bool use_edges = (RNA_boolean_get(op->ptr, "use_edges") && totelem_old_sel[1]);
558         const bool use_faces = (RNA_boolean_get(op->ptr, "use_faces") && totelem_old_sel[2]);
559
560         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
561                 Object *obedit = objects[ob_index];
562
563                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
564                 BMesh *bm = em->bm;
565                 BMIter iter;
566
567                 BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
568
569                 if (use_faces) {
570                         BMFace *f;
571
572                         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
573                                 if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
574                                         BM_elem_flag_set(f, BM_ELEM_TAG, bm_face_is_loose(f));
575                                 }
576                         }
577
578                         BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_FACES);
579                 }
580
581                 if (use_edges) {
582                         BMEdge *e;
583
584                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
585                                 if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
586                                         BM_elem_flag_set(e, BM_ELEM_TAG, BM_edge_is_wire(e));
587                                 }
588                         }
589
590                         BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_EDGES);
591                 }
592
593                 if (use_verts) {
594                         BMVert *v;
595
596                         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
597                                 if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
598                                         BM_elem_flag_set(v, BM_ELEM_TAG, (v->e == NULL));
599                                 }
600                         }
601
602                         BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_VERTS);
603                 }
604
605                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
606
607                 EDBM_update_generic(em, true, true);
608         }
609
610         int totelem_new[3];
611         EDBM_mesh_stats_multi(objects, objects_len, totelem_new, NULL);
612
613         edbm_report_delete_info(op->reports, totelem_old, totelem_new);
614
615         MEM_freeN(objects);
616
617         return OPERATOR_FINISHED;
618 }
619
620
621 void MESH_OT_delete_loose(wmOperatorType *ot)
622 {
623         /* identifiers */
624         ot->name = "Delete Loose";
625         ot->description = "Delete loose vertices, edges or faces";
626         ot->idname = "MESH_OT_delete_loose";
627
628         /* api callbacks */
629         ot->exec = edbm_delete_loose_exec;
630
631         ot->poll = ED_operator_editmesh;
632
633         /* flags */
634         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
635
636         /* props */
637         RNA_def_boolean(ot->srna, "use_verts", true, "Vertices", "Remove loose vertices");
638         RNA_def_boolean(ot->srna, "use_edges", true, "Edges", "Remove loose edges");
639         RNA_def_boolean(ot->srna, "use_faces", false, "Faces", "Remove loose faces");
640 }
641
642 /** \} */
643
644 /* -------------------------------------------------------------------- */
645 /** \name Collapse Edge Operator
646  * \{ */
647
648 static int edbm_collapse_edge_exec(bContext *C, wmOperator *op)
649 {
650         ViewLayer *view_layer = CTX_data_view_layer(C);
651         uint objects_len = 0;
652         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
653         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
654                 Object *obedit = objects[ob_index];
655                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
656
657                 if (em->bm->totedgesel == 0) {
658                         continue;
659                 }
660
661                 if (!EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, true)) {
662                         continue;
663                 }
664
665                 EDBM_update_generic(em, true, true);
666         }
667         MEM_freeN(objects);
668
669         return OPERATOR_FINISHED;
670 }
671
672 void MESH_OT_edge_collapse(wmOperatorType *ot)
673 {
674         /* identifiers */
675         ot->name = "Edge Collapse";
676         ot->description = "Collapse selected edges";
677         ot->idname = "MESH_OT_edge_collapse";
678
679         /* api callbacks */
680         ot->exec = edbm_collapse_edge_exec;
681         ot->poll = ED_operator_editmesh;
682
683         /* flags */
684         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
685 }
686
687 /** \} */
688
689 /* -------------------------------------------------------------------- */
690 /** \name Create Edge/Face Operator
691  * \{ */
692
693 static bool edbm_add_edge_face__smooth_get(BMesh *bm)
694 {
695         BMEdge *e;
696         BMIter iter;
697
698         unsigned int vote_on_smooth[2] = {0, 0};
699
700         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
701                 if (BM_elem_flag_test(e, BM_ELEM_SELECT) && e->l) {
702                         vote_on_smooth[BM_elem_flag_test_bool(e->l->f, BM_ELEM_SMOOTH)]++;
703                 }
704         }
705
706         return (vote_on_smooth[0] < vote_on_smooth[1]);
707 }
708
709 #ifdef USE_FACE_CREATE_SEL_EXTEND
710 /**
711  * Function used to get a fixed number of edges linked to a vertex that passes a test function.
712  * This is used so we can request all boundary edges connected to a vertex for eg.
713  */
714 static int edbm_add_edge_face_exec__vert_edge_lookup(
715         BMVert *v, BMEdge *e_used, BMEdge **e_arr, const int e_arr_len,
716         bool (* func)(const BMEdge *))
717 {
718         BMIter iter;
719         BMEdge *e_iter;
720         int i = 0;
721         BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
722                 if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == false) {
723                         if ((e_used == NULL) || (e_used != e_iter)) {
724                                 if (func(e_iter)) {
725                                         e_arr[i++] = e_iter;
726                                         if (i >= e_arr_len) {
727                                                 break;
728                                         }
729                                 }
730                         }
731                 }
732         }
733         return i;
734 }
735
736 static BMElem *edbm_add_edge_face_exec__tricky_extend_sel(BMesh *bm)
737 {
738         BMIter iter;
739         bool found = false;
740
741         if (bm->totvertsel == 1 && bm->totedgesel == 0 && bm->totfacesel == 0) {
742                 /* first look for 2 boundary edges */
743                 BMVert *v;
744
745                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
746                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
747                                 found = true;
748                                 break;
749                         }
750                 }
751
752                 if (found) {
753                         BMEdge *ed_pair[3];
754                         if (
755                             ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_wire) == 2) &&
756                              (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false)) ||
757
758                             ((edbm_add_edge_face_exec__vert_edge_lookup(v, NULL, ed_pair, 3, BM_edge_is_boundary) == 2) &&
759                              (BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false))
760                             )
761                         {
762                                 BMEdge *e_other = BM_edge_exists(
763                                         BM_edge_other_vert(ed_pair[0], v),
764                                         BM_edge_other_vert(ed_pair[1], v));
765                                 BM_edge_select_set(bm, ed_pair[0], true);
766                                 BM_edge_select_set(bm, ed_pair[1], true);
767                                 if (e_other) {
768                                         BM_edge_select_set(bm, e_other, true);
769                                 }
770                                 return (BMElem *)v;
771                         }
772                 }
773         }
774         else if (bm->totvertsel == 2 && bm->totedgesel == 1 && bm->totfacesel == 0) {
775                 /* first look for 2 boundary edges */
776                 BMEdge *e;
777
778                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
779                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
780                                 found = true;
781                                 break;
782                         }
783                 }
784                 if (found) {
785                         BMEdge *ed_pair_v1[2];
786                         BMEdge *ed_pair_v2[2];
787                         if (
788                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire) == 1) &&
789                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire) == 1) &&
790                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
791                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
792
793 #if 1  /* better support mixed cases [#37203] */
794                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_wire)     == 1) &&
795                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
796                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
797                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
798
799                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
800                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_wire)     == 1) &&
801                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
802                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false)) ||
803 #endif
804
805                             ((edbm_add_edge_face_exec__vert_edge_lookup(e->v1, e, ed_pair_v1, 2, BM_edge_is_boundary) == 1) &&
806                              (edbm_add_edge_face_exec__vert_edge_lookup(e->v2, e, ed_pair_v2, 2, BM_edge_is_boundary) == 1) &&
807                              (BM_edge_share_face_check(e, ed_pair_v1[0]) == false) &&
808                              (BM_edge_share_face_check(e, ed_pair_v2[0]) == false))
809                             )
810                         {
811                                 BMVert *v1_other = BM_edge_other_vert(ed_pair_v1[0], e->v1);
812                                 BMVert *v2_other = BM_edge_other_vert(ed_pair_v2[0], e->v2);
813                                 BMEdge *e_other = (v1_other != v2_other) ? BM_edge_exists(v1_other, v2_other) : NULL;
814                                 BM_edge_select_set(bm, ed_pair_v1[0], true);
815                                 BM_edge_select_set(bm, ed_pair_v2[0], true);
816                                 if (e_other) {
817                                         BM_edge_select_set(bm, e_other, true);
818                                 }
819                                 return (BMElem *)e;
820                         }
821                 }
822         }
823
824         return NULL;
825 }
826 static void edbm_add_edge_face_exec__tricky_finalize_sel(BMesh *bm, BMElem *ele_desel, BMFace *f)
827 {
828         /* now we need to find the edge that isnt connected to this element */
829         BM_select_history_clear(bm);
830
831         /* Notes on hidden geometry:
832          * - un-hide the face since its possible hidden was copied when copying surrounding face attributes.
833          * - un-hide before adding to select history
834          *   since we may extend into an existing, hidden vert/edge.
835          */
836
837         BM_elem_flag_disable(f, BM_ELEM_HIDDEN);
838         BM_face_select_set(bm, f, false);
839
840         if (ele_desel->head.htype == BM_VERT) {
841                 BMLoop *l = BM_face_vert_share_loop(f, (BMVert *)ele_desel);
842                 BLI_assert(f->len == 3);
843                 BM_vert_select_set(bm, (BMVert *)ele_desel, false);
844                 BM_edge_select_set(bm, l->next->e, true);
845                 BM_select_history_store(bm, l->next->e);
846         }
847         else {
848                 BMLoop *l = BM_face_edge_share_loop(f, (BMEdge *)ele_desel);
849                 BLI_assert(f->len == 4 || f->len == 3);
850
851                 BM_edge_select_set(bm, (BMEdge *)ele_desel, false);
852                 if (f->len == 4) {
853                         BMEdge *e_active = l->next->next->e;
854                         BM_elem_flag_disable(e_active, BM_ELEM_HIDDEN);
855                         BM_edge_select_set(bm, e_active, true);
856                         BM_select_history_store(bm, e_active);
857                 }
858                 else {
859                         BMVert *v_active = l->next->next->v;
860                         BM_elem_flag_disable(v_active, BM_ELEM_HIDDEN);
861                         BM_vert_select_set(bm, v_active, true);
862                         BM_select_history_store(bm, v_active);
863                 }
864         }
865 }
866 #endif  /* USE_FACE_CREATE_SEL_EXTEND */
867
868 static int edbm_add_edge_face_exec(bContext *C, wmOperator *op)
869 {
870         /* when this is used to dissolve we could avoid this, but checking isnt too slow */
871
872         ViewLayer *view_layer = CTX_data_view_layer(C);
873         uint objects_len = 0;
874         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
875         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
876                 Object *obedit = objects[ob_index];
877                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
878
879                 if ((em->bm->totvertsel == 0) &&
880                     (em->bm->totedgesel == 0) &&
881                     (em->bm->totvertsel == 0))
882                 {
883                         continue;
884                 }
885
886                 bool use_smooth = edbm_add_edge_face__smooth_get(em->bm);
887                 int totedge_orig = em->bm->totedge;
888                 int totface_orig = em->bm->totface;
889
890                 BMOperator bmop;
891 #ifdef USE_FACE_CREATE_SEL_EXTEND
892                 BMElem *ele_desel;
893                 BMFace *ele_desel_face;
894
895                 /* be extra clever, figure out if a partial selection should be extended so we can create geometry
896                  * with single vert or single edge selection */
897                 ele_desel = edbm_add_edge_face_exec__tricky_extend_sel(em->bm);
898 #endif
899                 if (!EDBM_op_init(
900                             em, &bmop, op,
901                             "contextual_create geom=%hfev mat_nr=%i use_smooth=%b",
902                             BM_ELEM_SELECT, em->mat_nr, use_smooth))
903                 {
904                         continue;
905                 }
906
907                 BMO_op_exec(em->bm, &bmop);
908
909                 /* cancel if nothing was done */
910                 if ((totedge_orig == em->bm->totedge) &&
911                     (totface_orig == em->bm->totface))
912                 {
913                         EDBM_op_finish(em, &bmop, op, true);
914                         continue;
915                 }
916 #ifdef USE_FACE_CREATE_SEL_EXTEND
917                 /* normally we would want to leave the new geometry selected,
918                  * but being able to press F many times to add geometry is too useful! */
919                 if (ele_desel &&
920                     (BMO_slot_buffer_count(bmop.slots_out, "faces.out") == 1) &&
921                     (ele_desel_face = BMO_slot_buffer_get_first(bmop.slots_out, "faces.out")))
922                 {
923                         edbm_add_edge_face_exec__tricky_finalize_sel(em->bm, ele_desel, ele_desel_face);
924                 }
925                 else
926 #endif
927                 {
928                         /* Newly created faces may include existing hidden edges,
929                          * copying face data from surrounding, may have copied hidden face flag too.
930                          *
931                          * Important that faces use flushing since 'edges.out' wont include hidden edges that already existed.
932                          */
933                         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_HIDDEN, true);
934                         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, false);
935
936                         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
937                         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
938                 }
939
940                 if (!EDBM_op_finish(em, &bmop, op, true)) {
941                         continue;
942                 }
943
944                 EDBM_update_generic(em, true, true);
945         }
946         MEM_freeN(objects);
947
948         return OPERATOR_FINISHED;
949 }
950
951 void MESH_OT_edge_face_add(wmOperatorType *ot)
952 {
953         /* identifiers */
954         ot->name = "Make Edge/Face";
955         ot->description = "Add an edge or face to selected";
956         ot->idname = "MESH_OT_edge_face_add";
957
958         /* api callbacks */
959         ot->exec = edbm_add_edge_face_exec;
960         ot->poll = ED_operator_editmesh;
961
962         /* flags */
963         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
964 }
965
966 /** \} */
967
968 /* -------------------------------------------------------------------- */
969 /** \name Mark Edge (Seam) Operator
970  * \{ */
971
972 static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
973 {
974         Scene *scene = CTX_data_scene(C);
975         ViewLayer *view_layer = CTX_data_view_layer(C);
976         BMEdge *eed;
977         BMIter iter;
978         const bool clear = RNA_boolean_get(op->ptr, "clear");
979
980         uint objects_len = 0;
981         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
982         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
983                 Object *obedit = objects[ob_index];
984                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
985                 BMesh *bm = em->bm;
986
987                 if (bm->totedgesel == 0) {
988                         continue;
989                 }
990
991                 if (clear) {
992                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
993                                 if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
994                                         continue;
995                                 }
996
997                                 BM_elem_flag_disable(eed, BM_ELEM_SEAM);
998                         }
999                 }
1000                 else {
1001                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
1002                                 if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
1003                                         continue;
1004                                 }
1005                                 BM_elem_flag_enable(eed, BM_ELEM_SEAM);
1006                         }
1007                 }
1008
1009                 ED_uvedit_live_unwrap(scene, obedit);
1010                 EDBM_update_generic(em, true, false);
1011         }
1012         MEM_freeN(objects);
1013
1014         return OPERATOR_FINISHED;
1015 }
1016
1017 void MESH_OT_mark_seam(wmOperatorType *ot)
1018 {
1019         PropertyRNA *prop;
1020
1021         /* identifiers */
1022         ot->name = "Mark Seam";
1023         ot->idname = "MESH_OT_mark_seam";
1024         ot->description = "(Un)mark selected edges as a seam";
1025
1026         /* api callbacks */
1027         ot->exec = edbm_mark_seam_exec;
1028         ot->poll = ED_operator_editmesh;
1029
1030         /* flags */
1031         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1032
1033         prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", "");
1034         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1035
1036         WM_operatortype_props_advanced_begin(ot);
1037 }
1038
1039 /** \} */
1040
1041 /* -------------------------------------------------------------------- */
1042 /** \name Mark Edge (Sharp) Operator
1043  * \{ */
1044
1045 static int edbm_mark_sharp_exec(bContext *C, wmOperator *op)
1046 {
1047         BMEdge *eed;
1048         BMIter iter;
1049         const bool clear = RNA_boolean_get(op->ptr, "clear");
1050         const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
1051         ViewLayer *view_layer = CTX_data_view_layer(C);
1052
1053         uint objects_len = 0;
1054         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1055         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1056                 Object *obedit = objects[ob_index];
1057                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1058                 BMesh *bm = em->bm;
1059
1060                 if (bm->totedgesel == 0) {
1061                         continue;
1062                 }
1063
1064                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
1065                         if (use_verts) {
1066                                 if (!(BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) || BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))) {
1067                                         continue;
1068                                 }
1069                         }
1070                         else if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1071                                 continue;
1072                         }
1073
1074                         BM_elem_flag_set(eed, BM_ELEM_SMOOTH, clear);
1075                 }
1076
1077                 EDBM_update_generic(em, true, false);
1078         }
1079         MEM_freeN(objects);
1080
1081         return OPERATOR_FINISHED;
1082 }
1083
1084 void MESH_OT_mark_sharp(wmOperatorType *ot)
1085 {
1086         PropertyRNA *prop;
1087
1088         /* identifiers */
1089         ot->name = "Mark Sharp";
1090         ot->idname = "MESH_OT_mark_sharp";
1091         ot->description = "(Un)mark selected edges as sharp";
1092
1093         /* api callbacks */
1094         ot->exec = edbm_mark_sharp_exec;
1095         ot->poll = ED_operator_editmesh;
1096
1097         /* flags */
1098         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1099
1100         prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
1101         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1102         prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices",
1103                                "Consider vertices instead of edges to select which edges to (un)tag as sharp");
1104         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1105 }
1106
1107 static bool edbm_connect_vert_pair(BMEditMesh *em, wmOperator *op)
1108 {
1109         BMesh *bm = em->bm;
1110         BMOperator bmop;
1111         const int verts_len = bm->totvertsel;
1112         bool is_pair = (verts_len == 2);
1113         int len = 0;
1114         bool check_degenerate = true;
1115
1116         BMVert **verts;
1117         bool checks_succeded = true;
1118
1119         /* sanity check */
1120         if (verts_len < 2) {
1121                 return false;
1122         }
1123
1124         verts = MEM_mallocN(sizeof(*verts) * verts_len, __func__);
1125         {
1126                 BMIter iter;
1127                 BMVert *v;
1128                 int i = 0;
1129
1130                 BM_ITER_MESH(v, &iter, bm, BM_VERTS_OF_MESH) {
1131                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1132                                 verts[i++] = v;
1133                         }
1134                 }
1135
1136                 if (BM_vert_pair_share_face_check_cb(
1137                             verts[0], verts[1],
1138                             BM_elem_cb_check_hflag_disabled_simple(BMFace *, BM_ELEM_HIDDEN)))
1139                 {
1140                         check_degenerate = false;
1141                         is_pair = false;
1142                 }
1143         }
1144
1145         if (is_pair) {
1146                 if (!EDBM_op_init(
1147                             em, &bmop, op,
1148                             "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf",
1149                             verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN))
1150                 {
1151                         checks_succeded = false;
1152                 }
1153         }
1154         else {
1155                 if (!EDBM_op_init(
1156                             em, &bmop, op,
1157                             "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b",
1158                             verts, verts_len, BM_ELEM_HIDDEN, check_degenerate))
1159                 {
1160                         checks_succeded = false;
1161                 }
1162         }
1163         if (checks_succeded) {
1164                 BMO_op_exec(bm, &bmop);
1165                 len = BMO_slot_get(bmop.slots_out, "edges.out")->len;
1166
1167                 if (len && is_pair) {
1168                         /* new verts have been added, we have to select the edges, not just flush */
1169                         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1170                 }
1171
1172                 if (!EDBM_op_finish(em, &bmop, op, true)) {
1173                         len = 0;
1174                 }
1175                 else {
1176                         EDBM_selectmode_flush(em);  /* so newly created edges get the selection state from the vertex */
1177
1178                         EDBM_update_generic(em, true, true);
1179                 }
1180         }
1181         MEM_freeN(verts);
1182
1183         return len;
1184 }
1185
1186 static int edbm_vert_connect_exec(bContext *C, wmOperator *op)
1187 {
1188         ViewLayer *view_layer = CTX_data_view_layer(C);
1189         uint objects_len = 0;
1190         uint failed_objects_len = 0;
1191         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1192
1193         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1194                 Object *obedit = objects[ob_index];
1195                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1196
1197                 if (!edbm_connect_vert_pair(em, op)) {
1198                         failed_objects_len++;
1199                 }
1200         }
1201         MEM_freeN(objects);
1202         return failed_objects_len == objects_len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1203 }
1204
1205 void MESH_OT_vert_connect(wmOperatorType *ot)
1206 {
1207         /* identifiers */
1208         ot->name = "Vertex Connect";
1209         ot->idname = "MESH_OT_vert_connect";
1210         ot->description = "Connect selected vertices of faces, splitting the face";
1211
1212         /* api callbacks */
1213         ot->exec = edbm_vert_connect_exec;
1214         ot->poll = ED_operator_editmesh;
1215
1216         /* flags */
1217         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1218 }
1219
1220 /** \} */
1221
1222 /* -------------------------------------------------------------------- */
1223 /** \name Split Concave Faces Operator
1224  * \{ */
1225
1226 /**
1227  * check that endpoints are verts and only have a single selected edge connected.
1228  */
1229 static bool bm_vert_is_select_history_open(BMesh *bm)
1230 {
1231         BMEditSelection *ele_a = bm->selected.first;
1232         BMEditSelection *ele_b = bm->selected.last;
1233         if ((ele_a->htype == BM_VERT) &&
1234             (ele_b->htype == BM_VERT))
1235         {
1236                 if ((BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_a->ele, BM_ELEM_SELECT, true) == 1) &&
1237                     (BM_iter_elem_count_flag(BM_EDGES_OF_VERT, (BMVert *)ele_b->ele, BM_ELEM_SELECT, true) == 1))
1238                 {
1239                         return true;
1240                 }
1241         }
1242
1243         return false;
1244 }
1245
1246 static bool bm_vert_connect_pair(BMesh *bm, BMVert *v_a, BMVert *v_b)
1247 {
1248         BMOperator bmop;
1249         BMVert **verts;
1250         const int totedge_orig = bm->totedge;
1251
1252         BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, "connect_vert_pair");
1253
1254         verts = BMO_slot_buffer_alloc(&bmop, bmop.slots_in, "verts", 2);
1255         verts[0] = v_a;
1256         verts[1] = v_b;
1257
1258         BM_vert_normal_update(verts[0]);
1259         BM_vert_normal_update(verts[1]);
1260
1261         BMO_op_exec(bm, &bmop);
1262         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1263         BMO_op_finish(bm, &bmop);
1264         return (bm->totedge != totedge_orig);
1265 }
1266
1267 static bool bm_vert_connect_select_history(BMesh *bm)
1268 {
1269         /* Logic is as follows:
1270          *
1271          * - If there are any isolated/wire verts - connect as edges.
1272          * - Otherwise connect faces.
1273          * - If all edges have been created already, closed the loop.
1274          */
1275         if (BLI_listbase_count_at_most(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) {
1276                 BMEditSelection *ese;
1277                 int tot = 0;
1278                 bool changed = false;
1279                 bool has_wire = false;
1280                 // bool all_verts;
1281
1282                 /* ensure all verts have history */
1283                 for (ese = bm->selected.first; ese; ese = ese->next, tot++) {
1284                         BMVert *v;
1285                         if (ese->htype != BM_VERT) {
1286                                 break;
1287                         }
1288                         v = (BMVert *)ese->ele;
1289                         if ((has_wire == false) && ((v->e == NULL) || BM_vert_is_wire(v))) {
1290                                 has_wire = true;
1291                         }
1292                 }
1293                 // all_verts = (ese == NULL);
1294
1295                 if (has_wire == false) {
1296                         /* all verts have faces , connect verts via faces! */
1297                         if (tot == bm->totvertsel) {
1298                                 BMEditSelection *ese_last;
1299                                 ese_last = bm->selected.first;
1300                                 ese = ese_last->next;
1301
1302                                 do {
1303
1304                                         if (BM_edge_exists((BMVert *)ese_last->ele, (BMVert *)ese->ele)) {
1305                                                 /* pass, edge exists (and will be selected) */
1306                                         }
1307                                         else {
1308                                                 changed |= bm_vert_connect_pair(bm, (BMVert *)ese_last->ele, (BMVert *)ese->ele);
1309                                         }
1310                                 } while ((void)
1311                                          (ese_last = ese),
1312                                          (ese = ese->next));
1313
1314                                 if (changed) {
1315                                         return true;
1316                                 }
1317                         }
1318
1319                         if (changed == false) {
1320                                 /* existing loops: close the selection */
1321                                 if (bm_vert_is_select_history_open(bm)) {
1322                                         changed |= bm_vert_connect_pair(
1323                                                 bm,
1324                                                 (BMVert *)((BMEditSelection *)bm->selected.first)->ele,
1325                                                 (BMVert *)((BMEditSelection *)bm->selected.last)->ele);
1326
1327                                         if (changed) {
1328                                                 return true;
1329                                         }
1330                                 }
1331                         }
1332                 }
1333
1334                 else {
1335                         /* no faces, simply connect the verts by edges */
1336                         BMEditSelection *ese_prev;
1337                         ese_prev = bm->selected.first;
1338                         ese = ese_prev->next;
1339
1340
1341                         do {
1342                                 if (BM_edge_exists((BMVert *)ese_prev->ele, (BMVert *)ese->ele)) {
1343                                         /* pass, edge exists (and will be selected) */
1344                                 }
1345                                 else {
1346                                         BMEdge *e;
1347                                         e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
1348                                         BM_edge_select_set(bm, e, true);
1349                                         changed = true;
1350                                 }
1351                         } while ((void)
1352                                  (ese_prev = ese),
1353                                  (ese = ese->next));
1354
1355                         if (changed == false) {
1356                                 /* existing loops: close the selection */
1357                                 if (bm_vert_is_select_history_open(bm)) {
1358                                         BMEdge *e;
1359                                         ese_prev = bm->selected.first;
1360                                         ese = bm->selected.last;
1361                                         e = BM_edge_create(bm, (BMVert *)ese_prev->ele, (BMVert *)ese->ele, NULL, 0);
1362                                         BM_edge_select_set(bm, e, true);
1363                                 }
1364                         }
1365
1366                         return true;
1367                 }
1368         }
1369
1370         return false;
1371 }
1372
1373 /**
1374  * Convert an edge selection to a temp vertex selection
1375  * (which must be cleared after use as a path to connect).
1376  */
1377 static bool bm_vert_connect_select_history_edge_to_vert_path(BMesh *bm, ListBase *r_selected)
1378 {
1379         ListBase selected_orig = {NULL, NULL};
1380         BMEditSelection *ese;
1381         int edges_len = 0;
1382         bool side = false;
1383
1384         /* first check all edges are OK */
1385         for (ese = bm->selected.first; ese; ese = ese->next) {
1386                 if (ese->htype == BM_EDGE) {
1387                         edges_len += 1;
1388                 }
1389                 else {
1390                         return false;
1391                 }
1392         }
1393         /* if this is a mixed selection, bail out! */
1394         if (bm->totedgesel != edges_len) {
1395                 return false;
1396         }
1397
1398         SWAP(ListBase, bm->selected, selected_orig);
1399
1400         /* convert edge selection into 2 ordered loops (where the first edge ends up in the middle) */
1401         for (ese = selected_orig.first; ese; ese = ese->next) {
1402                 BMEdge *e_curr = (BMEdge *)ese->ele;
1403                 BMEdge *e_prev = ese->prev ? (BMEdge *)ese->prev->ele : NULL;
1404                 BMLoop *l_curr;
1405                 BMLoop *l_prev;
1406                 BMVert *v;
1407
1408                 if (e_prev) {
1409                         BMFace *f = BM_edge_pair_share_face_by_len(e_curr, e_prev, &l_curr, &l_prev, true);
1410                         if (f) {
1411                                 if ((e_curr->v1 != l_curr->v) == (e_prev->v1 != l_prev->v)) {
1412                                         side = !side;
1413                                 }
1414                         }
1415                         else if (is_quad_flip_v3(e_curr->v1->co, e_curr->v2->co, e_prev->v2->co, e_prev->v1->co)) {
1416                                 side = !side;
1417                         }
1418                 }
1419
1420                 v = (&e_curr->v1)[side];
1421                 if (!bm->selected.last || (BMVert *)((BMEditSelection *)bm->selected.last)->ele != v) {
1422                         BM_select_history_store_notest(bm, v);
1423                 }
1424
1425                 v = (&e_curr->v1)[!side];
1426                 if (!bm->selected.first || (BMVert *)((BMEditSelection *)bm->selected.first)->ele != v) {
1427                         BM_select_history_store_head_notest(bm, v);
1428                 }
1429
1430                 e_prev = e_curr;
1431         }
1432
1433         *r_selected = bm->selected;
1434         bm->selected = selected_orig;
1435
1436         return true;
1437 }
1438
1439 static int edbm_vert_connect_path_exec(bContext *C, wmOperator *op)
1440 {
1441         ViewLayer *view_layer = CTX_data_view_layer(C);
1442         uint objects_len = 0;
1443         uint failed_selection_order_len = 0;
1444         uint failed_connect_len = 0;
1445         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1446
1447         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1448                 Object *obedit = objects[ob_index];
1449                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1450                 BMesh *bm = em->bm;
1451                 const bool is_pair = (em->bm->totvertsel == 2);
1452                 ListBase selected_orig = {NULL, NULL};
1453
1454                 if (bm->totvertsel == 0) {
1455                         continue;
1456                 }
1457
1458                 /* when there is only 2 vertices, we can ignore selection order */
1459                 if (is_pair) {
1460                         if (!edbm_connect_vert_pair(em, op)) {
1461                                 failed_connect_len++;
1462                         }
1463                         continue;
1464                 }
1465
1466                 if (bm->selected.first) {
1467                         BMEditSelection *ese = bm->selected.first;
1468                         if (ese->htype == BM_EDGE) {
1469                                 if (bm_vert_connect_select_history_edge_to_vert_path(bm, &selected_orig)) {
1470                                         SWAP(ListBase, bm->selected, selected_orig);
1471                                 }
1472                         }
1473                 }
1474
1475                 if (bm_vert_connect_select_history(bm)) {
1476                         EDBM_selectmode_flush(em);
1477                         EDBM_update_generic(em, true, true);
1478                 }
1479                 else {
1480                         failed_selection_order_len++;
1481                 }
1482
1483                 if (!BLI_listbase_is_empty(&selected_orig)) {
1484                         BM_select_history_clear(bm);
1485                         bm->selected = selected_orig;
1486                 }
1487         }
1488
1489         MEM_freeN(objects);
1490
1491         if (failed_selection_order_len == objects_len) {
1492                 BKE_report(op->reports, RPT_ERROR, "Invalid selection order");
1493                 return OPERATOR_CANCELLED;
1494         }
1495         else if (failed_connect_len == objects_len) {
1496                 BKE_report(op->reports, RPT_ERROR, "Could not connect vertices");
1497                 return OPERATOR_CANCELLED;
1498         }
1499
1500         return OPERATOR_FINISHED;
1501 }
1502
1503 void MESH_OT_vert_connect_path(wmOperatorType *ot)
1504 {
1505         /* identifiers */
1506         ot->name = "Vertex Connect Path";
1507         ot->idname = "MESH_OT_vert_connect_path";
1508         ot->description = "Connect vertices by their selection order, creating edges, splitting faces";
1509
1510         /* api callbacks */
1511         ot->exec = edbm_vert_connect_path_exec;
1512         ot->poll = ED_operator_editmesh;
1513
1514         /* flags */
1515         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1516 }
1517
1518 static int edbm_vert_connect_concave_exec(bContext *C, wmOperator *op)
1519 {
1520         ViewLayer *view_layer = CTX_data_view_layer(C);
1521         uint objects_len = 0;
1522         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1523         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1524                 Object *obedit = objects[ob_index];
1525                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1526
1527                 if (em->bm->totfacesel == 0) {
1528                         continue;
1529                 }
1530
1531                 if (!EDBM_op_call_and_selectf(
1532                              em, op,
1533                              "faces.out", true,
1534                              "connect_verts_concave faces=%hf",
1535                              BM_ELEM_SELECT))
1536                 {
1537                         continue;
1538                 }
1539                 EDBM_update_generic(em, true, true);
1540         }
1541
1542         MEM_freeN(objects);
1543         return OPERATOR_FINISHED;
1544 }
1545
1546 void MESH_OT_vert_connect_concave(wmOperatorType *ot)
1547 {
1548         /* identifiers */
1549         ot->name = "Split Concave Faces";
1550         ot->idname = "MESH_OT_vert_connect_concave";
1551         ot->description = "Make all faces convex";
1552
1553         /* api callbacks */
1554         ot->exec = edbm_vert_connect_concave_exec;
1555         ot->poll = ED_operator_editmesh;
1556
1557         /* flags */
1558         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1559 }
1560
1561 /** \} */
1562
1563 /* -------------------------------------------------------------------- */
1564 /** \name Split Non-Planar Faces Operator
1565  * \{ */
1566
1567 static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op)
1568 {
1569         ViewLayer *view_layer = CTX_data_view_layer(C);
1570         const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
1571         uint objects_len = 0;
1572         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1573
1574         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1575                 Object *obedit = objects[ob_index];
1576                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1577
1578                 if (em->bm->totfacesel == 0) {
1579                         continue;
1580                 }
1581
1582                 if (!EDBM_op_call_and_selectf(
1583                             em, op,
1584                             "faces.out", true,
1585                             "connect_verts_nonplanar faces=%hf angle_limit=%f",
1586                             BM_ELEM_SELECT, angle_limit))
1587                 {
1588                         continue;
1589                 }
1590
1591                 EDBM_update_generic(em, true, true);
1592         }
1593         MEM_freeN(objects);
1594
1595         return OPERATOR_FINISHED;
1596 }
1597
1598 void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot)
1599 {
1600         PropertyRNA *prop;
1601
1602         /* identifiers */
1603         ot->name = "Split Non-Planar Faces";
1604         ot->idname = "MESH_OT_vert_connect_nonplanar";
1605         ot->description = "Split non-planar faces that exceed the angle threshold";
1606
1607         /* api callbacks */
1608         ot->exec = edbm_vert_connect_nonplaner_exec;
1609         ot->poll = ED_operator_editmesh;
1610
1611         /* flags */
1612         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1613
1614         /* props */
1615         prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
1616                                       "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
1617         RNA_def_property_float_default(prop, DEG2RADF(5.0f));
1618 }
1619
1620 /** \} */
1621
1622 /* -------------------------------------------------------------------- */
1623 /** \name Make Planar Faces Operator
1624  * \{ */
1625
1626 static int edbm_face_make_planar_exec(bContext *C, wmOperator *op)
1627 {
1628         ViewLayer *view_layer = CTX_data_view_layer(C);
1629         uint objects_len = 0;
1630         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1631
1632         const int repeat = RNA_int_get(op->ptr, "repeat");
1633         const float fac = RNA_float_get(op->ptr, "factor");
1634
1635         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1636                 Object *obedit = objects[ob_index];
1637                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1638                 if (em->bm->totfacesel == 0) {
1639                         continue;
1640                 }
1641
1642                 if (!EDBM_op_callf(
1643                             em, op, "planar_faces faces=%hf iterations=%i factor=%f",
1644                             BM_ELEM_SELECT, repeat, fac))
1645                 {
1646                         continue;
1647                 }
1648
1649                 EDBM_update_generic(em, true, true);
1650         }
1651         MEM_freeN(objects);
1652
1653         return OPERATOR_FINISHED;
1654 }
1655
1656 void MESH_OT_face_make_planar(wmOperatorType *ot)
1657 {
1658         /* identifiers */
1659         ot->name = "Make Planar Faces";
1660         ot->idname = "MESH_OT_face_make_planar";
1661         ot->description = "Flatten selected faces";
1662
1663         /* api callbacks */
1664         ot->exec = edbm_face_make_planar_exec;
1665         ot->poll = ED_operator_editmesh;
1666
1667         /* flags */
1668         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1669
1670         /* props */
1671         RNA_def_float(ot->srna, "factor", 1.0f, -10.0f, 10.0f, "Factor", "", 0.0f, 1.0f);
1672         RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
1673 }
1674
1675 /** \} */
1676
1677 /* -------------------------------------------------------------------- */
1678 /** \name Split Edge Operator
1679  * \{ */
1680
1681 static int edbm_edge_split_exec(bContext *C, wmOperator *op)
1682 {
1683         ViewLayer *view_layer = CTX_data_view_layer(C);
1684         uint objects_len = 0;
1685         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1686         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1687                 Object *obedit = objects[ob_index];
1688                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1689                 if (em->bm->totedgesel == 0) {
1690                         continue;
1691                 }
1692
1693                 if (!EDBM_op_call_and_selectf(
1694                             em, op,
1695                             "edges.out", false,
1696                             "split_edges edges=%he",
1697                             BM_ELEM_SELECT))
1698                 {
1699                         continue;
1700                 }
1701
1702                 if (em->selectmode == SCE_SELECT_FACE) {
1703                         EDBM_select_flush(em);
1704                 }
1705
1706                 EDBM_update_generic(em, true, true);
1707         }
1708         MEM_freeN(objects);
1709
1710         return OPERATOR_FINISHED;
1711 }
1712
1713 void MESH_OT_edge_split(wmOperatorType *ot)
1714 {
1715         /* identifiers */
1716         ot->name = "Edge Split";
1717         ot->idname = "MESH_OT_edge_split";
1718         ot->description = "Split selected edges so that each neighbor face gets its own copy";
1719
1720         /* api callbacks */
1721         ot->exec = edbm_edge_split_exec;
1722         ot->poll = ED_operator_editmesh;
1723
1724         /* flags */
1725         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1726 }
1727
1728 /** \} */
1729
1730 /* -------------------------------------------------------------------- */
1731 /** \name Duplicate Operator
1732  * \{ */
1733
1734 static int edbm_duplicate_exec(bContext *C, wmOperator *op)
1735 {
1736         ViewLayer *view_layer = CTX_data_view_layer(C);
1737         uint objects_len = 0;
1738         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1739
1740         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1741                 Object *obedit = objects[ob_index];
1742                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1743                 if (em->bm->totvertsel == 0) {
1744                         continue;
1745                 }
1746
1747                 BMOperator bmop;
1748                 BMesh *bm = em->bm;
1749
1750                 EDBM_op_init(
1751                         em, &bmop, op,
1752                         "duplicate geom=%hvef use_select_history=%b",
1753                         BM_ELEM_SELECT, true);
1754
1755                 BMO_op_exec(bm, &bmop);
1756
1757                 /* de-select all would clear otherwise */
1758                 BM_SELECT_HISTORY_BACKUP(bm);
1759
1760                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1761
1762                 BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);
1763
1764                 /* rebuild editselection */
1765                 BM_SELECT_HISTORY_RESTORE(bm);
1766
1767                 if (!EDBM_op_finish(em, &bmop, op, true)) {
1768                         continue;
1769                 }
1770                 EDBM_update_generic(em, true, true);
1771         }
1772         MEM_freeN(objects);
1773
1774         return OPERATOR_FINISHED;
1775 }
1776
1777 static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1778 {
1779         WM_cursor_wait(1);
1780         edbm_duplicate_exec(C, op);
1781         WM_cursor_wait(0);
1782
1783         return OPERATOR_FINISHED;
1784 }
1785
1786 void MESH_OT_duplicate(wmOperatorType *ot)
1787 {
1788         /* identifiers */
1789         ot->name = "Duplicate";
1790         ot->description = "Duplicate selected vertices, edges or faces";
1791         ot->idname = "MESH_OT_duplicate";
1792
1793         /* api callbacks */
1794         ot->invoke = edbm_duplicate_invoke;
1795         ot->exec = edbm_duplicate_exec;
1796
1797         ot->poll = ED_operator_editmesh;
1798
1799         /* to give to transform */
1800         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1801 }
1802
1803 /** \} */
1804
1805 /* -------------------------------------------------------------------- */
1806 /** \name Flip Normals Operator
1807  * \{ */
1808 static int edbm_flip_normals_exec(bContext *C, wmOperator *op)
1809 {
1810         ViewLayer *view_layer = CTX_data_view_layer(C);
1811         uint objects_len = 0;
1812         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1813
1814         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1815                 Object *obedit = objects[ob_index];
1816                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1817
1818                 if (em->bm->totfacesel == 0) {
1819                         continue;
1820                 }
1821
1822                 if (!EDBM_op_callf(
1823                         em, op, "reverse_faces faces=%hf flip_multires=%b",
1824                         BM_ELEM_SELECT, true))
1825                 {
1826                         continue;
1827                 }
1828
1829                 EDBM_update_generic(em, true, false);
1830         }
1831
1832         MEM_freeN(objects);
1833         return OPERATOR_FINISHED;
1834 }
1835
1836 void MESH_OT_flip_normals(wmOperatorType *ot)
1837 {
1838         /* identifiers */
1839         ot->name = "Flip Normals";
1840         ot->description = "Flip the direction of selected faces' normals (and of their vertices)";
1841         ot->idname = "MESH_OT_flip_normals";
1842
1843         /* api callbacks */
1844         ot->exec = edbm_flip_normals_exec;
1845         ot->poll = ED_operator_editmesh;
1846
1847         /* flags */
1848         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1849 }
1850
1851 /** \} */
1852
1853 /* -------------------------------------------------------------------- */
1854 /** \name Rotate Edge Operator
1855  * \{ */
1856
1857 /**
1858  * Rotate the edges between selected faces, otherwise rotate the selected edges.
1859  */
1860 static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
1861 {
1862         BMEdge *eed;
1863         BMIter iter;
1864         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1865
1866         int tot_rotate_all = 0, tot_failed_all = 0;
1867         bool no_selected_edges = true, invalid_selected_edges = true;
1868
1869         ViewLayer *view_layer = CTX_data_view_layer(C);
1870         uint objects_len = 0;
1871         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1872         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1873                 Object *obedit = objects[ob_index];
1874                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1875                 int tot = 0;
1876
1877                 if (em->bm->totedgesel == 0) {
1878                         continue;
1879                 }
1880                 no_selected_edges = false;
1881
1882                 /* first see if we have two adjacent faces */
1883                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1884                         BM_elem_flag_disable(eed, BM_ELEM_TAG);
1885                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1886                                 BMFace *fa, *fb;
1887                                 if (BM_edge_face_pair(eed, &fa, &fb)) {
1888                                         /* if both faces are selected we rotate between them,
1889                                          * otherwise - rotate between 2 unselected - but not mixed */
1890                                         if (BM_elem_flag_test(fa, BM_ELEM_SELECT) == BM_elem_flag_test(fb, BM_ELEM_SELECT)) {
1891                                                 BM_elem_flag_enable(eed, BM_ELEM_TAG);
1892                                                 tot++;
1893                                         }
1894                                 }
1895                         }
1896                 }
1897
1898                 /* ok, we don't have two adjacent faces, but we do have two selected ones.
1899                  * that's an error condition.*/
1900                 if (tot == 0) {
1901                         continue;
1902                 }
1903                 invalid_selected_edges = false;
1904
1905                 BMOperator bmop;
1906                 EDBM_op_init(em, &bmop, op, "rotate_edges edges=%he use_ccw=%b", BM_ELEM_TAG, use_ccw);
1907
1908                 /* avoids leaving old verts selected which can be a problem running multiple times,
1909                  * since this means the edges become selected around the face which then attempt to rotate */
1910                 BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_in, "edges", BM_EDGE, BM_ELEM_SELECT, true);
1911
1912                 BMO_op_exec(em->bm, &bmop);
1913                 /* edges may rotate into hidden vertices, if this does _not_ run we get an illogical state */
1914                 BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, true);
1915                 BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1916
1917                 const int tot_rotate = BMO_slot_buffer_count(bmop.slots_out, "edges.out");
1918                 const int tot_failed = tot - tot_rotate;
1919
1920                 tot_rotate_all += tot_rotate;
1921                 tot_failed_all += tot_failed;
1922
1923                 if (tot_failed != 0) {
1924                         /* If some edges fail to rotate, we need to re-select them,
1925                          * otherwise we can end up with invalid selection
1926                          * (unselected edge between 2 selected faces). */
1927                         BM_mesh_elem_hflag_enable_test(em->bm, BM_EDGE, BM_ELEM_SELECT, true, false, BM_ELEM_TAG);
1928                 }
1929
1930                 EDBM_selectmode_flush(em);
1931
1932                 if (!EDBM_op_finish(em, &bmop, op, true)) {
1933                         continue;
1934                 }
1935
1936                 EDBM_update_generic(em, true, true);
1937         }
1938         MEM_freeN(objects);
1939
1940         if (no_selected_edges) {
1941                 BKE_report(op->reports, RPT_ERROR, "Select edges or face pairs for edge loops to rotate about");
1942                 return OPERATOR_CANCELLED;
1943         }
1944
1945         /* Ok, we don't have two adjacent faces, but we do have two selected ones.
1946          * that's an error condition. */
1947         if (invalid_selected_edges) {
1948                 BKE_report(op->reports, RPT_ERROR, "Could not find any selected edges that can be rotated");
1949                 return OPERATOR_CANCELLED;
1950         }
1951
1952         if (tot_failed_all != 0) {
1953                 BKE_reportf(op->reports, RPT_WARNING, "Unable to rotate %d edge(s)", tot_failed_all);
1954         }
1955
1956         return OPERATOR_FINISHED;
1957 }
1958
1959 void MESH_OT_edge_rotate(wmOperatorType *ot)
1960 {
1961         /* identifiers */
1962         ot->name = "Rotate Selected Edge";
1963         ot->description = "Rotate selected edge or adjoining faces";
1964         ot->idname = "MESH_OT_edge_rotate";
1965
1966         /* api callbacks */
1967         ot->exec = edbm_edge_rotate_selected_exec;
1968         ot->poll = ED_operator_editmesh;
1969
1970         /* flags */
1971         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1972
1973         /* props */
1974         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
1975 }
1976
1977 /** \} */
1978
1979 /* -------------------------------------------------------------------- */
1980 /** \name Hide Operator
1981  * \{ */
1982
1983 static int edbm_hide_exec(bContext *C, wmOperator *op)
1984 {
1985         const bool unselected = RNA_boolean_get(op->ptr, "unselected");
1986         ViewLayer *view_layer = CTX_data_view_layer(C);
1987
1988         uint objects_len = 0;
1989         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
1990         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
1991                 Object *obedit = objects[ob_index];
1992                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1993                 BMesh *bm = em->bm;
1994
1995                 if ((bm->totvertsel == 0) &&
1996                     (bm->totedgesel == 0) &&
1997                     (bm->totfacesel == 0))
1998                 {
1999                         continue;
2000                 }
2001
2002                 EDBM_mesh_hide(em, unselected);
2003                 EDBM_update_generic(em, true, false);
2004         }
2005
2006         MEM_freeN(objects);
2007         return OPERATOR_FINISHED;
2008 }
2009
2010 void MESH_OT_hide(wmOperatorType *ot)
2011 {
2012         /* identifiers */
2013         ot->name = "Hide Selection";
2014         ot->idname = "MESH_OT_hide";
2015         ot->description = "Hide (un)selected vertices, edges or faces";
2016
2017         /* api callbacks */
2018         ot->exec = edbm_hide_exec;
2019         ot->poll = ED_operator_editmesh;
2020
2021         /* flags */
2022         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2023
2024         /* props */
2025         RNA_def_boolean(ot->srna, "unselected", false, "Unselected", "Hide unselected rather than selected");
2026 }
2027
2028 /** \} */
2029
2030 /* -------------------------------------------------------------------- */
2031 /** \name Reveal Operator
2032  * \{ */
2033
2034 static int edbm_reveal_exec(bContext *C, wmOperator *op)
2035 {
2036         const bool select = RNA_boolean_get(op->ptr, "select");
2037         ViewLayer *view_layer = CTX_data_view_layer(C);
2038
2039         uint objects_len = 0;
2040         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2041         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2042                 Object *obedit = objects[ob_index];
2043                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2044
2045                 EDBM_mesh_reveal(em, select);
2046                 EDBM_update_generic(em, true, false);
2047         }
2048         MEM_freeN(objects);
2049
2050         return OPERATOR_FINISHED;
2051 }
2052
2053 void MESH_OT_reveal(wmOperatorType *ot)
2054 {
2055         /* identifiers */
2056         ot->name = "Reveal Hidden";
2057         ot->idname = "MESH_OT_reveal";
2058         ot->description = "Reveal all hidden vertices, edges and faces";
2059
2060         /* api callbacks */
2061         ot->exec = edbm_reveal_exec;
2062         ot->poll = ED_operator_editmesh;
2063
2064         /* flags */
2065         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2066
2067         RNA_def_boolean(ot->srna, "select", true, "Select", "");
2068 }
2069
2070 /** \} */
2071
2072 /* -------------------------------------------------------------------- */
2073 /** \name Recalculate Normals Operator
2074  * \{ */
2075
2076 static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op)
2077 {
2078         ViewLayer *view_layer = CTX_data_view_layer(C);
2079
2080         uint objects_len = 0;
2081         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2082         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2083                 Object *obedit = objects[ob_index];
2084                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2085
2086                 if (em->bm->totfacesel == 0) {
2087                         continue;
2088                 }
2089
2090                 if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT)) {
2091                         continue;
2092                 }
2093                 if (RNA_boolean_get(op->ptr, "inside")) {
2094                         EDBM_op_callf(em, op, "reverse_faces faces=%hf flip_multires=%b", BM_ELEM_SELECT, true);
2095                 }
2096
2097                 EDBM_update_generic(em, true, false);
2098         }
2099         MEM_freeN(objects);
2100
2101         return OPERATOR_FINISHED;
2102 }
2103
2104 void MESH_OT_normals_make_consistent(wmOperatorType *ot)
2105 {
2106         /* identifiers */
2107         ot->name = "Make Normals Consistent";
2108         ot->description = "Make face and vertex normals point either outside or inside the mesh";
2109         ot->idname = "MESH_OT_normals_make_consistent";
2110
2111         /* api callbacks */
2112         ot->exec = edbm_normals_make_consistent_exec;
2113         ot->poll = ED_operator_editmesh;
2114
2115         /* flags */
2116         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2117
2118         RNA_def_boolean(ot->srna, "inside", false, "Inside", "");
2119 }
2120
2121 /** \} */
2122
2123 /* -------------------------------------------------------------------- */
2124 /** \name Smooth Vertex Operator
2125  * \{ */
2126
2127 static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
2128 {
2129         const float fac = RNA_float_get(op->ptr, "factor");
2130
2131         const bool xaxis = RNA_boolean_get(op->ptr, "xaxis");
2132         const bool yaxis = RNA_boolean_get(op->ptr, "yaxis");
2133         const bool zaxis = RNA_boolean_get(op->ptr, "zaxis");
2134         int repeat = RNA_int_get(op->ptr, "repeat");
2135
2136         if (!repeat) {
2137                 repeat = 1;
2138         }
2139
2140         ViewLayer *view_layer = CTX_data_view_layer(C);
2141         uint objects_len = 0;
2142         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2143         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2144                 Object *obedit = objects[ob_index];
2145                 Mesh *me = obedit->data;
2146                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2147                 ModifierData *md;
2148                 bool mirrx = false, mirry = false, mirrz = false;
2149                 int i;
2150                 float clip_dist = 0.0f;
2151                 const bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
2152
2153                 if (em->bm->totvertsel == 0) {
2154                         continue;
2155                 }
2156
2157                 /* mirror before smooth */
2158                 if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
2159                         EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
2160                 }
2161
2162                 /* if there is a mirror modifier with clipping, flag the verts that
2163                  * are within tolerance of the plane(s) of reflection
2164                  */
2165                 for (md = obedit->modifiers.first; md; md = md->next) {
2166                         if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
2167                                 MirrorModifierData *mmd = (MirrorModifierData *)md;
2168
2169                                 if (mmd->flag & MOD_MIR_CLIPPING) {
2170                                         if (mmd->flag & MOD_MIR_AXIS_X)
2171                                                 mirrx = true;
2172                                         if (mmd->flag & MOD_MIR_AXIS_Y)
2173                                                 mirry = true;
2174                                         if (mmd->flag & MOD_MIR_AXIS_Z)
2175                                                 mirrz = true;
2176
2177                                         clip_dist = mmd->tolerance;
2178                                 }
2179                         }
2180                 }
2181
2182                 for (i = 0; i < repeat; i++) {
2183                         if (!EDBM_op_callf(
2184                                 em, op,
2185                                 "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b "
2186                                 "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b",
2187                                 BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
2188                         {
2189                                 continue;
2190                         }
2191                 }
2192
2193                 /* apply mirror */
2194                 if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
2195                         EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
2196                         EDBM_verts_mirror_cache_end(em);
2197                 }
2198
2199                 EDBM_update_generic(em, true, false);
2200         }
2201         MEM_freeN(objects);
2202
2203         return OPERATOR_FINISHED;
2204 }
2205
2206 void MESH_OT_vertices_smooth(wmOperatorType *ot)
2207 {
2208         /* identifiers */
2209         ot->name = "Smooth Vertex";
2210         ot->description = "Flatten angles of selected vertices";
2211         ot->idname = "MESH_OT_vertices_smooth";
2212
2213         /* api callbacks */
2214         ot->exec = edbm_do_smooth_vertex_exec;
2215         ot->poll = ED_operator_editmesh;
2216
2217         /* flags */
2218         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2219
2220         ot->prop = RNA_def_float(ot->srna, "factor", 0.5f, -10.0f, 10.0f, "Smoothing", "Smoothing factor", 0.0f, 1.0f);
2221         RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Repeat", "Number of times to smooth the mesh", 1, 100);
2222
2223         WM_operatortype_props_advanced_begin(ot);
2224
2225         RNA_def_boolean(ot->srna, "xaxis", true, "X-Axis", "Smooth along the X axis");
2226         RNA_def_boolean(ot->srna, "yaxis", true, "Y-Axis", "Smooth along the Y axis");
2227         RNA_def_boolean(ot->srna, "zaxis", true, "Z-Axis", "Smooth along the Z axis");
2228 }
2229
2230 /** \} */
2231
2232 /* -------------------------------------------------------------------- */
2233 /** \name Laplacian Vertex Smooth Operator
2234  * \{ */
2235
2236 static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
2237 {
2238         BMIter fiter;
2239         BMFace *f;
2240         int tot_invalid = 0;
2241         int tot_unselected = 0;
2242         ViewLayer *view_layer = CTX_data_view_layer(C);
2243
2244         const float lambda_factor = RNA_float_get(op->ptr, "lambda_factor");
2245         const float lambda_border = RNA_float_get(op->ptr, "lambda_border");
2246         const bool usex = RNA_boolean_get(op->ptr, "use_x");
2247         const bool usey = RNA_boolean_get(op->ptr, "use_y");
2248         const bool usez = RNA_boolean_get(op->ptr, "use_z");
2249         const bool preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume");
2250         int repeat = RNA_int_get(op->ptr, "repeat");
2251
2252         if (!repeat) {
2253                 repeat = 1;
2254         }
2255
2256         uint objects_len = 0;
2257         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2258         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2259                 Object *obedit = objects[ob_index];
2260                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2261                 Mesh *me = obedit->data;
2262                 bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
2263
2264                 if (em->bm->totvertsel == 0) {
2265                         tot_unselected++;
2266                         tot_invalid++;
2267                         continue;
2268                 }
2269
2270                 bool is_invalid = false;
2271                 /* Check if select faces are triangles. */
2272                 BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
2273                         if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
2274                                 if (f->len > 4) {
2275                                         tot_invalid++;
2276                                         is_invalid = true;
2277                                         break;
2278                                 }
2279                         }
2280                 }
2281                 if (is_invalid) {
2282                         continue;
2283                 }
2284
2285                 /* Mirror before smooth. */
2286                 if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
2287                         EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
2288                 }
2289
2290                 bool failed_repeat_loop = false;
2291                 for (int i = 0; i < repeat; i++) {
2292                         if (!EDBM_op_callf(
2293                                 em, op,
2294                                 "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
2295                                 BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
2296                         {
2297                                 failed_repeat_loop = true;
2298                                 break;
2299                         }
2300                 }
2301                 if (failed_repeat_loop) {
2302                         continue;
2303                 }
2304
2305                 /* Apply mirror. */
2306                 if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
2307                         EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
2308                         EDBM_verts_mirror_cache_end(em);
2309                 }
2310
2311                 EDBM_update_generic(em, true, false);
2312         }
2313         MEM_freeN(objects);
2314
2315         if (tot_unselected == objects_len) {
2316                 BKE_report(op->reports, RPT_WARNING, "No selected vertex");
2317                 return OPERATOR_CANCELLED;
2318         }
2319         else if (tot_invalid == objects_len) {
2320                 BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
2321                 return OPERATOR_CANCELLED;
2322         }
2323
2324         return OPERATOR_FINISHED;
2325 }
2326
2327 void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
2328 {
2329         /* identifiers */
2330         ot->name = "Laplacian Smooth Vertex";
2331         ot->description = "Laplacian smooth of selected vertices";
2332         ot->idname = "MESH_OT_vertices_smooth_laplacian";
2333
2334         /* api callbacks */
2335         ot->exec = edbm_do_smooth_laplacian_vertex_exec;
2336         ot->poll = ED_operator_editmesh;
2337
2338         /* flags */
2339         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2340
2341         RNA_def_int(ot->srna, "repeat", 1, 1, 1000,
2342                     "Number of iterations to smooth the mesh", "", 1, 200);
2343         RNA_def_float(ot->srna, "lambda_factor", 1.0f, 1e-7f, 1000.0f,
2344                       "Lambda factor", "", 1e-7f, 1000.0f);
2345         RNA_def_float(ot->srna, "lambda_border", 5e-5f, 1e-7f, 1000.0f,
2346                       "Lambda factor in border", "", 1e-7f, 1000.0f);
2347
2348         WM_operatortype_props_advanced_begin(ot);
2349
2350         RNA_def_boolean(ot->srna, "use_x", true, "Smooth X Axis", "Smooth object along X axis");
2351         RNA_def_boolean(ot->srna, "use_y", true, "Smooth Y Axis", "Smooth object along Y axis");
2352         RNA_def_boolean(ot->srna, "use_z", true, "Smooth Z Axis", "Smooth object along Z axis");
2353         RNA_def_boolean(ot->srna, "preserve_volume", true, "Preserve Volume", "Apply volume preservation after smooth");
2354 }
2355
2356 /** \} */
2357
2358 /* -------------------------------------------------------------------- */
2359 /** \name Set Faces Smooth Shading Operator
2360  * \{ */
2361
2362 static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
2363 {
2364         BMIter iter;
2365         BMFace *efa;
2366
2367         if (em == NULL) return;
2368
2369         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2370                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
2371                         BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth);
2372                 }
2373         }
2374 }
2375
2376 static int edbm_faces_shade_smooth_exec(bContext *C, wmOperator *UNUSED(op))
2377 {
2378         ViewLayer *view_layer = CTX_data_view_layer(C);
2379         uint objects_len = 0;
2380         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2381         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2382                 Object *obedit = objects[ob_index];
2383                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2384
2385                 if (em->bm->totfacesel == 0) {
2386                         continue;
2387                 }
2388
2389                 mesh_set_smooth_faces(em, 1);
2390                 EDBM_update_generic(em, false, false);
2391         }
2392         MEM_freeN(objects);
2393
2394         return OPERATOR_FINISHED;
2395 }
2396
2397 void MESH_OT_faces_shade_smooth(wmOperatorType *ot)
2398 {
2399         /* identifiers */
2400         ot->name = "Shade Smooth";
2401         ot->description = "Display faces smooth (using vertex normals)";
2402         ot->idname = "MESH_OT_faces_shade_smooth";
2403
2404         /* api callbacks */
2405         ot->exec = edbm_faces_shade_smooth_exec;
2406         ot->poll = ED_operator_editmesh;
2407
2408         /* flags */
2409         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2410 }
2411
2412 /** \} */
2413
2414 /* -------------------------------------------------------------------- */
2415 /** \name Set Faces Flat Shading Operator
2416  * \{ */
2417
2418 static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op))
2419 {
2420         ViewLayer *view_layer = CTX_data_view_layer(C);
2421         uint objects_len = 0;
2422         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2423         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2424                 Object *obedit = objects[ob_index];
2425                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2426
2427                 if (em->bm->totfacesel == 0) {
2428                         continue;
2429                 }
2430
2431                 mesh_set_smooth_faces(em, 0);
2432                 EDBM_update_generic(em, false, false);
2433         }
2434         MEM_freeN(objects);
2435
2436         return OPERATOR_FINISHED;
2437 }
2438
2439 void MESH_OT_faces_shade_flat(wmOperatorType *ot)
2440 {
2441         /* identifiers */
2442         ot->name = "Shade Flat";
2443         ot->description = "Display faces flat";
2444         ot->idname = "MESH_OT_faces_shade_flat";
2445
2446         /* api callbacks */
2447         ot->exec = edbm_faces_shade_flat_exec;
2448         ot->poll = ED_operator_editmesh;
2449
2450         /* flags */
2451         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2452 }
2453
2454 /** \} */
2455
2456 /* -------------------------------------------------------------------- */
2457 /** \name UV/Color Rotate/Reverse Operator
2458  * \{ */
2459
2460 static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op)
2461 {
2462         /* get the direction from RNA */
2463         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
2464
2465         ViewLayer *view_layer = CTX_data_view_layer(C);
2466         uint objects_len = 0;
2467         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2468         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2469                 Object *obedit = objects[ob_index];
2470                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2471
2472                 if (em->bm->totfacesel == 0) {
2473                         continue;
2474                 }
2475
2476                 BMOperator bmop;
2477
2478                 /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
2479                 EDBM_op_init(em, &bmop, op, "rotate_uvs faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
2480
2481                 /* execute the operator */
2482                 BMO_op_exec(em->bm, &bmop);
2483
2484                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2485                         continue;
2486                 }
2487
2488                 EDBM_update_generic(em, false, false);
2489         }
2490
2491         MEM_freeN(objects);
2492         return OPERATOR_FINISHED;
2493 }
2494
2495 static int edbm_reverse_uvs_exec(bContext *C, wmOperator *op)
2496 {
2497         ViewLayer *view_layer = CTX_data_view_layer(C);
2498         uint objects_len = 0;
2499         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2500         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2501                 Object *obedit = objects[ob_index];
2502                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2503
2504                 if (em->bm->totfacesel == 0) {
2505                         continue;
2506                 }
2507
2508                 BMOperator bmop;
2509
2510                 /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
2511                 EDBM_op_init(em, &bmop, op, "reverse_uvs faces=%hf", BM_ELEM_SELECT);
2512
2513                 /* execute the operator */
2514                 BMO_op_exec(em->bm, &bmop);
2515
2516                 /* finish the operator */
2517                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2518                         continue;
2519                 }
2520                 EDBM_update_generic(em, false, false);
2521         }
2522
2523         MEM_freeN(objects);
2524         return OPERATOR_FINISHED;
2525 }
2526
2527 static int edbm_rotate_colors_exec(bContext *C, wmOperator *op)
2528 {
2529                 /* get the direction from RNA */
2530         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
2531
2532         ViewLayer *view_layer = CTX_data_view_layer(C);
2533         uint objects_len = 0;
2534         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2535
2536         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2537                 Object *ob = objects[ob_index];
2538                 BMEditMesh *em = BKE_editmesh_from_object(ob);
2539                 if (em->bm->totfacesel == 0) {
2540                         continue;
2541                 }
2542
2543                 BMOperator bmop;
2544
2545                 /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
2546                 EDBM_op_init(em, &bmop, op, "rotate_colors faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
2547
2548                 /* execute the operator */
2549                 BMO_op_exec(em->bm, &bmop);
2550
2551                 /* finish the operator */
2552                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2553                         continue;
2554                 }
2555
2556                 /* dependencies graph and notification stuff */
2557                 EDBM_update_generic(em, false, false);
2558         }
2559
2560         MEM_freeN(objects);
2561
2562         return OPERATOR_FINISHED;
2563 }
2564
2565
2566 static int edbm_reverse_colors_exec(bContext *C, wmOperator *op)
2567 {
2568         ViewLayer *view_layer = CTX_data_view_layer(C);
2569         uint objects_len = 0;
2570         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2571
2572         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2573                 Object *ob = objects[ob_index];
2574                 BMEditMesh *em = BKE_editmesh_from_object(ob);
2575
2576                 if (em->bm->totfacesel == 0) {
2577                         continue;
2578                 }
2579
2580                 BMOperator bmop;
2581
2582                 /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
2583                 EDBM_op_init(em, &bmop, op, "reverse_colors faces=%hf", BM_ELEM_SELECT);
2584
2585                 /* execute the operator */
2586                 BMO_op_exec(em->bm, &bmop);
2587
2588                 /* finish the operator */
2589                 if (!EDBM_op_finish(em, &bmop, op, true)) {
2590                         return OPERATOR_CANCELLED;
2591                 }
2592
2593                 EDBM_update_generic(em, false, false);
2594         }
2595         MEM_freeN(objects);
2596
2597         return OPERATOR_FINISHED;
2598 }
2599
2600 void MESH_OT_uvs_rotate(wmOperatorType *ot)
2601 {
2602         /* identifiers */
2603         ot->name = "Rotate UVs";
2604         ot->idname = "MESH_OT_uvs_rotate";
2605         ot->description = "Rotate UV coordinates inside faces";
2606
2607         /* api callbacks */
2608         ot->exec = edbm_rotate_uvs_exec;
2609         ot->poll = ED_operator_editmesh;
2610
2611         /* flags */
2612         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2613
2614         /* props */
2615         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
2616 }
2617
2618 void MESH_OT_uvs_reverse(wmOperatorType *ot)
2619 {
2620         /* identifiers */
2621         ot->name = "Reverse UVs";
2622         ot->idname = "MESH_OT_uvs_reverse";
2623         ot->description = "Flip direction of UV coordinates inside faces";
2624
2625         /* api callbacks */
2626         ot->exec = edbm_reverse_uvs_exec;
2627         ot->poll = ED_operator_editmesh;
2628
2629         /* flags */
2630         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2631
2632         /* props */
2633         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror UVs around");
2634 }
2635
2636 void MESH_OT_colors_rotate(wmOperatorType *ot)
2637 {
2638         /* identifiers */
2639         ot->name = "Rotate Colors";
2640         ot->idname = "MESH_OT_colors_rotate";
2641         ot->description = "Rotate vertex colors inside faces";
2642
2643         /* api callbacks */
2644         ot->exec = edbm_rotate_colors_exec;
2645         ot->poll = ED_operator_editmesh;
2646
2647         /* flags */
2648         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2649
2650         /* props */
2651         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
2652 }
2653
2654 void MESH_OT_colors_reverse(wmOperatorType *ot)
2655 {
2656         /* identifiers */
2657         ot->name = "Reverse Colors";
2658         ot->idname = "MESH_OT_colors_reverse";
2659         ot->description = "Flip direction of vertex colors inside faces";
2660
2661         /* api callbacks */
2662         ot->exec = edbm_reverse_colors_exec;
2663         ot->poll = ED_operator_editmesh;
2664
2665         /* flags */
2666         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2667
2668         /* props */
2669         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around");
2670 }
2671
2672 /** \} */
2673
2674 /* -------------------------------------------------------------------- */
2675 /** \name Merge Vertices Operator
2676  * \{ */
2677
2678 enum {
2679         MESH_MERGE_LAST     = 1,
2680         MESH_MERGE_CENTER   = 3,
2681         MESH_MERGE_CURSOR   = 4,
2682         MESH_MERGE_COLLAPSE = 5,
2683         MESH_MERGE_FIRST    = 6,
2684 };
2685
2686 static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use_uvmerge, wmOperator *wmop)
2687 {
2688         BMVert *mergevert;
2689         BMEditSelection *ese;
2690
2691         /* operator could be called directly from shortcut or python,
2692          * so do extra check for data here
2693          */
2694
2695         /* do sanity check in mergemenu in edit.c ?*/
2696         if (use_first == false) {
2697                 if (!em->bm->selected.last || ((BMEditSelection *)em->bm->selected.last)->htype != BM_VERT)
2698                         return false;
2699
2700                 ese = em->bm->selected.last;
2701                 mergevert = (BMVert *)ese->ele;
2702         }
2703         else {
2704                 if (!em->bm->selected.first || ((BMEditSelection *)em->bm->selected.first)->htype != BM_VERT)
2705                         return false;
2706
2707                 ese = em->bm->selected.first;
2708                 mergevert = (BMVert *)ese->ele;
2709         }
2710
2711         if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT))
2712                 return false;
2713
2714         if (use_uvmerge) {
2715                 if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert))
2716                         return false;
2717         }
2718
2719         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, mergevert->co))
2720                 return false;
2721
2722         return true;
2723 }
2724
2725 static bool merge_target(
2726         BMEditMesh *em, Scene *scene, Object *ob,
2727         const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
2728 {
2729         BMIter iter;
2730         BMVert *v;
2731         float co[3], cent[3] = {0.0f, 0.0f, 0.0f};
2732         const float *vco = NULL;
2733
2734         if (use_cursor) {
2735                 vco = scene->cursor.location;
2736                 copy_v3_v3(co, vco);
2737                 invert_m4_m4(ob->imat, ob->obmat);
2738                 mul_m4_v3(ob->imat, co);
2739         }
2740         else {
2741                 float fac;
2742                 int i = 0;
2743                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2744                         if (!BM_elem_flag_test(v, BM_ELEM_SELECT))
2745                                 continue;
2746                         add_v3_v3(cent, v->co);
2747                         i++;
2748                 }
2749
2750                 if (!i)
2751                         return false;
2752
2753                 fac = 1.0f / (float)i;
2754                 mul_v3_fl(cent, fac);
2755                 copy_v3_v3(co, cent);
2756                 vco = co;
2757         }
2758
2759         if (!vco)
2760                 return false;
2761
2762         if (use_uvmerge) {
2763                 if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT))
2764                         return false;
2765         }
2766
2767         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, co))
2768                 return false;
2769
2770         return true;
2771 }
2772
2773 static int edbm_merge_exec(bContext *C, wmOperator *op)
2774 {
2775         Scene *scene = CTX_data_scene(C);
2776         ViewLayer *view_layer = CTX_data_view_layer(C);
2777         uint objects_len = 0;
2778         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2779         const int type = RNA_enum_get(op->ptr, "type");
2780         const bool uvs = RNA_boolean_get(op->ptr, "uvs");
2781
2782         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2783                 Object *obedit = objects[ob_index];
2784                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2785
2786                 if (em->bm->totvertsel == 0) {
2787                         continue;
2788                 }
2789
2790                 bool ok = false;
2791                 switch (type) {
2792                         case MESH_MERGE_CENTER:
2793                                 ok = merge_target(em, scene, obedit, false, uvs, op);
2794                                 break;
2795                         case MESH_MERGE_CURSOR:
2796                                 ok = merge_target(em, scene, obedit, true, uvs, op);
2797                                 break;
2798                         case MESH_MERGE_LAST:
2799                                 ok = merge_firstlast(em, false, uvs, op);
2800                                 break;
2801                         case MESH_MERGE_FIRST:
2802                                 ok = merge_firstlast(em, true, uvs, op);
2803                                 break;
2804                         case MESH_MERGE_COLLAPSE:
2805                                 ok = EDBM_op_callf(em, op, "collapse edges=%he uvs=%b", BM_ELEM_SELECT, uvs);
2806                                 break;
2807                         default:
2808                                 BLI_assert(0);
2809                                 break;
2810                 }
2811
2812                 if (!ok) {
2813                         continue;
2814                 }
2815
2816                 EDBM_update_generic(em, true, true);
2817
2818                 /* once collapsed, we can't have edge/face selection */
2819                 if ((em->selectmode & SCE_SELECT_VERTEX) == 0) {
2820                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2821                 }
2822                 /* Only active object supported, see comment below. */
2823                 if (ELEM(type, MESH_MERGE_FIRST, MESH_MERGE_LAST)) {
2824                         break;
2825                 }
2826         }
2827
2828         MEM_freeN(objects);
2829
2830         return OPERATOR_FINISHED;
2831 }
2832
2833 static const EnumPropertyItem merge_type_items[] = {
2834         {MESH_MERGE_FIRST, "FIRST", 0, "At First", ""},
2835         {MESH_MERGE_LAST, "LAST", 0, "At Last", ""},
2836         {MESH_MERGE_CENTER, "CENTER", 0, "At Center", ""},
2837         {MESH_MERGE_CURSOR, "CURSOR", 0, "At Cursor", ""},
2838         {MESH_MERGE_COLLAPSE, "COLLAPSE", 0, "Collapse", ""},
2839         {0, NULL, 0, NULL, NULL}
2840 };
2841
2842 static const EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
2843 {
2844         Object *obedit;
2845         EnumPropertyItem *item = NULL;
2846         int totitem = 0;
2847
2848         if (!C) /* needed for docs */
2849                 return merge_type_items;
2850
2851         obedit = CTX_data_edit_object(C);
2852         if (obedit && obedit->type == OB_MESH) {
2853                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2854
2855                 /* Only active object supported:
2856                  * In practice it doesn't make sense to run this operation on non-active meshes
2857                  * since selecting will activate - we could have own code-path for these but it's a hassle
2858                  * for now just apply to the active (first) object. */
2859                 if (em->selectmode & SCE_SELECT_VERTEX) {
2860                         if (em->bm->selected.first && em->bm->selected.last &&
2861                             ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT &&
2862                             ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT)
2863                         {
2864                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST);
2865                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST);
2866                         }
2867                         else if (em->bm->selected.first && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT) {
2868                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_FIRST);
2869                         }
2870                         else if (em->bm->selected.last && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) {
2871                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_LAST);
2872                         }
2873                 }
2874
2875                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CENTER);
2876                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_CURSOR);
2877                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, MESH_MERGE_COLLAPSE);
2878                 RNA_enum_item_end(&item, &totitem);
2879
2880                 *r_free = true;
2881
2882                 return item;
2883         }
2884
2885         return NULL;
2886 }
2887
2888 void MESH_OT_merge(wmOperatorType *ot)
2889 {
2890         /* identifiers */
2891         ot->name = "Merge";
2892         ot->description = "Merge selected vertices";
2893         ot->idname = "MESH_OT_merge";
2894
2895         /* api callbacks */
2896         ot->exec = edbm_merge_exec;
2897         ot->invoke = WM_menu_invoke;
2898         ot->poll = ED_operator_editmesh;
2899
2900         /* flags */
2901         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2902
2903         /* properties */
2904         ot->prop = RNA_def_enum(ot->srna, "type", merge_type_items, MESH_MERGE_CENTER, "Type", "Merge method to use");
2905         RNA_def_enum_funcs(ot->prop, merge_type_itemf);
2906
2907         WM_operatortype_props_advanced_begin(ot);
2908
2909         RNA_def_boolean(ot->srna, "uvs", false, "UVs", "Move UVs according to merge");
2910 }
2911
2912 /** \} */
2913
2914 /* -------------------------------------------------------------------- */
2915 /** \name Remove Doubles Operator
2916  * \{ */
2917
2918 static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
2919 {
2920         const float threshold = RNA_float_get(op->ptr, "threshold");
2921         const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
2922         int count_multi = 0;
2923
2924         ViewLayer *view_layer = CTX_data_view_layer(C);
2925         uint objects_len = 0;
2926         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
2927
2928         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
2929                 Object *obedit = objects[ob_index];
2930                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2931
2932                 /* Selection used as target with 'use_unselected'. */
2933                 if (em->bm->totvertsel == 0) {
2934                         continue;
2935                 }
2936
2937                 BMOperator bmop;
2938                 const int totvert_orig = em->bm->totvert;
2939
2940                 /* avoid losing selection state (select -> tags) */
2941                 char htype_select;
2942                 if      (em->selectmode & SCE_SELECT_VERTEX) htype_select = BM_VERT;
2943                 else if (em->selectmode & SCE_SELECT_EDGE)   htype_select = BM_EDGE;
2944                 else                                         htype_select = BM_FACE;
2945
2946                 /* store selection as tags */
2947                 BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_TAG, true, true, BM_ELEM_SELECT);
2948
2949
2950                 if (use_unselected) {
2951                         EDBM_op_init(
2952                                 em, &bmop, op,
2953                                 "automerge verts=%hv dist=%f",
2954                                 BM_ELEM_SELECT, threshold);
2955                         BMO_op_exec(em->bm, &bmop);
2956
2957                         if (!EDBM_op_finish(em, &bmop, op, true)) {
2958                                 continue;
2959                         }
2960                 }
2961                 else {
2962                         EDBM_op_init(
2963                                 em, &bmop, op,
2964                                 "find_doubles verts=%hv dist=%f",
2965                                 BM_ELEM_SELECT, threshold);
2966
2967                         BMO_op_exec(em->bm, &bmop);
2968
2969                         if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) {
2970                                 BMO_op_finish(em->bm, &bmop);
2971                                 continue;
2972                         }
2973
2974                         if (!EDBM_op_finish(em, &bmop, op, true)) {
2975                                 continue;
2976                         }
2977                 }
2978
2979                 const int count = (totvert_orig - em->bm->totvert);
2980
2981                 /* restore selection from tags */
2982                 BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_SELECT, true, true, BM_ELEM_TAG);
2983                 EDBM_selectmode_flush(em);
2984
2985                 if (count) {
2986                         count_multi += count;
2987                         EDBM_update_generic(em, true, true);
2988                 }
2989         }
2990         MEM_freeN(objects);
2991
2992         BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count_multi);
2993
2994         return OPERATOR_FINISHED;
2995 }
2996
2997 void MESH_OT_remove_doubles(wmOperatorType *ot)
2998 {
2999         /* identifiers */
3000         ot->name = "Remove Doubles";
3001         ot->description = "Remove duplicate vertices";
3002         ot->idname = "MESH_OT_remove_doubles";
3003
3004         /* api callbacks */
3005         ot->exec = edbm_remove_doubles_exec;
3006         ot->poll = ED_operator_editmesh;
3007
3008         /* flags */
3009         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3010
3011         RNA_def_float_distance(ot->srna, "threshold", 1e-4f, 1e-6f, 50.0f, "Merge Distance",
3012                                "Minimum distance between elements to merge", 1e-5f, 10.0f);
3013         RNA_def_boolean(ot->srna, "use_unselected", false, "Unselected", "Merge selected to other unselected vertices");
3014 }
3015
3016 /** \} */
3017
3018 /* -------------------------------------------------------------------- */
3019 /** \name Shape Key Propagate Operator
3020  * \{ */
3021
3022 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
3023 static bool shape_propagate(BMEditMesh *em)
3024 {
3025         BMIter iter;
3026         BMVert *eve = NULL;
3027         float *co;
3028         int totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
3029
3030         if (!CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) {
3031                 return false;
3032         }
3033
3034         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
3035                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
3036                         continue;
3037                 }
3038
3039                 for (int i = 0; i < totshape; i++) {
3040                         co = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, i);
3041                         copy_v3_v3(co, eve->co);
3042                 }
3043         }
3044         return true;
3045 }
3046
3047 static int edbm_shape_propagate_to_all_exec(bContext *C, wmOperator *op)
3048 {
3049         ViewLayer *view_layer = CTX_data_view_layer(C);
3050         int tot_shapekeys = 0;
3051         int tot_selected_verts_objects = 0;
3052
3053         uint objects_len = 0;
3054         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
3055         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
3056                 Object *obedit = objects[ob_index];
3057                 Mesh *me = obedit->data;
3058                 BMEditMesh *em = me->edit_btmesh;
3059
3060                 if (em->bm->totvertsel == 0) {
3061                         continue;
3062                 }
3063                 tot_selected_verts_objects++;
3064
3065                 if (shape_propagate(em)) {
3066                         tot_shapekeys++;
3067                 }
3068
3069                 EDBM_update_generic(em, false, false);
3070         }
3071         MEM_freeN(objects);
3072
3073         if (tot_selected_verts_objects == 0) {
3074                 BKE_report(op->reports, RPT_ERROR, "No selected vertex");
3075                 return OPERATOR_CANCELLED;
3076         }
3077         else if (tot_shapekeys == 0) {
3078                 BKE_report(
3079                         op->reports,
3080                         RPT_ERROR,
3081                         objects_len > 1 ?
3082                         "Meshes do not have shape keys" :
3083                         "Mesh does not have shape keys");
3084                 return OPERATOR_CANCELLED;
3085         }
3086
3087         return OPERATOR_FINISHED;
3088 }
3089
3090
3091 void MESH_OT_shape_propagate_to_all(wmOperatorType *ot)
3092 {
3093         /* identifiers */
3094         ot->name = "Shape Propagate";
3095         ot->description = "Apply selected vertex locations to all other shape keys";
3096         ot->idname = "MESH_OT_shape_propagate_to_all";
3097
3098         /* api callbacks */
3099         ot->exec = edbm_shape_propagate_to_all_exec;
3100         ot->poll = ED_operator_editmesh;
3101
3102         /* flags */
3103         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3104 }
3105
3106 /** \} */
3107
3108 /* -------------------------------------------------------------------- */
3109 /** \name Blend from Shape Operator
3110  * \{ */
3111
3112 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
3113 static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
3114 {
3115         Object *obedit_ref = CTX_data_edit_object(C);
3116         Mesh *me_ref = obedit_ref->data;
3117         Key *key_ref = me_ref->key;
3118         KeyBlock *kb_ref = NULL;
3119         BMEditMesh *em_ref = me_ref->edit_btmesh;
3120         BMVert *eve;
3121         BMIter iter;
3122         ViewLayer *view_layer = CTX_data_view_layer(C);
3123         float co[3], *sco;
3124         int totshape_ref = 0;
3125
3126         const float blend = RNA_float_get(op->ptr, "blend");
3127         int shape_ref = RNA_enum_get(op->ptr, "shape");
3128         const bool use_add = RNA_boolean_get(op->ptr, "add");
3129
3130         /* Sanity check. */
3131         totshape_ref = CustomData_number_of_layers(&em_ref->bm->vdata, CD_SHAPEKEY);
3132
3133         if (totshape_ref == 0 || shape_ref < 0) {
3134                 BKE_report(op->reports, RPT_ERROR, "Active mesh does not have shape keys");
3135                 return OPERATOR_CANCELLED;
3136         }
3137         else if (shape_ref >= totshape_ref) {
3138                 /* This case occurs if operator was used before on object with more keys than current one. */
3139                 shape_ref = 0; /* default to basis */
3140         }
3141
3142         /* Get shape key - needed for finding reference shape (for add mode only). */
3143         if (key_ref) {
3144                 kb_ref = BLI_findlink(&key_ref->block, shape_ref);
3145         }
3146
3147         int tot_selected_verts_objects = 0;
3148         uint objects_len = 0;
3149         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
3150         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
3151                 Object *obedit = objects[ob_index];
3152                 Mesh *me = obedit->data;
3153                 Key *key = me->key;
3154                 KeyBlock *kb = NULL;
3155                 BMEditMesh *em = me->edit_btmesh;
3156                 int shape;
3157
3158                 if (em->bm->totvertsel == 0) {
3159                         continue;
3160                 }
3161                 tot_selected_verts_objects++;
3162
3163                 if (!key) {
3164                         continue;
3165                 }
3166                 else {
3167                         kb = BKE_keyblock_find_name(key, kb_ref->name);
3168                         shape = BLI_findindex(&key->block, kb);
3169                 }
3170
3171                 if (kb) {
3172                         /* Perform blending on selected vertices. */
3173                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
3174                                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
3175                                         continue;
3176
3177                                 /* Get coordinates of shapekey we're blending from. */
3178                                 sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape);
3179                                 copy_v3_v3(co, sco);
3180
3181                                 if (use_add) {
3182                                         /* In add mode, we add relative shape key offset. */
3183                                         if (kb) {
3184                                                 const float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative);
3185                                                 sub_v3_v3v3(co, co, rco);
3186                                         }
3187
3188                                         madd_v3_v3fl(eve->co, co, blend);
3189                                 }
3190                                 else {
3191                                         /* In blend mode, we interpolate to the shape key. */
3192                                         interp_v3_v3v3(eve->co, eve->co, co, blend);
3193                                 }
3194                         }
3195                         EDBM_update_generic(em, true, false);
3196                 }
3197         }
3198         MEM_freeN(objects);
3199
3200         if (tot_selected_verts_objects == 0) {
3201                 BKE_report(op->reports, RPT_ERROR, "No selected vertex");
3202                 return OPERATOR_CANCELLED;
3203         }
3204
3205         return OPERATOR_FINISHED;
3206 }
3207
3208 static const EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
3209 {
3210         Object *obedit = CTX_data_edit_object(C);
3211         BMEditMesh *em;
3212         EnumPropertyItem *item = NULL;
3213         int totitem = 0;
3214
3215         if ((obedit && obedit->type == OB_MESH) &&
3216             (em = BKE_editmesh_from_object(obedit)) &&
3217             CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY))
3218         {
3219                 EnumPropertyItem tmp = {0, "", 0, "", ""};
3220                 int a;
3221
3222                 for (a = 0; a < em->bm->vdata.totlayer; a++) {
3223                         if (em->bm->vdata.layers[a].type != CD_SHAPEKEY)
3224                                 continue;
3225
3226                         tmp.value = totitem;
3227                         tmp.identifier = em->bm->vdata.layers[a].name;
3228                         tmp.name = em->bm->vdata.layers[a].name;
3229                         /* RNA_enum_item_add sets totitem itself! */
3230                         RNA_enum_item_add(&item, &totitem, &tmp);
3231                 }
3232         }
3233
3234         RNA_enum_item_end(&item, &totitem);
3235         *r_free = true;
3236
3237         return item;
3238 }