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