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