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