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