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