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