Add Edge sharp/smooth to 3DView shading panel, as well as new Vert sharp/smooth.
[blender-staging.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_STRAIGHT_CUT)
94         {
95                 RNA_enum_set(op->ptr, "quadcorner", SUBD_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_INNERVERT,     "INNERVERT", 0,      "Inner Vert", ""},
114         {SUBD_PATH,          "PATH", 0,           "Path", ""},
115         {SUBD_STRAIGHT_CUT,  "STRAIGHT_CUT", 0,   "Straight Cut", ""},
116         {SUBD_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_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         const bool is_pair = (bm->totvertsel == 2);
881         int len;
882         
883         if (is_pair) {
884                 if (!EDBM_op_init(em, &bmop, op, "connect_vert_pair verts=%hv", BM_ELEM_SELECT)) {
885                         return OPERATOR_CANCELLED;
886                 }
887         }
888         else {
889                 if (!EDBM_op_init(em, &bmop, op, "connect_verts verts=%hv check_degenerate=%b", BM_ELEM_SELECT, true)) {
890                         return OPERATOR_CANCELLED;
891                 }
892         }
893
894         BMO_op_exec(bm, &bmop);
895         len = BMO_slot_get(bmop.slots_out, "edges.out")->len;
896
897         if (len) {
898                 if (is_pair) {
899                         /* new verts have been added, we have to select the edges, not just flush */
900                         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
901                 }
902         }
903
904         if (!EDBM_op_finish(em, &bmop, op, true)) {
905                 return OPERATOR_CANCELLED;
906         }
907         else {
908                 EDBM_selectmode_flush(em);  /* so newly created edges get the selection state from the vertex */
909
910                 EDBM_update_generic(em, true, true);
911
912                 return len ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
913         }
914 }
915
916 void MESH_OT_vert_connect(wmOperatorType *ot)
917 {
918         /* identifiers */
919         ot->name = "Vertex Connect";
920         ot->idname = "MESH_OT_vert_connect";
921         ot->description = "Connect 2 vertices of a face by an edge, splitting the face in two";
922         
923         /* api callbacks */
924         ot->exec = edbm_vert_connect_exec;
925         ot->poll = ED_operator_editmesh;
926         
927         /* flags */
928         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
929 }
930
931
932 static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op)
933 {
934         Object *obedit = CTX_data_edit_object(C);
935         BMEditMesh *em = BKE_editmesh_from_object(obedit);
936
937         const float angle_limit = RNA_float_get(op->ptr, "angle_limit");
938
939         if (!EDBM_op_call_and_selectf(
940                      em, op,
941                      "faces.out", true,
942                      "connect_verts_nonplanar faces=%hf angle_limit=%f",
943                      BM_ELEM_SELECT, angle_limit))
944         {
945                 return OPERATOR_CANCELLED;
946         }
947
948
949         EDBM_update_generic(em, true, true);
950         return OPERATOR_FINISHED;
951 }
952
953 void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot)
954 {
955         PropertyRNA *prop;
956
957         /* identifiers */
958         ot->name = "Split Non-Planar Faces";
959         ot->idname = "MESH_OT_vert_connect_nonplanar";
960         ot->description = "Split non-planar faces that exceed the angle threshold";
961
962         /* api callbacks */
963         ot->exec = edbm_vert_connect_nonplaner_exec;
964         ot->poll = ED_operator_editmesh;
965
966         /* flags */
967         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
968
969         /* props */
970         prop = RNA_def_float_rotation(ot->srna, "angle_limit", 0, NULL, 0.0f, DEG2RADF(180.0f),
971                                       "Max Angle", "Angle limit", 0.0f, DEG2RADF(180.0f));
972         RNA_def_property_float_default(prop, DEG2RADF(5.0f));
973 }
974
975
976 static int edbm_edge_split_exec(bContext *C, wmOperator *op)
977 {
978         Object *obedit = CTX_data_edit_object(C);
979         BMEditMesh *em = BKE_editmesh_from_object(obedit);
980
981         if (!EDBM_op_call_and_selectf(
982                 em, op,
983                 "edges.out", false,
984                 "split_edges edges=%he",
985                 BM_ELEM_SELECT))
986         {
987                 return OPERATOR_CANCELLED;
988         }
989         
990         if (em->selectmode == SCE_SELECT_FACE) {
991                 EDBM_select_flush(em);
992         }
993
994         EDBM_update_generic(em, true, true);
995
996         return OPERATOR_FINISHED;
997 }
998
999 void MESH_OT_edge_split(wmOperatorType *ot)
1000 {
1001         /* identifiers */
1002         ot->name = "Edge Split";
1003         ot->idname = "MESH_OT_edge_split";
1004         ot->description = "Split selected edges so that each neighbor face gets its own copy";
1005         
1006         /* api callbacks */
1007         ot->exec = edbm_edge_split_exec;
1008         ot->poll = ED_operator_editmesh;
1009         
1010         /* flags */
1011         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1012 }
1013
1014 /****************** add duplicate operator ***************/
1015
1016 static int edbm_duplicate_exec(bContext *C, wmOperator *op)
1017 {
1018         Object *ob = CTX_data_edit_object(C);
1019         BMEditMesh *em = BKE_editmesh_from_object(ob);
1020         BMesh *bm = em->bm;
1021         BMOperator bmop;
1022         ListBase bm_selected_store = {NULL, NULL};
1023
1024         /* de-select all would clear otherwise */
1025         SWAP(ListBase, bm->selected, bm_selected_store);
1026
1027         EDBM_op_init(em, &bmop, op, "duplicate geom=%hvef", BM_ELEM_SELECT);
1028         
1029         BMO_op_exec(bm, &bmop);
1030         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1031
1032         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);
1033
1034         /* rebuild editselection */
1035         bm->selected = bm_selected_store;
1036
1037         if (bm->selected.first) {
1038                 BMOpSlot *slot_vert_map_out = BMO_slot_get(bmop.slots_out, "vert_map.out");
1039                 BMOpSlot *slot_edge_map_out = BMO_slot_get(bmop.slots_out, "edge_map.out");
1040                 BMOpSlot *slot_face_map_out = BMO_slot_get(bmop.slots_out, "face_map.out");
1041
1042                 BMO_mesh_selected_remap(bm, slot_vert_map_out, slot_edge_map_out, slot_face_map_out);
1043         }
1044
1045         if (!EDBM_op_finish(em, &bmop, op, true)) {
1046                 return OPERATOR_CANCELLED;
1047         }
1048
1049         EDBM_update_generic(em, true, true);
1050         
1051         return OPERATOR_FINISHED;
1052 }
1053
1054 static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1055 {
1056         WM_cursor_wait(1);
1057         edbm_duplicate_exec(C, op);
1058         WM_cursor_wait(0);
1059         
1060         return OPERATOR_FINISHED;
1061 }
1062
1063 void MESH_OT_duplicate(wmOperatorType *ot)
1064 {
1065         /* identifiers */
1066         ot->name = "Duplicate";
1067         ot->description = "Duplicate selected vertices, edges or faces";
1068         ot->idname = "MESH_OT_duplicate";
1069         
1070         /* api callbacks */
1071         ot->invoke = edbm_duplicate_invoke;
1072         ot->exec = edbm_duplicate_exec;
1073         
1074         ot->poll = ED_operator_editmesh;
1075         
1076         /* to give to transform */
1077         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1078 }
1079
1080 static int edbm_flip_normals_exec(bContext *C, wmOperator *op)
1081 {
1082         Object *obedit = CTX_data_edit_object(C);
1083         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1084         
1085         if (!EDBM_op_callf(em, op, "reverse_faces faces=%hf", BM_ELEM_SELECT))
1086                 return OPERATOR_CANCELLED;
1087         
1088         EDBM_update_generic(em, true, false);
1089
1090         return OPERATOR_FINISHED;
1091 }
1092
1093 void MESH_OT_flip_normals(wmOperatorType *ot)
1094 {
1095         /* identifiers */
1096         ot->name = "Flip Normals";
1097         ot->description = "Flip the direction of selected faces' normals (and of their vertices)";
1098         ot->idname = "MESH_OT_flip_normals";
1099         
1100         /* api callbacks */
1101         ot->exec = edbm_flip_normals_exec;
1102         ot->poll = ED_operator_editmesh;
1103         
1104         /* flags */
1105         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1106 }
1107
1108 /* only accepts 1 selected edge, or 2 selected faces */
1109 static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
1110 {
1111         Object *obedit = CTX_data_edit_object(C);
1112         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1113         BMOperator bmop;
1114         BMEdge *eed;
1115         BMIter iter;
1116         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1117         int tot = 0;
1118
1119         if (em->bm->totedgesel == 0) {
1120                 BKE_report(op->reports, RPT_ERROR, "Select edges or face pairs for edge loops to rotate about");
1121                 return OPERATOR_CANCELLED;
1122         }
1123
1124         /* first see if we have two adjacent faces */
1125         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1126                 BM_elem_flag_disable(eed, BM_ELEM_TAG);
1127                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1128                         BMFace *fa, *fb;
1129                         if (BM_edge_face_pair(eed, &fa, &fb)) {
1130                                 /* if both faces are selected we rotate between them,
1131                                  * otherwise - rotate between 2 unselected - but not mixed */
1132                                 if (BM_elem_flag_test(fa, BM_ELEM_SELECT) == BM_elem_flag_test(fb, BM_ELEM_SELECT)) {
1133                                         BM_elem_flag_enable(eed, BM_ELEM_TAG);
1134                                         tot++;
1135                                 }
1136                         }
1137                 }
1138         }
1139         
1140         /* ok, we don't have two adjacent faces, but we do have two selected ones.
1141          * that's an error condition.*/
1142         if (tot == 0) {
1143                 BKE_report(op->reports, RPT_ERROR, "Could not find any selected edges that can be rotated");
1144                 return OPERATOR_CANCELLED;
1145         }
1146
1147         EDBM_op_init(em, &bmop, op, "rotate_edges edges=%he use_ccw=%b", BM_ELEM_TAG, use_ccw);
1148
1149         /* avoids leaving old verts selected which can be a problem running multiple times,
1150          * since this means the edges become selected around the face which then attempt to rotate */
1151         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_in, "edges", BM_EDGE, BM_ELEM_SELECT, true);
1152
1153         BMO_op_exec(em->bm, &bmop);
1154         /* edges may rotate into hidden vertices, if this does _not_ run we get an ilogical state */
1155         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_HIDDEN, true);
1156         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, true);
1157         EDBM_selectmode_flush(em);
1158
1159         if (!EDBM_op_finish(em, &bmop, op, true)) {
1160                 return OPERATOR_CANCELLED;
1161         }
1162
1163         EDBM_update_generic(em, true, true);
1164
1165         return OPERATOR_FINISHED;
1166 }
1167
1168 void MESH_OT_edge_rotate(wmOperatorType *ot)
1169 {
1170         /* identifiers */
1171         ot->name = "Rotate Selected Edge";
1172         ot->description = "Rotate selected edge or adjoining faces";
1173         ot->idname = "MESH_OT_edge_rotate";
1174
1175         /* api callbacks */
1176         ot->exec = edbm_edge_rotate_selected_exec;
1177         ot->poll = ED_operator_editmesh;
1178
1179         /* flags */
1180         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1181
1182         /* props */
1183         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
1184 }
1185
1186
1187 static int edbm_hide_exec(bContext *C, wmOperator *op)
1188 {
1189         Object *obedit = CTX_data_edit_object(C);
1190         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1191         
1192         EDBM_mesh_hide(em, RNA_boolean_get(op->ptr, "unselected"));
1193
1194         EDBM_update_generic(em, true, false);
1195
1196         return OPERATOR_FINISHED;
1197 }
1198
1199 void MESH_OT_hide(wmOperatorType *ot)
1200 {
1201         /* identifiers */
1202         ot->name = "Hide Selection";
1203         ot->idname = "MESH_OT_hide";
1204         ot->description = "Hide (un)selected vertices, edges or faces";
1205         
1206         /* api callbacks */
1207         ot->exec = edbm_hide_exec;
1208         ot->poll = ED_operator_editmesh;
1209
1210         /* flags */
1211         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1212         
1213         /* props */
1214         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
1215 }
1216
1217 static int edbm_reveal_exec(bContext *C, wmOperator *UNUSED(op))
1218 {
1219         Object *obedit = CTX_data_edit_object(C);
1220         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1221         
1222         EDBM_mesh_reveal(em);
1223
1224         EDBM_update_generic(em, true, false);
1225
1226         return OPERATOR_FINISHED;
1227 }
1228
1229 void MESH_OT_reveal(wmOperatorType *ot)
1230 {
1231         /* identifiers */
1232         ot->name = "Reveal Hidden";
1233         ot->idname = "MESH_OT_reveal";
1234         ot->description = "Reveal all hidden vertices, edges and faces";
1235         
1236         /* api callbacks */
1237         ot->exec = edbm_reveal_exec;
1238         ot->poll = ED_operator_editmesh;
1239         
1240         /* flags */
1241         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1242 }
1243
1244 static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op)
1245 {
1246         Object *obedit = CTX_data_edit_object(C);
1247         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1248         
1249         /* doflip has to do with bmesh_rationalize_normals, it's an internal
1250          * thing */
1251         if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT))
1252                 return OPERATOR_CANCELLED;
1253
1254         if (RNA_boolean_get(op->ptr, "inside"))
1255                 EDBM_op_callf(em, op, "reverse_faces faces=%hf", BM_ELEM_SELECT);
1256
1257         EDBM_update_generic(em, true, false);
1258
1259         return OPERATOR_FINISHED;
1260 }
1261
1262 void MESH_OT_normals_make_consistent(wmOperatorType *ot)
1263 {
1264         /* identifiers */
1265         ot->name = "Make Normals Consistent";
1266         ot->description = "Make face and vertex normals point either outside or inside the mesh";
1267         ot->idname = "MESH_OT_normals_make_consistent";
1268         
1269         /* api callbacks */
1270         ot->exec = edbm_normals_make_consistent_exec;
1271         ot->poll = ED_operator_editmesh;
1272         
1273         /* flags */
1274         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1275         
1276         RNA_def_boolean(ot->srna, "inside", 0, "Inside", "");
1277 }
1278
1279
1280
1281 static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
1282 {
1283         Object *obedit = CTX_data_edit_object(C);
1284         Mesh *me = obedit->data;
1285         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1286         ModifierData *md;
1287         bool mirrx = false, mirry = false, mirrz = false;
1288         int i, repeat;
1289         float clip_dist = 0.0f;
1290         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1291
1292         const bool xaxis = RNA_boolean_get(op->ptr, "xaxis");
1293         const bool yaxis = RNA_boolean_get(op->ptr, "yaxis");
1294         const bool zaxis = RNA_boolean_get(op->ptr, "zaxis");
1295
1296         /* mirror before smooth */
1297         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1298                 EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
1299         }
1300
1301         /* if there is a mirror modifier with clipping, flag the verts that
1302          * are within tolerance of the plane(s) of reflection 
1303          */
1304         for (md = obedit->modifiers.first; md; md = md->next) {
1305                 if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
1306                         MirrorModifierData *mmd = (MirrorModifierData *)md;
1307                 
1308                         if (mmd->flag & MOD_MIR_CLIPPING) {
1309                                 if (mmd->flag & MOD_MIR_AXIS_X)
1310                                         mirrx = true;
1311                                 if (mmd->flag & MOD_MIR_AXIS_Y)
1312                                         mirry = true;
1313                                 if (mmd->flag & MOD_MIR_AXIS_Z)
1314                                         mirrz = true;
1315
1316                                 clip_dist = mmd->tolerance;
1317                         }
1318                 }
1319         }
1320
1321         repeat = RNA_int_get(op->ptr, "repeat");
1322         if (!repeat)
1323                 repeat = 1;
1324         
1325         for (i = 0; i < repeat; i++) {
1326                 if (!EDBM_op_callf(em, op,
1327                                    "smooth_vert verts=%hv mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b clip_dist=%f "
1328                                    "use_axis_x=%b use_axis_y=%b use_axis_z=%b",
1329                                    BM_ELEM_SELECT, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
1330                 {
1331                         return OPERATOR_CANCELLED;
1332                 }
1333         }
1334
1335         /* apply mirror */
1336         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1337                 EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
1338                 EDBM_verts_mirror_cache_end(em);
1339         }
1340
1341         EDBM_update_generic(em, true, false);
1342
1343         return OPERATOR_FINISHED;
1344 }       
1345         
1346 void MESH_OT_vertices_smooth(wmOperatorType *ot)
1347 {
1348         /* identifiers */
1349         ot->name = "Smooth Vertex";
1350         ot->description = "Flatten angles of selected vertices";
1351         ot->idname = "MESH_OT_vertices_smooth";
1352         
1353         /* api callbacks */
1354         ot->exec = edbm_do_smooth_vertex_exec;
1355         ot->poll = ED_operator_editmesh;
1356         
1357         /* flags */
1358         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1359
1360         RNA_def_int(ot->srna, "repeat", 1, 1, 1000, "Number of times to smooth the mesh", "", 1, 100);
1361         RNA_def_boolean(ot->srna, "xaxis", 1, "X-Axis", "Smooth along the X axis");
1362         RNA_def_boolean(ot->srna, "yaxis", 1, "Y-Axis", "Smooth along the Y axis");
1363         RNA_def_boolean(ot->srna, "zaxis", 1, "Z-Axis", "Smooth along the Z axis");
1364 }
1365
1366 static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
1367 {
1368         Object *obedit = CTX_data_edit_object(C);
1369         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1370         Mesh *me = obedit->data;
1371         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1372         bool usex = true, usey = true, usez = true, preserve_volume = true;
1373         int i, repeat;
1374         float lambda_factor;
1375         float lambda_border;
1376         BMIter fiter;
1377         BMFace *f;
1378
1379         /* Check if select faces are triangles  */
1380         BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
1381                 if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1382                         if (f->len > 4) {
1383                                 BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
1384                                 return OPERATOR_CANCELLED;
1385                         }       
1386                 }
1387         }
1388
1389         /* mirror before smooth */
1390         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1391                 EDBM_verts_mirror_cache_begin(em, 0, false, true, use_topology);
1392         }
1393
1394         repeat = RNA_int_get(op->ptr, "repeat");
1395         lambda_factor = RNA_float_get(op->ptr, "lambda_factor");
1396         lambda_border = RNA_float_get(op->ptr, "lambda_border");
1397         usex = RNA_boolean_get(op->ptr, "use_x");
1398         usey = RNA_boolean_get(op->ptr, "use_y");
1399         usez = RNA_boolean_get(op->ptr, "use_z");
1400         preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume");
1401         if (!repeat)
1402                 repeat = 1;
1403         
1404         for (i = 0; i < repeat; i++) {
1405                 if (!EDBM_op_callf(em, op,
1406                                    "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
1407                                    BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
1408                 {
1409                         return OPERATOR_CANCELLED;
1410                 }
1411         }
1412
1413         /* apply mirror */
1414         if (((Mesh *)obedit->data)->editflag & ME_EDIT_MIRROR_X) {
1415                 EDBM_verts_mirror_apply(em, BM_ELEM_SELECT, 0);
1416                 EDBM_verts_mirror_cache_end(em);
1417         }
1418
1419         EDBM_update_generic(em, true, false);
1420
1421         return OPERATOR_FINISHED;
1422 }
1423
1424 void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
1425 {
1426         /* identifiers */
1427         ot->name = "Laplacian Smooth Vertex";
1428         ot->description = "Laplacian smooth of selected vertices";
1429         ot->idname = "MESH_OT_vertices_smooth_laplacian";
1430         
1431         /* api callbacks */
1432         ot->exec = edbm_do_smooth_laplacian_vertex_exec;
1433         ot->poll = ED_operator_editmesh;
1434         
1435         /* flags */
1436         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1437
1438         RNA_def_int(ot->srna, "repeat", 1, 1, 200,
1439                     "Number of iterations to smooth the mesh", "", 1, 200);
1440         RNA_def_float(ot->srna, "lambda_factor", 0.00005f, 0.0000001f, 1000.0f,
1441                       "Lambda factor", "", 0.0000001f, 1000.0f);
1442         RNA_def_float(ot->srna, "lambda_border", 0.00005f, 0.0000001f, 1000.0f,
1443                       "Lambda factor in border", "", 0.0000001f, 1000.0f);
1444         RNA_def_boolean(ot->srna, "use_x", 1, "Smooth X Axis", "Smooth object along X axis");
1445         RNA_def_boolean(ot->srna, "use_y", 1, "Smooth Y Axis", "Smooth object along Y axis");
1446         RNA_def_boolean(ot->srna, "use_z", 1, "Smooth Z Axis", "Smooth object along Z axis");
1447         RNA_def_boolean(ot->srna, "preserve_volume", 1, "Preserve Volume", "Apply volume preservation after smooth");
1448 }
1449
1450 /********************** Smooth/Solid Operators *************************/
1451
1452 static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
1453 {
1454         BMIter iter;
1455         BMFace *efa;
1456
1457         if (em == NULL) return;
1458         
1459         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1460                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1461                         BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth);
1462                 }
1463         }
1464 }
1465
1466 static int edbm_faces_shade_smooth_exec(bContext *C, wmOperator *UNUSED(op))
1467 {
1468         Object *obedit = CTX_data_edit_object(C);
1469         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1470
1471         mesh_set_smooth_faces(em, 1);
1472
1473         EDBM_update_generic(em, false, false);
1474
1475         return OPERATOR_FINISHED;
1476 }
1477
1478 void MESH_OT_faces_shade_smooth(wmOperatorType *ot)
1479 {
1480         /* identifiers */
1481         ot->name = "Shade Smooth";
1482         ot->description = "Display faces smooth (using vertex normals)";
1483         ot->idname = "MESH_OT_faces_shade_smooth";
1484
1485         /* api callbacks */
1486         ot->exec = edbm_faces_shade_smooth_exec;
1487         ot->poll = ED_operator_editmesh;
1488
1489         /* flags */
1490         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1491 }
1492
1493 static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op))
1494 {
1495         Object *obedit = CTX_data_edit_object(C);
1496         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1497
1498         mesh_set_smooth_faces(em, 0);
1499
1500         EDBM_update_generic(em, false, false);
1501
1502         return OPERATOR_FINISHED;
1503 }
1504
1505 void MESH_OT_faces_shade_flat(wmOperatorType *ot)
1506 {
1507         /* identifiers */
1508         ot->name = "Shade Flat";
1509         ot->description = "Display faces flat";
1510         ot->idname = "MESH_OT_faces_shade_flat";
1511
1512         /* api callbacks */
1513         ot->exec = edbm_faces_shade_flat_exec;
1514         ot->poll = ED_operator_editmesh;
1515
1516         /* flags */
1517         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1518 }
1519
1520
1521 /********************** UV/Color Operators *************************/
1522
1523 static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op)
1524 {
1525         Object *ob = CTX_data_edit_object(C);
1526         BMEditMesh *em = BKE_editmesh_from_object(ob);
1527         BMOperator bmop;
1528
1529         /* get the direction from RNA */
1530         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1531
1532         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1533         EDBM_op_init(em, &bmop, op, "rotate_uvs faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
1534
1535         /* execute the operator */
1536         BMO_op_exec(em->bm, &bmop);
1537
1538         /* finish the operator */
1539         if (!EDBM_op_finish(em, &bmop, op, true)) {
1540                 return OPERATOR_CANCELLED;
1541         }
1542
1543         EDBM_update_generic(em, false, false);
1544
1545         return OPERATOR_FINISHED;
1546 }
1547
1548 static int edbm_reverse_uvs_exec(bContext *C, wmOperator *op)
1549 {
1550         Object *ob = CTX_data_edit_object(C);
1551         BMEditMesh *em = BKE_editmesh_from_object(ob);
1552         BMOperator bmop;
1553
1554         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1555         EDBM_op_init(em, &bmop, op, "reverse_uvs faces=%hf", BM_ELEM_SELECT);
1556
1557         /* execute the operator */
1558         BMO_op_exec(em->bm, &bmop);
1559
1560         /* finish the operator */
1561         if (!EDBM_op_finish(em, &bmop, op, true)) {
1562                 return OPERATOR_CANCELLED;
1563         }
1564
1565         EDBM_update_generic(em, false, false);
1566
1567         return OPERATOR_FINISHED;
1568 }
1569
1570 static int edbm_rotate_colors_exec(bContext *C, wmOperator *op)
1571 {
1572         Object *ob = CTX_data_edit_object(C);
1573         BMEditMesh *em = BKE_editmesh_from_object(ob);
1574         BMOperator bmop;
1575
1576         /* get the direction from RNA */
1577         const bool use_ccw = RNA_boolean_get(op->ptr, "use_ccw");
1578
1579         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1580         EDBM_op_init(em, &bmop, op, "rotate_colors faces=%hf use_ccw=%b", BM_ELEM_SELECT, use_ccw);
1581
1582         /* execute the operator */
1583         BMO_op_exec(em->bm, &bmop);
1584
1585         /* finish the operator */
1586         if (!EDBM_op_finish(em, &bmop, op, true)) {
1587                 return OPERATOR_CANCELLED;
1588         }
1589
1590         /* dependencies graph and notification stuff */
1591         EDBM_update_generic(em, false, false);
1592
1593         return OPERATOR_FINISHED;
1594 }
1595
1596
1597 static int edbm_reverse_colors_exec(bContext *C, wmOperator *op)
1598 {
1599         Object *ob = CTX_data_edit_object(C);
1600         BMEditMesh *em = BKE_editmesh_from_object(ob);
1601         BMOperator bmop;
1602
1603         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
1604         EDBM_op_init(em, &bmop, op, "reverse_colors faces=%hf", BM_ELEM_SELECT);
1605
1606         /* execute the operator */
1607         BMO_op_exec(em->bm, &bmop);
1608
1609         /* finish the operator */
1610         if (!EDBM_op_finish(em, &bmop, op, true)) {
1611                 return OPERATOR_CANCELLED;
1612         }
1613
1614         EDBM_update_generic(em, false, false);
1615
1616         return OPERATOR_FINISHED;
1617 }
1618
1619 void MESH_OT_uvs_rotate(wmOperatorType *ot)
1620 {
1621         /* identifiers */
1622         ot->name = "Rotate UVs";
1623         ot->idname = "MESH_OT_uvs_rotate";
1624         ot->description = "Rotate UV coordinates inside faces";
1625
1626         /* api callbacks */
1627         ot->exec = edbm_rotate_uvs_exec;
1628         ot->poll = ED_operator_editmesh;
1629
1630         /* flags */
1631         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1632
1633         /* props */
1634         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
1635 }
1636
1637 void MESH_OT_uvs_reverse(wmOperatorType *ot)
1638 {
1639         /* identifiers */
1640         ot->name = "Reverse UVs";
1641         ot->idname = "MESH_OT_uvs_reverse";
1642         ot->description = "Flip direction of UV coordinates inside faces";
1643
1644         /* api callbacks */
1645         ot->exec = edbm_reverse_uvs_exec;
1646         ot->poll = ED_operator_editmesh;
1647
1648         /* flags */
1649         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1650
1651         /* props */
1652         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror UVs around");
1653 }
1654
1655 void MESH_OT_colors_rotate(wmOperatorType *ot)
1656 {
1657         /* identifiers */
1658         ot->name = "Rotate Colors";
1659         ot->idname = "MESH_OT_colors_rotate";
1660         ot->description = "Rotate vertex colors inside faces";
1661
1662         /* api callbacks */
1663         ot->exec = edbm_rotate_colors_exec;
1664         ot->poll = ED_operator_editmesh;
1665
1666         /* flags */
1667         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1668
1669         /* props */
1670         RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
1671 }
1672
1673 void MESH_OT_colors_reverse(wmOperatorType *ot)
1674 {
1675         /* identifiers */
1676         ot->name = "Reverse Colors";
1677         ot->idname = "MESH_OT_colors_reverse";
1678         ot->description = "Flip direction of vertex colors inside faces";
1679
1680         /* api callbacks */
1681         ot->exec = edbm_reverse_colors_exec;
1682         ot->poll = ED_operator_editmesh;
1683
1684         /* flags */
1685         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1686
1687         /* props */
1688         //RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around");
1689 }
1690
1691
1692 static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use_uvmerge, wmOperator *wmop)
1693 {
1694         BMVert *mergevert;
1695         BMEditSelection *ese;
1696
1697         /* operator could be called directly from shortcut or python,
1698          * so do extra check for data here
1699          */
1700
1701         /* do sanity check in mergemenu in edit.c ?*/
1702         if (use_first == false) {
1703                 if (!em->bm->selected.last || ((BMEditSelection *)em->bm->selected.last)->htype != BM_VERT)
1704                         return false;
1705
1706                 ese = em->bm->selected.last;
1707                 mergevert = (BMVert *)ese->ele;
1708         }
1709         else {
1710                 if (!em->bm->selected.first || ((BMEditSelection *)em->bm->selected.first)->htype != BM_VERT)
1711                         return false;
1712
1713                 ese = em->bm->selected.first;
1714                 mergevert = (BMVert *)ese->ele;
1715         }
1716
1717         if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT))
1718                 return false;
1719         
1720         if (use_uvmerge) {
1721                 if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert))
1722                         return false;
1723         }
1724
1725         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, mergevert->co))
1726                 return false;
1727
1728         return true;
1729 }
1730
1731 static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
1732                          const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
1733 {
1734         BMIter iter;
1735         BMVert *v;
1736         float co[3], cent[3] = {0.0f, 0.0f, 0.0f};
1737         const float *vco = NULL;
1738
1739         if (use_cursor) {
1740                 vco = ED_view3d_cursor3d_get(scene, v3d);
1741                 copy_v3_v3(co, vco);
1742                 mul_m4_v3(ob->imat, co);
1743         }
1744         else {
1745                 float fac;
1746                 int i = 0;
1747                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
1748                         if (!BM_elem_flag_test(v, BM_ELEM_SELECT))
1749                                 continue;
1750                         add_v3_v3(cent, v->co);
1751                         i++;
1752                 }
1753                 
1754                 if (!i)
1755                         return false;
1756
1757                 fac = 1.0f / (float)i;
1758                 mul_v3_fl(cent, fac);
1759                 copy_v3_v3(co, cent);
1760                 vco = co;
1761         }
1762
1763         if (!vco)
1764                 return false;
1765         
1766         if (use_uvmerge) {
1767                 if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT))
1768                         return false;
1769         }
1770
1771         if (!EDBM_op_callf(em, wmop, "pointmerge verts=%hv merge_co=%v", BM_ELEM_SELECT, co))
1772                 return false;
1773
1774         return true;
1775 }
1776
1777 static int edbm_merge_exec(bContext *C, wmOperator *op)
1778 {
1779         Scene *scene = CTX_data_scene(C);
1780         View3D *v3d = CTX_wm_view3d(C);
1781         Object *obedit = CTX_data_edit_object(C);
1782         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1783         const int type = RNA_enum_get(op->ptr, "type");
1784         const bool uvs = RNA_boolean_get(op->ptr, "uvs");
1785         bool ok = false;
1786
1787         switch (type) {
1788                 case 3:
1789                         ok = merge_target(em, scene, v3d, obedit, false, uvs, op);
1790                         break;
1791                 case 4:
1792                         ok = merge_target(em, scene, v3d, obedit, true, uvs, op);
1793                         break;
1794                 case 1:
1795                         ok = merge_firstlast(em, false, uvs, op);
1796                         break;
1797                 case 6:
1798                         ok = merge_firstlast(em, true, uvs, op);
1799                         break;
1800                 case 5:
1801                         ok = true;
1802                         if (!EDBM_op_callf(em, op, "collapse edges=%he", BM_ELEM_SELECT))
1803                                 ok = false;
1804                         break;
1805                 default:
1806                         BLI_assert(0);
1807                         break;
1808         }
1809
1810         if (!ok) {
1811                 return OPERATOR_CANCELLED;
1812         }
1813
1814         EDBM_update_generic(em, true, true);
1815
1816         return OPERATOR_FINISHED;
1817 }
1818
1819 static EnumPropertyItem merge_type_items[] = {
1820         {6, "FIRST", 0, "At First", ""},
1821         {1, "LAST", 0, "At Last", ""},
1822         {3, "CENTER", 0, "At Center", ""},
1823         {4, "CURSOR", 0, "At Cursor", ""},
1824         {5, "COLLAPSE", 0, "Collapse", ""},
1825         {0, NULL, 0, NULL, NULL}
1826 };
1827
1828 static EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
1829 {       
1830         Object *obedit;
1831         EnumPropertyItem *item = NULL;
1832         int totitem = 0;
1833         
1834         if (!C) /* needed for docs */
1835                 return merge_type_items;
1836         
1837         obedit = CTX_data_edit_object(C);
1838         if (obedit && obedit->type == OB_MESH) {
1839                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
1840
1841                 if (em->selectmode & SCE_SELECT_VERTEX) {
1842                         if (em->bm->selected.first && em->bm->selected.last &&
1843                             ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT &&
1844                             ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT)
1845                         {
1846                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 6);
1847                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 1);
1848                         }
1849                         else if (em->bm->selected.first && ((BMEditSelection *)em->bm->selected.first)->htype == BM_VERT) {
1850                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 6);
1851                         }
1852                         else if (em->bm->selected.last && ((BMEditSelection *)em->bm->selected.last)->htype == BM_VERT) {
1853                                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 1);
1854                         }
1855                 }
1856
1857                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 3);
1858                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 4);
1859                 RNA_enum_items_add_value(&item, &totitem, merge_type_items, 5);
1860                 RNA_enum_item_end(&item, &totitem);
1861
1862                 *r_free = true;
1863
1864                 return item;
1865         }
1866         
1867         return NULL;
1868 }
1869
1870 void MESH_OT_merge(wmOperatorType *ot)
1871 {
1872         /* identifiers */
1873         ot->name = "Merge";
1874         ot->description = "Merge selected vertices";
1875         ot->idname = "MESH_OT_merge";
1876
1877         /* api callbacks */
1878         ot->exec = edbm_merge_exec;
1879         ot->invoke = WM_menu_invoke;
1880         ot->poll = ED_operator_editmesh;
1881
1882         /* flags */
1883         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1884
1885         /* properties */
1886         ot->prop = RNA_def_enum(ot->srna, "type", merge_type_items, 3, "Type", "Merge method to use");
1887         RNA_def_enum_funcs(ot->prop, merge_type_itemf);
1888         RNA_def_boolean(ot->srna, "uvs", 0, "UVs", "Move UVs according to merge");
1889 }
1890
1891
1892 static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
1893 {
1894         Object *obedit = CTX_data_edit_object(C);
1895         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1896         BMOperator bmop;
1897         const float threshold = RNA_float_get(op->ptr, "threshold");
1898         const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
1899         const int totvert_orig = em->bm->totvert;
1900         int count;
1901         char htype_select;
1902
1903         /* avoid loosing selection state (select -> tags) */
1904         if      (em->selectmode & SCE_SELECT_VERTEX) htype_select = BM_VERT;
1905         else if (em->selectmode & SCE_SELECT_EDGE)   htype_select = BM_EDGE;
1906         else                                         htype_select = BM_FACE;
1907
1908         /* store selection as tags */
1909         BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_TAG, true, true, BM_ELEM_SELECT);
1910
1911
1912         if (use_unselected) {
1913                 EDBM_op_init(em, &bmop, op,
1914                              "automerge verts=%hv dist=%f",
1915                              BM_ELEM_SELECT, threshold);
1916                 BMO_op_exec(em->bm, &bmop);
1917
1918                 if (!EDBM_op_finish(em, &bmop, op, true)) {
1919                         return OPERATOR_CANCELLED;
1920                 }
1921         }
1922         else {
1923                 EDBM_op_init(em, &bmop, op,
1924                              "find_doubles verts=%hv dist=%f",
1925                              BM_ELEM_SELECT, threshold);
1926                 BMO_op_exec(em->bm, &bmop);
1927
1928                 if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) {
1929                         BMO_op_finish(em->bm, &bmop);
1930                         return OPERATOR_CANCELLED;
1931                 }
1932
1933                 if (!EDBM_op_finish(em, &bmop, op, true)) {
1934                         return OPERATOR_CANCELLED;
1935                 }
1936         }
1937         
1938         count = totvert_orig - em->bm->totvert;
1939         BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count);
1940
1941         /* restore selection from tags */
1942         BM_mesh_elem_hflag_enable_test(em->bm, htype_select, BM_ELEM_SELECT, true, true, BM_ELEM_TAG);
1943         EDBM_selectmode_flush(em);
1944
1945         EDBM_update_generic(em, true, true);
1946
1947         return OPERATOR_FINISHED;
1948 }
1949
1950 void MESH_OT_remove_doubles(wmOperatorType *ot)
1951 {
1952         /* identifiers */
1953         ot->name = "Remove Doubles";
1954         ot->description = "Remove duplicate vertices";
1955         ot->idname = "MESH_OT_remove_doubles";
1956
1957         /* api callbacks */
1958         ot->exec = edbm_remove_doubles_exec;
1959         ot->poll = ED_operator_editmesh;
1960
1961         /* flags */
1962         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1963
1964         RNA_def_float(ot->srna, "threshold", 0.0001f, 0.000001f, 50.0f,  "Merge Distance",
1965                       "Minimum distance between elements to merge", 0.00001, 10.0);
1966         RNA_def_boolean(ot->srna, "use_unselected", 0, "Unselected", "Merge selected to other unselected vertices");
1967 }
1968
1969
1970 /************************ Shape Operators *************************/
1971
1972 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
1973 static void shape_propagate(BMEditMesh *em, wmOperator *op)
1974 {
1975         BMIter iter;
1976         BMVert *eve = NULL;
1977         float *co;
1978         int i, totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
1979
1980         if (!CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY)) {
1981                 BKE_report(op->reports, RPT_ERROR, "Mesh does not have shape keys");
1982                 return;
1983         }
1984         
1985         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1986                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
1987                         continue;
1988
1989                 for (i = 0; i < totshape; i++) {
1990                         co = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, i);
1991                         copy_v3_v3(co, eve->co);
1992                 }
1993         }
1994
1995 #if 0
1996         //TAG Mesh Objects that share this data
1997         for (base = scene->base.first; base; base = base->next) {
1998                 if (base->object && base->object->data == me) {
1999                         DAG_id_tag_update(&base->object->id, OB_RECALC_DATA);
2000                 }
2001         }
2002 #endif
2003 }
2004
2005
2006 static int edbm_shape_propagate_to_all_exec(bContext *C, wmOperator *op)
2007 {
2008         Object *obedit = CTX_data_edit_object(C);
2009         Mesh *me = obedit->data;
2010         BMEditMesh *em = me->edit_btmesh;
2011
2012         shape_propagate(em, op);
2013
2014         EDBM_update_generic(em, false, false);
2015
2016         return OPERATOR_FINISHED;
2017 }
2018
2019
2020 void MESH_OT_shape_propagate_to_all(wmOperatorType *ot)
2021 {
2022         /* identifiers */
2023         ot->name = "Shape Propagate";
2024         ot->description = "Apply selected vertex locations to all other shape keys";
2025         ot->idname = "MESH_OT_shape_propagate_to_all";
2026
2027         /* api callbacks */
2028         ot->exec = edbm_shape_propagate_to_all_exec;
2029         ot->poll = ED_operator_editmesh;
2030
2031         /* flags */
2032         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2033 }
2034
2035 /* BMESH_TODO this should be properly encapsulated in a bmop.  but later.*/
2036 static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
2037 {
2038         Object *obedit = CTX_data_edit_object(C);
2039         Mesh *me = obedit->data;
2040         Key *key = me->key;
2041         KeyBlock *kb = NULL;
2042         BMEditMesh *em = me->edit_btmesh;
2043         BMVert *eve;
2044         BMIter iter;
2045         float co[3], *sco;
2046         int totshape;
2047
2048         const float blend = RNA_float_get(op->ptr, "blend");
2049         const int shape = RNA_enum_get(op->ptr, "shape");
2050         const bool use_add = RNA_boolean_get(op->ptr, "add");
2051
2052         /* sanity check */
2053         totshape = CustomData_number_of_layers(&em->bm->vdata, CD_SHAPEKEY);
2054         if (totshape == 0 || shape < 0 || shape >= totshape)
2055                 return OPERATOR_CANCELLED;
2056
2057         /* get shape key - needed for finding reference shape (for add mode only) */
2058         if (key) {
2059                 kb = BLI_findlink(&key->block, shape);
2060         }
2061         
2062         /* perform blending on selected vertices*/
2063         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2064                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
2065                         continue;
2066                 
2067                 /* get coordinates of shapekey we're blending from */
2068                 sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape);
2069                 copy_v3_v3(co, sco);
2070                 
2071                 if (use_add) {
2072                         /* in add mode, we add relative shape key offset */
2073                         if (kb) {
2074                                 float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative);
2075                                 sub_v3_v3v3(co, co, rco);
2076                         }
2077                         
2078                         madd_v3_v3fl(eve->co, co, blend);
2079                 }
2080                 else {
2081                         /* in blend mode, we interpolate to the shape key */
2082                         interp_v3_v3v3(eve->co, eve->co, co, blend);
2083                 }
2084         }
2085
2086         EDBM_update_generic(em, true, false);
2087
2088         return OPERATOR_FINISHED;
2089 }
2090
2091 static EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr),  PropertyRNA *UNUSED(prop), bool *r_free)
2092 {       
2093         Object *obedit = CTX_data_edit_object(C);
2094         BMEditMesh *em;
2095         EnumPropertyItem *item = NULL;
2096         int totitem = 0;
2097
2098         if ((obedit && obedit->type == OB_MESH) &&
2099             (em = BKE_editmesh_from_object(obedit)) &&
2100             CustomData_has_layer(&em->bm->vdata, CD_SHAPEKEY))
2101         {
2102                 EnumPropertyItem tmp = {0, "", 0, "", ""};
2103                 int a;
2104
2105                 for (a = 0; a < em->bm->vdata.totlayer; a++) {
2106                         if (em->bm->vdata.layers[a].type != CD_SHAPEKEY)
2107                                 continue;
2108
2109                         tmp.value = totitem;
2110                         tmp.identifier = em->bm->vdata.layers[a].name;
2111                         tmp.name = em->bm->vdata.layers[a].name;
2112                         /* RNA_enum_item_add sets totitem itself! */
2113                         RNA_enum_item_add(&item, &totitem, &tmp);
2114                 }
2115         }
2116
2117         RNA_enum_item_end(&item, &totitem);
2118         *r_free = true;
2119
2120         return item;
2121 }
2122
2123 static void edbm_blend_from_shape_ui(bContext *C, wmOperator *op)
2124 {
2125         uiLayout *layout = op->layout;
2126         PointerRNA ptr;
2127         Object *obedit = CTX_data_edit_object(C);
2128         Mesh *me = obedit->data;
2129         PointerRNA ptr_key;
2130
2131         RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr);
2132         RNA_id_pointer_create((ID *)me->key, &ptr_key);
2133
2134         uiItemPointerR(layout, &ptr, "shape", &ptr_key, "key_blocks", "", ICON_SHAPEKEY_DATA);
2135         uiItemR(layout, &ptr, "blend", 0, NULL, ICON_NONE);
2136         uiItemR(layout, &ptr, "add", 0, NULL, ICON_NONE);
2137 }
2138
2139 void MESH_OT_blend_from_shape(wmOperatorType *ot)
2140 {
2141         PropertyRNA *prop;
2142
2143         /* identifiers */
2144         ot->name = "Blend From Shape";
2145         ot->description = "Blend in shape from a shape key";
2146         ot->idname = "MESH_OT_blend_from_shape";
2147
2148         /* api callbacks */
2149         ot->exec = edbm_blend_from_shape_exec;
2150 //      ot->invoke = WM_operator_props_popup_call;  /* disable because search popup closes too easily */
2151         ot->ui = edbm_blend_from_shape_ui;
2152         ot->poll = ED_operator_editmesh;
2153
2154         /* flags */
2155         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2156
2157         /* properties */
2158         prop = RNA_def_enum(ot->srna, "shape", DummyRNA_NULL_items, 0, "Shape", "Shape key to use for blending");
2159         RNA_def_enum_funcs(prop, shape_itemf);
2160         RNA_def_float(ot->srna, "blend", 1.0f, -FLT_MAX, FLT_MAX, "Blend", "Blending factor", -2.0f, 2.0f);
2161         RNA_def_boolean(ot->srna, "add", 1, "Add", "Add rather than blend between shapes");
2162 }
2163
2164 static int edbm_solidify_exec(bContext *C, wmOperator *op)
2165 {
2166         Object *obedit = CTX_data_edit_object(C);
2167         Mesh *me = obedit->data;
2168         BMEditMesh *em = me->edit_btmesh;
2169         BMesh *bm = em->bm;
2170         BMOperator bmop;
2171
2172         const float thickness = RNA_float_get(op->ptr, "thickness");
2173
2174         if (!EDBM_op_init(em, &bmop, op, "solidify geom=%hf thickness=%f", BM_ELEM_SELECT, thickness)) {
2175                 return OPERATOR_CANCELLED;
2176         }
2177
2178         /* deselect only the faces in the region to be solidified (leave wire
2179          * edges and loose verts selected, as there will be no corresponding
2180          * geometry selected below) */
2181         BMO_slot_buffer_hflag_disable(bm, bmop.slots_in, "geom", BM_FACE, BM_ELEM_SELECT, true);
2182
2183         /* run the solidify operator */
2184         BMO_op_exec(bm, &bmop);
2185
2186         /* select the newly generated faces */
2187         BMO_slot_buffer_hflag_enable(bm, bmop.slots_out, "geom.out", BM_FACE, BM_ELEM_SELECT, true);
2188
2189         if (!EDBM_op_finish(em, &bmop, op, true)) {
2190                 return OPERATOR_CANCELLED;
2191         }
2192
2193         EDBM_update_generic(em, true, true);
2194
2195         return OPERATOR_FINISHED;
2196 }
2197
2198
2199 void MESH_OT_solidify(wmOperatorType *ot)
2200 {
2201         PropertyRNA *prop;
2202         /* identifiers */
2203         ot->name = "Solidify";
2204         ot->description = "Create a solid skin by extruding, compensating for sharp angles";
2205         ot->idname = "MESH_OT_solidify";
2206
2207         /* api callbacks */
2208         ot->exec = edbm_solidify_exec;
2209         ot->poll = ED_operator_editmesh;
2210
2211         /* flags */
2212         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2213
2214         prop = RNA_def_float(ot->srna, "thickness", 0.01f, -FLT_MAX, FLT_MAX, "thickness", "", -10.0f, 10.0f);
2215         RNA_def_property_ui_range(prop, -10, 10, 0.1, 4);
2216 }
2217
2218 /* ******************************************************************** */
2219 /* Knife Subdivide Tool.  Subdivides edges intersected by a mouse trail
2220  * drawn by user.
2221  *
2222  * Currently mapped to KKey when in MeshEdit mode.
2223  * Usage:
2224  * - Hit Shift K, Select Centers or Exact
2225  * - Hold LMB down to draw path, hit RETKEY.
2226  * - ESC cancels as expected.
2227  *
2228  * Contributed by Robert Wenzlaff (Det. Thorn).
2229  *
2230  * 2.5 Revamp:
2231  *  - non modal (no menu before cutting)
2232  *  - exit on mouse release
2233  *  - polygon/segment drawing can become handled by WM cb later
2234  *
2235  * bmesh port version
2236  */
2237
2238 #define KNIFE_EXACT     1
2239 #define KNIFE_MIDPOINT  2
2240 #define KNIFE_MULTICUT  3
2241
2242 static EnumPropertyItem knife_items[] = {
2243         {KNIFE_EXACT, "EXACT", 0, "Exact", ""},
2244         {KNIFE_MIDPOINT, "MIDPOINTS", 0, "Midpoints", ""},
2245         {KNIFE_MULTICUT, "MULTICUT", 0, "Multicut", ""},
2246         {0, NULL, 0, NULL, NULL}
2247 };
2248
2249 /* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */
2250
2251 static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
2252                                float (*mouse_path)[2], int len, char mode, int *isected)
2253 {
2254 #define MAXSLOPE 100000
2255         float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max;
2256         float y2min, dist, lastdist = 0, xdiff2, xdiff1;
2257         float m1, b1, m2, b2, x21, x22, y21, y22, xi;
2258         float yi, x1min, x1max, y1max, y1min, perc = 0;
2259         float threshold = 0.0;
2260         int i;
2261         
2262         //threshold = 0.000001; /* tolerance for vertex intersection */
2263         // XXX threshold = scene->toolsettings->select_thresh / 100;
2264         
2265         /* Get screen coords of verts */
2266         x21 = sco_a[0];
2267         y21 = sco_a[1];
2268         
2269         x22 = sco_b[0];
2270         y22 = sco_b[1];
2271         
2272         xdiff2 = (x22 - x21);
2273         if (xdiff2) {
2274                 m2 = (y22 - y21) / xdiff2;
2275                 b2 = ((x22 * y21) - (x21 * y22)) / xdiff2;
2276         }
2277         else {
2278                 m2 = MAXSLOPE;  /* Verticle slope  */
2279                 b2 = x22;
2280         }
2281
2282         *isected = 0;
2283
2284         /* check for _exact_ vertex intersection first */
2285         if (mode != KNIFE_MULTICUT) {
2286                 for (i = 0; i < len; i++) {
2287                         if (i > 0) {
2288                                 x11 = x12;
2289                                 y11 = y12;
2290                         }
2291                         else {
2292                                 x11 = mouse_path[i][0];
2293                                 y11 = mouse_path[i][1];
2294                         }
2295                         x12 = mouse_path[i][0];
2296                         y12 = mouse_path[i][1];
2297                         
2298                         /* test e->v1 */
2299                         if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) {
2300                                 perc = 0;
2301                                 *isected = 1;
2302                                 return perc;
2303                         }
2304                         /* test e->v2 */
2305                         else if ((x11 == x22 && y11 == y22) || (x12 == x22 && y12 == y22)) {
2306                                 perc = 0;
2307                                 *isected = 2;
2308                                 return perc;
2309                         }
2310                 }
2311         }
2312         
2313         /* now check for edge intersect (may produce vertex intersection as well) */
2314         for (i = 0; i < len; i++) {
2315                 if (i > 0) {
2316                         x11 = x12;
2317                         y11 = y12;
2318                 }
2319                 else {
2320                         x11 = mouse_path[i][0];
2321                         y11 = mouse_path[i][1];
2322                 }
2323                 x12 = mouse_path[i][0];
2324                 y12 = mouse_path[i][1];
2325                 
2326                 /* Perp. Distance from point to line */
2327                 if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2);  /* /sqrt(m2 * m2 + 1); Only looking for */
2328                 /* change in sign.  Skip extra math */
2329                 else dist = x22 - x12;
2330                 
2331                 if (i == 0) lastdist = dist;
2332                 
2333                 /* if dist changes sign, and intersect point in edge's Bound Box */
2334                 if ((lastdist * dist) <= 0) {
2335                         xdiff1 = (x12 - x11); /* Equation of line between last 2 points */
2336                         if (xdiff1) {
2337                                 m1 = (y12 - y11) / xdiff1;
2338                                 b1 = ((x12 * y11) - (x11 * y12)) / xdiff1;
2339                         }
2340                         else {
2341                                 m1 = MAXSLOPE;
2342                                 b1 = x12;
2343                         }
2344                         x2max = max_ff(x21, x22) + 0.001f; /* prevent missed edges   */
2345                         x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */
2346                         y2max = max_ff(y21, y22) + 0.001f;
2347                         y2min = min_ff(y21, y22) - 0.001f;
2348                         
2349                         /* Found an intersect,  calc intersect point */
2350                         if (m1 == m2) { /* co-incident lines */
2351                                 /* cut at 50% of overlap area */
2352                                 x1max = max_ff(x11, x12);
2353                                 x1min = min_ff(x11, x12);
2354                                 xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f;
2355                                 
2356                                 y1max = max_ff(y11, y12);
2357                                 y1min = min_ff(y11, y12);
2358                                 yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f;
2359                         }
2360                         else if (m2 == MAXSLOPE) {
2361                                 xi = x22;
2362                                 yi = m1 * x22 + b1;
2363                         }
2364                         else if (m1 == MAXSLOPE) {
2365                                 xi = x12;
2366                                 yi = m2 * x12 + b2;
2367                         }
2368                         else {
2369                                 xi = (b1 - b2) / (m2 - m1);
2370                                 yi = (b1 * m2 - m1 * b2) / (m2 - m1);
2371                         }
2372                         
2373                         /* Intersect inside bounding box of edge?*/
2374                         if ((xi >= x2min) && (xi <= x2max) && (yi <= y2max) && (yi >= y2min)) {
2375                                 /* test for vertex intersect that may be 'close enough'*/
2376                                 if (mode != KNIFE_MULTICUT) {
2377                                         if (xi <= (x21 + threshold) && xi >= (x21 - threshold)) {
2378                                                 if (yi <= (y21 + threshold) && yi >= (y21 - threshold)) {
2379                                                         *isected = 1;
2380                                                         perc = 0;
2381                                                         break;
2382                                                 }
2383                                         }
2384                                         if (xi <= (x22 + threshold) && xi >= (x22 - threshold)) {
2385                                                 if (yi <= (y22 + threshold) && yi >= (y22 - threshold)) {
2386                                                         *isected = 2;
2387                                                         perc = 0;
2388                                                         break;
2389                                                 }
2390                                         }
2391                                 }
2392                                 if ((m2 <= 1.0f) && (m2 >= -1.0f)) perc = (xi - x21) / (x22 - x21);
2393                                 else perc = (yi - y21) / (y22 - y21);  /* lower slope more accurate */
2394                                 //isect = 32768.0 * (perc + 0.0000153); /* Percentage in 1 / 32768ths */
2395                                 
2396                                 break;
2397                         }
2398                 }
2399                 lastdist = dist;
2400         }
2401         return perc;
2402 }
2403
2404 #define ELE_EDGE_CUT 1
2405
2406 static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
2407 {
2408         Object *obedit = CTX_data_edit_object(C);
2409         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2410         BMesh *bm = em->bm;
2411         ARegion *ar = CTX_wm_region(C);
2412         BMVert *bv;
2413         BMIter iter;
2414         BMEdge *be;
2415         BMOperator bmop;
2416         float isect = 0.0f;
2417         int len = 0, isected, i;
2418         short numcuts = 1;
2419         const short mode = RNA_int_get(op->ptr, "type");
2420         BMOpSlot *slot_edge_percents;
2421
2422         /* allocd vars */
2423         float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2];
2424         
2425         /* edit-object needed for matrix, and ar->regiondata for projections to work */
2426         if (ELEM3(NULL, obedit, ar, ar->regiondata))
2427                 return OPERATOR_CANCELLED;
2428         
2429         if (bm->totvertsel < 2) {
2430                 BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on");
2431                 return OPERATOR_CANCELLED;
2432         }
2433
2434         len = RNA_collection_length(op->ptr, "path");
2435
2436         if (len < 2) {
2437                 BKE_report(op->reports, RPT_ERROR, "Mouse path too short");
2438                 return OPERATOR_CANCELLED;
2439         }
2440
2441         mouse_path = MEM_mallocN(len * sizeof(*mouse_path), __func__);
2442
2443         /* get the cut curve */
2444         RNA_BEGIN (op->ptr, itemptr, "path")
2445         {
2446                 RNA_float_get_array(&itemptr, "loc", (float *)&mouse_path[len]);
2447         }
2448         RNA_END;
2449
2450         /* for ED_view3d_project_float_object */
2451         ED_view3d_init_mats_rv3d(obedit, ar->regiondata);
2452
2453         /* TODO, investigate using index lookup for screen_vert_coords() rather then a hash table */
2454
2455         /* the floating point coordinates of verts in screen space will be stored in a hash table according to the vertices pointer */
2456         screen_vert_coords = sco = MEM_mallocN(bm->totvert * sizeof(float) * 2, __func__);
2457
2458         BM_ITER_MESH_INDEX (bv, &iter, bm, BM_VERTS_OF_MESH, i) {
2459                 if (ED_view3d_project_float_object(ar, bv->co, *sco, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) {
2460                         copy_v2_fl(*sco, FLT_MAX);  /* set error value */
2461                 }
2462                 BM_elem_index_set(bv, i); /* set_ok */
2463                 sco++;
2464
2465         }
2466         bm->elem_index_dirty &= ~BM_VERT; /* clear dirty flag */
2467
2468         if (!EDBM_op_init(em, &bmop, op, "subdivide_edges")) {
2469                 MEM_freeN(mouse_path);
2470                 MEM_freeN(screen_vert_coords);
2471                 return OPERATOR_CANCELLED;
2472         }
2473
2474         /* store percentage of edge cut for KNIFE_EXACT here.*/
2475         slot_edge_percents = BMO_slot_get(bmop.slots_in, "edge_percents");
2476         BM_ITER_MESH (be, &iter, bm, BM_EDGES_OF_MESH) {
2477                 bool is_cut = false;
2478                 if (BM_elem_flag_test(be, BM_ELEM_SELECT)) {
2479                         const float *sco_a = screen_vert_coords[BM_elem_index_get(be->v1)];
2480                         const float *sco_b = screen_vert_coords[BM_elem_index_get(be->v2)];
2481
2482                         /* check for error value (vert cant be projected) */
2483                         if ((sco_a[0] != FLT_MAX) && (sco_b[0] != FLT_MAX)) {
2484                                 isect = bm_edge_seg_isect(sco_a, sco_b, mouse_path, len, mode, &isected);
2485
2486                                 if (isect != 0.0f) {
2487                                         if (mode != KNIFE_MULTICUT && mode != KNIFE_MIDPOINT) {
2488                                                 BMO_slot_map_float_insert(&bmop, slot_edge_percents, be, isect);
2489                                         }
2490                                 }
2491                         }
2492                 }
2493
2494                 BMO_elem_flag_set(bm, be, ELE_EDGE_CUT, is_cut);
2495         }
2496
2497
2498         /* free all allocs */
2499         MEM_freeN(screen_vert_coords);
2500         MEM_freeN(mouse_path);
2501
2502
2503         BMO_slot_buffer_from_enabled_flag(bm, &bmop, bmop.slots_in, "edges", BM_EDGE, ELE_EDGE_CUT);
2504
2505         if (mode == KNIFE_MIDPOINT) numcuts = 1;
2506         BMO_slot_int_set(bmop.slots_in, "cuts", numcuts);
2507
2508         BMO_slot_int_set(bmop.slots_in, "quad_corner_type", SUBD_STRAIGHT_CUT);
2509         BMO_slot_bool_set(bmop.slots_in, "use_single_edge", false);
2510         BMO_slot_bool_set(bmop.slots_in, "use_grid_fill", false);
2511
2512         BMO_slot_float_set(bmop.slots_in, "radius", 0);
2513         
2514         BMO_op_exec(bm, &bmop);
2515         if (!EDBM_op_finish(em, &bmop, op, true)) {
2516                 return OPERATOR_CANCELLED;
2517         }
2518
2519         EDBM_update_generic(em, true, true);
2520
2521         return OPERATOR_FINISHED;
2522 }
2523
2524 #undef ELE_EDGE_CUT
2525
2526 void MESH_OT_knife_cut(wmOperatorType *ot)
2527 {
2528         PropertyRNA *prop;
2529         
2530         ot->name = "Knife Cut";
2531         ot->description = "Cut selected edges and faces into parts";
2532         ot->idname = "MESH_OT_knife_cut";
2533         
2534         ot->invoke = WM_gesture_lines_invoke;
2535         ot->modal = WM_gesture_lines_modal;
2536         ot->exec = edbm_knife_cut_exec;
2537         
2538         ot->poll = EDBM_view3d_poll;
2539         
2540         /* flags */
2541         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2542         
2543         RNA_def_enum(ot->srna, "type", knife_items, KNIFE_EXACT, "Type", "");
2544         prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2545         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2546         
2547         /* internal */
2548         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2549 }
2550
2551 static Base *mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2552 {
2553         Base *base_new;
2554         Object *obedit = base_old->object;
2555         BMesh *bm_new;
2556
2557         bm_new = BM_mesh_create(&bm_mesh_allocsize_default);
2558         BM_mesh_elem_toolflags_ensure(bm_new);  /* needed for 'duplicate' bmo */
2559
2560         CustomData_copy(&bm_old->vdata, &bm_new->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
2561         CustomData_copy(&bm_old->edata, &bm_new->edata, CD_MASK_BMESH, CD_CALLOC, 0);
2562         CustomData_copy(&bm_old->ldata, &bm_new->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
2563         CustomData_copy(&bm_old->pdata, &bm_new->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
2564
2565         CustomData_bmesh_init_pool(&bm_new->vdata, bm_mesh_allocsize_default.totvert, BM_VERT);
2566         CustomData_bmesh_init_pool(&bm_new->edata, bm_mesh_allocsize_default.totedge, BM_EDGE);
2567         CustomData_bmesh_init_pool(&bm_new->ldata, bm_mesh_allocsize_default.totloop, BM_LOOP);
2568         CustomData_bmesh_init_pool(&bm_new->pdata, bm_mesh_allocsize_default.totface, BM_FACE);
2569
2570         base_new = ED_object_add_duplicate(bmain, scene, base_old, USER_DUP_MESH);
2571         /* DAG_relations_tag_update(bmain); */ /* normally would call directly after but in this case delay recalc */
2572         assign_matarar(base_new->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */
2573
2574         ED_base_object_select(base_new, BA_SELECT);
2575
2576         BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
2577                      "duplicate geom=%hvef dest=%p", BM_ELEM_TAG, bm_new);
2578         BMO_op_callf(bm_old, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
2579                      "delete geom=%hvef context=%i", BM_ELEM_TAG, DEL_FACES);
2580
2581         /* deselect loose data - this used to get deleted,
2582          * we could de-select edges and verts only, but this turns out to be less complicated
2583          * since de-selecting all skips selection flushing logic */
2584         BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
2585
2586         BM_mesh_normals_update(bm_new);
2587
2588         BM_mesh_bm_to_me(bm_new, base_new->object->data, false);
2589
2590         BM_mesh_free(bm_new);
2591         ((Mesh *)base_new->object->data)->edit_btmesh = NULL;
2592         
2593         return base_new;
2594 }
2595
2596 static bool mesh_separate_selected(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2597 {
2598         /* we may have tags from previous operators */
2599         BM_mesh_elem_hflag_disable_all(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, false);
2600
2601         /* sel -> tag */
2602         BM_mesh_elem_hflag_enable_test(bm_old, BM_FACE | BM_EDGE | BM_VERT, BM_ELEM_TAG, true, false, BM_ELEM_SELECT);
2603
2604         return (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL);
2605 }
2606
2607 /* flush a hflag to from verts to edges/faces */
2608 static void bm_mesh_hflag_flush_vert(BMesh *bm, const char hflag)
2609 {
2610         BMEdge *e;
2611         BMLoop *l_iter;
2612         BMLoop *l_first;
2613         BMFace *f;
2614
2615         BMIter eiter;
2616         BMIter fiter;
2617
2618         bool ok;
2619
2620         BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
2621                 if (BM_elem_flag_test(e->v1, hflag) &&
2622                     BM_elem_flag_test(e->v2, hflag))
2623                 {
2624                         BM_elem_flag_enable(e, hflag);
2625                 }
2626                 else {
2627                         BM_elem_flag_disable(e, hflag);
2628                 }
2629         }
2630         BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
2631                 ok = true;
2632                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
2633                 do {
2634                         if (!BM_elem_flag_test(l_iter->v, hflag)) {
2635                                 ok = false;
2636                                 break;
2637                         }
2638                 } while ((l_iter = l_iter->next) != l_first);
2639
2640                 BM_elem_flag_set(f, hflag, ok);
2641         }
2642 }
2643
2644 /**
2645  * Sets an object to a single material. from one of its slots.
2646  *
2647  * \note This could be used for split-by-material for non mesh types.
2648  * \note This could take material data from another object or args.
2649  */
2650 static void mesh_separate_material_assign_mat_nr(Object *ob, const short mat_nr)
2651 {
2652         ID *obdata = ob->data;
2653
2654         Material ***matarar;
2655         short *totcolp;
2656
2657         totcolp = give_totcolp_id(obdata);
2658         matarar = give_matarar_id(obdata);
2659
2660         if ((totcolp && matarar) == 0) {
2661                 BLI_assert(0);
2662                 return;
2663         }
2664
2665         if (*totcolp) {
2666                 Material *ma_ob;
2667                 Material *ma_obdata;
2668                 char matbit;
2669
2670                 if (mat_nr < ob->totcol) {
2671                         ma_ob = ob->mat[mat_nr];
2672                         matbit = ob->matbits[mat_nr];
2673                 }
2674                 else {
2675                         ma_ob = NULL;
2676                         matbit = 0;
2677                 }
2678
2679                 if (mat_nr < *totcolp) {
2680                          ma_obdata = (*matarar)[mat_nr];
2681                 }
2682                 else {
2683                         ma_obdata = NULL;
2684                 }
2685
2686                 BKE_material_clear_id(obdata, true);
2687                 BKE_material_resize_object(ob, 1, true);
2688                 BKE_material_resize_id(obdata, 1, true);
2689
2690                 ob->mat[0] = ma_ob;
2691                 ob->matbits[0] = matbit;
2692                 (*matarar)[0] = ma_obdata;
2693         }
2694         else {
2695                 BKE_material_clear_id(obdata, true);
2696                 BKE_material_resize_object(ob, 0, true);
2697                 BKE_material_resize_id(obdata, 0, true);
2698         }
2699 }
2700
2701 static bool mesh_separate_material(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2702 {
2703         BMFace *f_cmp, *f;
2704         BMIter iter;
2705         bool result = false;
2706
2707         while ((f_cmp = BM_iter_at_index(bm_old, BM_FACES_OF_MESH, NULL, 0))) {
2708                 Base *base_new;
2709                 const short mat_nr = f_cmp->mat_nr;
2710                 int tot = 0;
2711
2712                 BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
2713
2714                 BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
2715                         if (f->mat_nr == mat_nr) {
2716                                 BMLoop *l_iter;
2717                                 BMLoop *l_first;
2718
2719                                 BM_elem_flag_enable(f, BM_ELEM_TAG);
2720                                 l_iter = l_first = BM_FACE_FIRST_LOOP(f);
2721                                 do {
2722                                         BM_elem_flag_enable(l_iter->v, BM_ELEM_TAG);
2723                                         BM_elem_flag_enable(l_iter->e, BM_ELEM_TAG);
2724                                 } while ((l_iter = l_iter->next) != l_first);
2725
2726                                 tot++;
2727                         }
2728                 }
2729
2730                 /* leave the current object with some materials */
2731                 if (tot == bm_old->totface) {
2732                         mesh_separate_material_assign_mat_nr(base_old->object, mat_nr);
2733
2734                         /* since we're in editmode, must set faces here */
2735                         BM_ITER_MESH (f, &iter, bm_old, BM_FACES_OF_MESH) {
2736                                 f->mat_nr = 0;
2737                         }
2738                         break;
2739                 }
2740
2741                 /* Move selection into a separate object */
2742                 base_new = mesh_separate_tagged(bmain, scene, base_old, bm_old);
2743                 if (base_new) {
2744                         mesh_separate_material_assign_mat_nr(base_new->object, mat_nr);
2745                 }
2746
2747                 result |= (base_new != NULL);
2748         }
2749
2750         return result;
2751 }
2752
2753 static bool mesh_separate_loose(Main *bmain, Scene *scene, Base *base_old, BMesh *bm_old)
2754 {
2755         int i;
2756         BMEdge *e;
2757         BMVert *v_seed;
2758         BMWalker walker;
2759         bool result = false;
2760         int max_iter = bm_old->totvert;
2761
2762         /* Clear all selected vertices */
2763         BM_mesh_elem_hflag_disable_all(bm_old, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
2764
2765         /* A "while (true)" loop should work here as each iteration should
2766          * select and remove at least one vertex and when all vertices
2767          * are selected the loop will break out. But guard against bad
2768          * behavior by limiting iterations to the number of vertices in the
2769          * original mesh.*/
2770         for (i = 0; i < max_iter; i++) {
2771                 int tot = 0;
2772                 /* Get a seed vertex to start the walk */
2773                 v_seed = BM_iter_at_index(bm_old, BM_VERTS_OF_MESH, NULL, 0);
2774
2775                 /* No vertices available, can't do anything */
2776                 if (v_seed == NULL) {
2777                         break;
2778                 }
2779
2780                 /* Select the seed explicitly, in case it has no edges */
2781                 if (!BM_elem_flag_test(v_seed, BM_ELEM_TAG)) { BM_elem_flag_enable(v_seed, BM_ELEM_TAG); tot++; }
2782
2783                 /* Walk from the single vertex, selecting everything connected
2784                  * to it */
2785                 BMW_init(&walker, bm_old, BMW_SHELL,
2786                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
2787                          BMW_FLAG_NOP,
2788                          BMW_NIL_LAY);
2789
2790                 for (e = BMW_begin(&walker, v_seed); e; e = BMW_step(&walker)) {
2791                         if (!BM_elem_flag_test(e->v1, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v1, BM_ELEM_TAG); tot++; }
2792                         if (!BM_elem_flag_test(e->v2, BM_ELEM_TAG)) { BM_elem_flag_enable(e->v2, BM_ELEM_TAG); tot++; }
2793                 }
2794                 BMW_end(&walker);
2795
2796                 if (bm_old->totvert == tot) {
2797                         /* Every vertex selected, nothing to separate, work is done */
2798                         break;
2799                 }
2800
2801                 /* Flush the selection to get edge/face selections matching
2802                  * the vertex selection */
2803                 bm_mesh_hflag_flush_vert(bm_old, BM_ELEM_TAG);
2804
2805                 /* Move selection into a separate object */
2806                 result |= (mesh_separate_tagged(bmain, scene, base_old, bm_old) != NULL);
2807         }
2808
2809         return result;
2810 }
2811
2812 static int edbm_separate_exec(bContext *C, wmOperator *op)
2813 {
2814         Main *bmain = CTX_data_main(C);
2815         Scene *scene = CTX_data_scene(C);
2816         const int type = RNA_enum_get(op->ptr, "type");
2817         int retval = 0;
2818         
2819         if (ED_operator_editmesh(C)) {
2820                 Base *base = CTX_data_active_base(C);
2821                 BMEditMesh *em = BKE_editmesh_from_object(base->object);
2822
2823                 if (type == 0) {
2824                         if ((em->bm->totvertsel == 0) &&
2825                             (em->bm->totedgesel == 0) &&
2826                             (em->bm->totfacesel == 0))
2827                         {
2828                                 BKE_report(op->reports, RPT_ERROR, "Nothing selected");
2829                                 return OPERATOR_CANCELLED;
2830                         }
2831                 }
2832
2833                 /* editmode separate */
2834                 if      (type == 0) retval = mesh_separate_selected(bmain, scene, base, em->bm);
2835                 else if (type == 1) retval = mesh_separate_material(bmain, scene, base, em->bm);
2836                 else if (type == 2) retval = mesh_separate_loose(bmain, scene, base, em->bm);
2837                 else                BLI_assert(0);
2838
2839                 if (retval) {
2840                         EDBM_update_generic(em, true, true);
2841                 }
2842         }
2843         else {
2844                 if (type == 0) {
2845                         BKE_report(op->reports, RPT_ERROR, "Selection not supported in object mode");
2846                         return OPERATOR_CANCELLED;
2847                 }
2848
2849                 /* object mode separate */
2850                 CTX_DATA_BEGIN(C, Base *, base_iter, selected_editable_bases)
2851                 {
2852                         Object *ob = base_iter->object;
2853                         if (ob->type == OB_MESH) {
2854                                 Mesh *me = ob->data;
2855                                 if (me->id.lib == NULL) {
2856                                         BMesh *bm_old = NULL;
2857                                         int retval_iter = 0;
2858
2859                                         bm_old = BM_mesh_create(&bm_mesh_allocsize_default);
2860
2861                                         BM_mesh_bm_from_me(bm_old, me, false, false, 0);
2862
2863                                         if      (type == 1) retval_iter = mesh_separate_material(bmain, scene, base_iter, bm_old);
2864                                         else if (type == 2) retval_iter = mesh_separate_loose(bmain, scene, base_iter, bm_old);
2865                                         else                BLI_assert(0);
2866
2867                                         if (retval_iter) {
2868                                                 BM_mesh_bm_to_me(bm_old, me, false);
2869
2870                                                 DAG_id_tag_update(&me->id, OB_RECALC_DATA);
2871                                                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2872                                         }
2873
2874                                         BM_mesh_free(bm_old);
2875
2876                                         retval |= retval_iter;
2877                                 }
2878                         }
2879                 }
2880                 CTX_DATA_END;
2881         }
2882
2883         if (retval) {
2884                 /* delay depsgraph recalc until all objects are duplicated */
2885                 DAG_relations_tag_update(bmain);
2886                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
2887
2888                 return OPERATOR_FINISHED;
2889         }
2890
2891         return OPERATOR_CANCELLED;
2892 }
2893
2894 /* *************** Operator: separate parts *************/
2895
2896 static EnumPropertyItem prop_separate_types[] = {
2897         {0, "SELECTED", 0, "Selection", ""},
2898         {1, "MATERIAL", 0, "By Material", ""},
2899         {2, "LOOSE", 0, "By loose parts", ""},
2900         {0, NULL, 0, NULL, NULL}
2901 };
2902
2903 void MESH_OT_separate(wmOperatorType *ot)
2904 {
2905         /* identifiers */
2906         ot->name = "Separate";
2907         ot->description = "Separate selected geometry into a new mesh";
2908         ot->idname = "MESH_OT_separate";
2909         
2910         /* api callbacks */
2911         ot->invoke = WM_menu_invoke;
2912         ot->exec = edbm_separate_exec;
2913         ot->poll = ED_operator_scene_editable; /* object and editmode */
2914         
2915         /* flags */
2916         ot->flag = OPTYPE_UNDO;
2917         
2918         ot->prop = RNA_def_enum(ot->srna, "type", prop_separate_types, 0, "Type", "");
2919 }
2920
2921
2922 static int edbm_fill_exec(bContext *C, wmOperator *op)
2923 {
2924         Object *obedit = CTX_data_edit_object(C);
2925         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2926         const bool use_beauty = RNA_boolean_get(op->ptr, "use_beauty");
2927         BMOperator bmop;
2928         
2929         if (!EDBM_op_init(em, &bmop, op,
2930                           "triangle_fill edges=%he use_beauty=%b",
2931                           BM_ELEM_SELECT, use_beauty))
2932         {
2933                 return OPERATOR_CANCELLED;
2934         }
2935         
2936         BMO_op_exec(em->bm, &bmop);
2937         
2938         /* select new geometry */
2939         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE | BM_EDGE, BM_ELEM_SELECT, true);
2940         
2941         if (!EDBM_op_finish(em, &bmop, op, true)) {
2942                 return OPERATOR_CANCELLED;
2943         }
2944
2945         EDBM_update_generic(em, true, true);
2946         
2947         return OPERATOR_FINISHED;
2948
2949 }
2950
2951 void MESH_OT_fill(wmOperatorType *ot)
2952 {
2953         /* identifiers */
2954         ot->name = "Fill";
2955         ot->idname = "MESH_OT_fill";
2956         ot->description = "Fill a selected edge loop with faces";
2957
2958         /* api callbacks */
2959         ot->exec = edbm_fill_exec;
2960         ot->poll = ED_operator_editmesh;
2961
2962         /* flags */
2963         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2964
2965         RNA_def_boolean(ot->srna, "use_beauty", true, "Beauty", "Use best triangulation division");
2966 }
2967
2968
2969 /* -------------------------------------------------------------------- */
2970 /* Grid Fill (and helper functions) */
2971
2972 static bool bm_edge_test_fill_grid_cb(BMEdge *e, void *UNUSED(bm_v))
2973 {
2974         return BM_elem_flag_test_bool(e, BM_ELEM_TAG);
2975 }
2976
2977 static float edbm_fill_grid_vert_tag_angle(BMVert *v)
2978 {
2979         BMIter iter;
2980         BMEdge *e_iter;
2981         BMVert *v_pair[2];
2982         int i = 0;
2983         BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
2984                 if (BM_elem_flag_test(e_iter, BM_ELEM_TAG)) {
2985                         v_pair[i++] = BM_edge_other_vert(e_iter, v);
2986                 }
2987         }
2988         BLI_assert(i == 2);
2989
2990         return fabsf((float)M_PI - angle_v3v3v3(v_pair[0]->co, v->co, v_pair[1]->co));
2991 }
2992
2993 /**
2994  * non-essential utility function to select 2 open edge loops from a closed loop.
2995  */
2996 static void edbm_fill_grid_prepare(BMesh *bm, int offset, int *r_span, bool span_calc)
2997 {
2998         BMEdge *e;
2999         BMIter iter;
3000         int count;
3001         int span = *r_span;
3002
3003         ListBase eloops = {NULL};
3004         struct BMEdgeLoopStore *el_store;
3005         // LinkData *el_store;
3006
3007         /* select -> tag */
3008         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
3009                 BM_elem_flag_set(e, BM_ELEM_TAG, BM_elem_flag_test(e, BM_ELEM_SELECT));
3010         }
3011
3012         count = BM_mesh_edgeloops_find(bm, &eloops, bm_edge_test_fill_grid_cb, bm);
3013         el_store = eloops.first;
3014
3015         if (count == 1 && BM_edgeloop_is_closed(el_store) && (BM_edgeloop_length_get(el_store) & 1) == 0) {
3016                 /* be clever! detect 2 edge loops from one closed edge loop */
3017                 const int verts_len = BM_edgeloop_length_get(el_store);
3018                 ListBase *verts = BM_edgeloop_verts_get(el_store);
3019                 BMVert *v_act = BM_mesh_active_vert_get(bm);
3020                 LinkData *v_act_link;
3021                 BMEdge **edges = MEM_mallocN(sizeof(*edges) * verts_len, __func__);
3022                 int i;
3023
3024                 if (v_act && (v_act_link = BLI_findptr(verts, v_act, offsetof(LinkData, data)))) {
3025                         /* pass */
3026                 }
3027                 else {
3028                         /* find the vertex with the best angle (a corner vertex) */
3029                         LinkData *v_link, *v_link_best = NULL;
3030                         float angle_best = -1.0f;
3031                         for (v_link = verts->first; v_link; v_link = v_link->next) {
3032                                 const float angle = edbm_fill_grid_vert_tag_angle(v_link->data);
3033                                 if ((angle > angle_best) || (v_link_best == NULL)) {
3034                                         angle_best = angle;
3035                                         v_link_best = v_link;
3036                                 }
3037                         }
3038
3039                         v_act_link = v_link_best;
3040                         v_act = v_act_link->data;
3041                 }
3042
3043                 if (offset != 0) {
3044                         v_act_link = BLI_findlink(verts, offset);
3045                         v_act = v_act_link->data;
3046                 }
3047
3048                 /* set this vertex first */
3049                 BLI_rotatelist_first(verts, v_act_link);
3050                 BM_edgeloop_edges_get(el_store, edges);
3051
3052
3053                 if (span_calc) {
3054                         /* calculate the span by finding the next corner in 'verts'
3055                          * we dont know what defines a corner exactly so find the 4 verts
3056                          * in the loop with the greatest angle.
3057                          * Tag them and use the first tagged vertex to calculate the span.
3058                          *
3059                          * note: we may have already checked 'edbm_fill_grid_vert_tag_angle()' on each
3060                          * vert, but advantage of de-duplicating is minimal. */
3061                         struct SortPointerByFloat *ele_sort = MEM_mallocN(sizeof(*ele_sort) * verts_len, __func__);
3062                         LinkData *v_link;
3063                         for (v_link = verts->first, i = 0; v_link; v_link = v_link->next, i++) {
3064                                 BMVert *v = v_link->data;
3065                                 const float angle = edbm_fill_grid_vert_tag_angle(v);
3066                                 ele_sort[i].sort_value = angle;
3067                                 ele_sort[i].data = v;
3068
3069                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
3070                         }
3071
3072                         qsort(ele_sort, verts_len, sizeof(*ele_sort), BLI_sortutil_cmp_float_reverse);
3073
3074                         for (i = 0; i < 4; i++) {
3075                                 BMVert *v = ele_sort[i].data;
3076                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
3077                         }
3078
3079                         /* now find the first... */
3080                         for (v_link = verts->first, i = 0; i < verts_len / 2; v_link = v_link->next, i++) {
3081                                 BMVert *v = v_link->data;
3082                                 if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
3083                                         if (v != v_act) {
3084                                                 span = i;
3085                                                 break;
3086                                         }
3087                                 }
3088                         }
3089                         MEM_freeN(ele_sort);
3090                 }
3091                 /* end span calc */
3092
3093
3094                 /* un-flag 'rails' */
3095                 for (i = 0; i < span; i++) {
3096                         BM_elem_flag_disable(edges[i], BM_ELEM_TAG);
3097                         BM_elem_flag_disable(edges[(verts_len / 2) + i], BM_ELEM_TAG);
3098                 }
3099                 MEM_freeN(edges);
3100         }
3101         /* else let the bmesh-operator handle it */
3102
3103         BM_mesh_edgeloops_free(&eloops);
3104
3105         *r_span = span;
3106 }
3107
3108 static int edbm_fill_grid_exec(bContext *C, wmOperator *op)
3109 {
3110         BMOperator bmop;
3111         Object *obedit = CTX_data_edit_object(C);
3112         BMEditMesh *em = BKE_editmesh_from_object(obedit);
3113         const short use_smooth = edbm_add_edge_face__smooth_get(em->bm);
3114         const int totedge_orig = em->bm->totedge;
3115         const int totface_orig = em->bm->totface;
3116         const bool use_interp_simple = RNA_boolean_get(op->ptr, "use_interp_simple");
3117         const bool use_prepare = true;
3118
3119
3120         if (use_prepare) {
3121                 /* use when we have a single loop selected */
3122                 PropertyRNA *prop_span = RNA_struct_find_property(op->ptr, "span");
3123                 PropertyRNA *prop_offset = RNA_struct_find_property(op->ptr, "offset");
3124                 bool calc_span;
3125
3126                 const int clamp = em->bm->totvertsel;
3127                 int span;
3128                 int offset;
3129
3130                 if (RNA_property_is_set(op->ptr, prop_span)) {
3131                         span = RNA_property_int_get(op->ptr, prop_span);
3132                         span = min_ii(span, (clamp / 2) - 1);
3133                         calc_span = false;
3134                 }
3135                 else {
3136                         span = clamp / 4;
3137                         calc_span = true;
3138                 }
3139
3140                 offset = RNA_property_int_get(op->ptr, prop_offset);
3141                 offset = clamp ? mod_i(offset, clamp) : 0;
3142
3143                 /* in simple cases, move selection for tags, but also support more advanced cases */
3144                 edbm_fill_grid_prepare(em->bm, offset, &span, calc_span);
3145
3146                 RNA_property_int_set(op->ptr, prop_span, span);
3147         }
3148         /* end tricky prepare code */
3149
3150
3151         if (!EDBM_op_init(em, &bmop, op,
3152                           "grid_fill edges=%he mat_nr=%i use_smooth=%b use_interp_simple=%b",
3153                           use_prepare ? BM_ELEM_TAG : BM_ELEM_SELECT,
3154                           em->mat_nr, use_smooth, use_interp_simple))
3155         {
3156                 return OPERATOR_CANCELLED;
3157         }
3158
3159         BMO_op_exec(em->bm, &bmop);
3160
3161         /* cancel if nothing was done */
3162         if ((totedge_orig == em->bm->totedge) &&
3163             (totface_orig == em->bm->totface))
3164         {
3165                 EDBM_op_finish(em, &bmop, op, true);
3166                 return OPERATOR_CANCELLED;
3167         }
3168
3169         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, true);
3170
3171         if (!EDBM_op_finish(em, &bmop, op, true)) {
3172                 return OPERATOR_CANCELLED;
3173         }
3174
3175         EDBM_update_generic(em, true, true);
3176
3177         return OPERATOR_FINISHED;
3178 }
3179
3180 void MESH_OT_fill_grid(wmOperatorType *ot)
3181 {
3182         PropertyRNA *prop;
3183
3184         /* identifiers */
3185         ot->name = "Grid Fill";
3186         ot->description = "Fill grid from two loops";
3187         ot->idname = "MESH_OT_fill_grid";
3188
3189         /* api callbacks */
3190         ot->exec = edbm_fill_grid_exec;
3191         ot->poll = ED_operator_editmesh;
3192
3193         /* flags */
3194         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3195