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