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