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