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