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