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