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