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