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