Fix [#34005] blender will close immediately in debug mode on deleting objects
[blender.git] / source / blender / editors / mesh / editmesh_select.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 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_select.c
29  *  \ingroup edmesh
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_blenlib.h"
35 #include "BLI_math.h"
36 #include "BLI_rand.h"
37 #include "BLI_array.h"
38 #include "BLI_smallhash.h"
39 #include "BLI_heap.h"
40
41 #include "BKE_context.h"
42 #include "BKE_displist.h"
43 #include "BKE_report.h"
44 #include "BKE_paint.h"
45 #include "BKE_mesh.h"
46 #include "BKE_tessmesh.h"
47
48 #include "IMB_imbuf_types.h"
49 #include "IMB_imbuf.h"
50
51 #include "WM_api.h"
52 #include "WM_types.h"
53
54 #include "RNA_access.h"
55 #include "RNA_define.h"
56
57 #include "ED_mesh.h"
58 #include "ED_screen.h"
59 #include "ED_uvedit.h"
60 #include "ED_view3d.h"
61
62 #include "BIF_gl.h"
63
64 #include "DNA_scene_types.h"
65 #include "DNA_object_types.h"
66 #include "DNA_mesh_types.h"
67
68 #include "mesh_intern.h"
69
70 #include "UI_resources.h"
71
72 /* ****************************** MIRROR **************** */
73
74 void EDBM_select_mirrored(Object *UNUSED(obedit), BMEditMesh *em, int extend)
75 {
76         BMVert *v1, *v2;
77         BMIter iter;
78
79         BM_ITER_MESH (v1, &iter, em->bm, BM_VERTS_OF_MESH) {
80                 if (!BM_elem_flag_test(v1, BM_ELEM_SELECT) || BM_elem_flag_test(v1, BM_ELEM_HIDDEN)) {
81                         BM_elem_flag_disable(v1, BM_ELEM_TAG);
82                 }
83                 else {
84                         BM_elem_flag_enable(v1, BM_ELEM_TAG);
85                 }
86         }
87
88         EDBM_verts_mirror_cache_begin(em, TRUE);
89
90         if (!extend)
91                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
92
93         BM_ITER_MESH (v1, &iter, em->bm, BM_VERTS_OF_MESH) {
94                 if (!BM_elem_flag_test(v1, BM_ELEM_TAG) || BM_elem_flag_test(v1, BM_ELEM_HIDDEN))
95                         continue;
96
97                 v2 = EDBM_verts_mirror_get(em, v1);
98                 if (v2 && !BM_elem_flag_test(v2, BM_ELEM_HIDDEN)) {
99                         BM_vert_select_set(em->bm, v2, TRUE);
100                 }
101         }
102
103         EDBM_verts_mirror_cache_end(em);
104 }
105
106 void EDBM_automerge(Scene *scene, Object *obedit, int update)
107 {
108         
109         if ((scene->toolsettings->automerge) &&
110             (obedit && obedit->type == OB_MESH))
111         {
112                 int ok;
113                 BMEditMesh *em = BMEdit_FromObject(obedit);
114
115                 if (!em) {
116                         return;
117                 }
118
119                 ok = BMO_op_callf(em->bm, BMO_FLAG_DEFAULTS,
120                                   "automerge verts=%hv dist=%f",
121                                   BM_ELEM_SELECT, scene->toolsettings->doublimit);
122
123                 if (LIKELY(ok) && update) {
124                         EDBM_update_generic(em, TRUE, TRUE);
125                 }
126         }
127 }
128
129 /* ****************************** SELECTION ROUTINES **************** */
130
131 unsigned int bm_solidoffs = 0, bm_wireoffs = 0, bm_vertoffs = 0;    /* set in drawobject.c ... for colorindices */
132
133 /* facilities for border select and circle select */
134 static char *selbuf = NULL;
135
136 /* opengl doesn't support concave... */
137 static void draw_triangulated(const int mcords[][2], const short tot)
138 {
139         ListBase lb = {NULL, NULL};
140         DispList *dl;
141         float *fp;
142         int a;
143         
144         /* make displist */
145         dl = MEM_callocN(sizeof(DispList), "poly disp");
146         dl->type = DL_POLY;
147         dl->parts = 1;
148         dl->nr = tot;
149         dl->verts = fp = MEM_callocN(tot * 3 * sizeof(float), "poly verts");
150         BLI_addtail(&lb, dl);
151         
152         for (a = 0; a < tot; a++, fp += 3) {
153                 fp[0] = (float)mcords[a][0];
154                 fp[1] = (float)mcords[a][1];
155         }
156         
157         /* do the fill */
158         BKE_displist_fill(&lb, &lb, 0);
159
160         /* do the draw */
161         dl = lb.first;  /* filldisplist adds in head of list */
162         if (dl->type == DL_INDEX3) {
163                 int *index;
164                 
165                 a = dl->parts;
166                 fp = dl->verts;
167                 index = dl->index;
168                 glBegin(GL_TRIANGLES);
169                 while (a--) {
170                         glVertex3fv(fp + 3 * index[0]);
171                         glVertex3fv(fp + 3 * index[1]);
172                         glVertex3fv(fp + 3 * index[2]);
173                         index += 3;
174                 }
175                 glEnd();
176         }
177         
178         BKE_displist_free(&lb);
179 }
180
181
182 /* reads rect, and builds selection array for quick lookup */
183 /* returns if all is OK */
184 int EDBM_backbuf_border_init(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
185 {
186         struct ImBuf *buf;
187         unsigned int *dr;
188         int a;
189         
190         if (vc->obedit == NULL || vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
191                 return 0;
192         }
193         
194         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
195         if (buf == NULL) return 0;
196         if (bm_vertoffs == 0) return 0;
197
198         dr = buf->rect;
199         
200         /* build selection lookup */
201         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
202         
203         a = (xmax - xmin + 1) * (ymax - ymin + 1);
204         while (a--) {
205                 if (*dr > 0 && *dr <= bm_vertoffs)
206                         selbuf[*dr] = 1;
207                 dr++;
208         }
209         IMB_freeImBuf(buf);
210         return 1;
211 }
212
213 int EDBM_backbuf_check(unsigned int index)
214 {
215         if (selbuf == NULL) return 1;
216         if (index > 0 && index <= bm_vertoffs)
217                 return selbuf[index];
218         return 0;
219 }
220
221 void EDBM_backbuf_free(void)
222 {
223         if (selbuf) MEM_freeN(selbuf);
224         selbuf = NULL;
225 }
226
227 /* mcords is a polygon mask
228  * - grab backbuffer,
229  * - draw with black in backbuffer, 
230  * - grab again and compare
231  * returns 'OK' 
232  */
233 int EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
234 {
235         unsigned int *dr, *drm;
236         struct ImBuf *buf, *bufmask;
237         int a;
238         
239         /* method in use for face selecting too */
240         if (vc->obedit == NULL) {
241                 if (!(paint_facesel_test(vc->obact) || paint_vertsel_test(vc->obact))) {
242                         return 0;
243                 }
244         }
245         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
246                 return 0;
247         }
248
249         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
250         if (buf == NULL) return 0;
251         if (bm_vertoffs == 0) return 0;
252
253         dr = buf->rect;
254
255         /* draw the mask */
256         glDisable(GL_DEPTH_TEST);
257         
258         glColor3ub(0, 0, 0);
259         
260         /* yah, opengl doesn't do concave... tsk! */
261         ED_region_pixelspace(vc->ar);
262         draw_triangulated(mcords, tot);
263         
264         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
265         for (a = 0; a < tot; a++) {
266                 glVertex2iv(mcords[a]);
267         }
268         glEnd();
269         
270         glFinish(); /* to be sure readpixels sees mask */
271         
272         /* grab mask */
273         bufmask = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
274
275         if (bufmask == NULL) {
276                 return 0; /* only when mem alloc fails, go crash somewhere else! */
277         }
278         else {
279                 drm = bufmask->rect;
280         }
281
282         /* build selection lookup */
283         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
284         
285         a = (xmax - xmin + 1) * (ymax - ymin + 1);
286         while (a--) {
287                 if (*dr > 0 && *dr <= bm_vertoffs && *drm == 0) selbuf[*dr] = 1;
288                 dr++; drm++;
289         }
290         IMB_freeImBuf(buf);
291         IMB_freeImBuf(bufmask);
292
293         return 1;
294 }
295
296 /* circle shaped sample area */
297 int EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
298 {
299         struct ImBuf *buf;
300         unsigned int *dr;
301         short xmin, ymin, xmax, ymax, xc, yc;
302         int radsq;
303         
304         /* method in use for face selecting too */
305         if (vc->obedit == NULL) {
306                 if (!(paint_facesel_test(vc->obact) || paint_vertsel_test(vc->obact))) {
307                         return 0;
308                 }
309         }
310         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) return 0;
311         
312         xmin = xs - rads; xmax = xs + rads;
313         ymin = ys - rads; ymax = ys + rads;
314         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
315         if (bm_vertoffs == 0) return 0;
316         if (buf == NULL) return 0;
317
318         dr = buf->rect;
319         
320         /* build selection lookup */
321         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
322         radsq = rads * rads;
323         for (yc = -rads; yc <= rads; yc++) {
324                 for (xc = -rads; xc <= rads; xc++, dr++) {
325                         if (xc * xc + yc * yc < radsq) {
326                                 if (*dr > 0 && *dr <= bm_vertoffs) selbuf[*dr] = 1;
327                         }
328                 }
329         }
330
331         IMB_freeImBuf(buf);
332         return 1;
333         
334 }
335
336 static void findnearestvert__doClosest(void *userData, BMVert *eve, const float screen_co[2], int index)
337 {
338         struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
339
340         if (data->pass == 0) {
341                 if (index <= data->lastIndex)
342                         return;
343         }
344         else {
345                 if (index > data->lastIndex)
346                         return;
347         }
348
349         if (data->dist > 3) {
350                 float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
351                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) == data->select) {
352                         if (data->strict == 1) {
353                                 return;
354                         }
355                         else {
356                                 dist_test += 5;
357                         }
358                 }
359
360                 if (dist_test < data->dist) {
361                         data->dist = dist_test;
362                         data->closest = eve;
363                         data->closestIndex = index;
364                 }
365         }
366 }
367
368
369
370
371 static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
372 {
373         BMEditMesh *em = (BMEditMesh *)handle;
374         BMVert *eve = BM_vert_at_index(em->bm, index - 1);
375
376         if (eve && BM_elem_flag_test(eve, BM_ELEM_SELECT)) return 0;
377         return 1;
378 }
379 /**
380  * findnearestvert
381  * 
382  * dist (in/out): minimal distance to the nearest and at the end, actual distance
383  * sel: selection bias
384  *      if SELECT, selected vertice are given a 5 pixel bias to make them further than unselect verts
385  *      if 0, unselected vertice are given the bias
386  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
387  */
388 BMVert *EDBM_vert_find_nearest(ViewContext *vc, float *r_dist, const short sel, const short strict)
389 {
390         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
391                 float distance;
392                 unsigned int index;
393                 BMVert *eve;
394                 
395                 if (strict) {
396                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
397                                                            strict, vc->em, findnearestvert__backbufIndextest);
398                 }
399                 else {
400                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
401                                                            0, NULL, NULL);
402                 }
403                 
404                 eve = BM_vert_at_index(vc->em->bm, index - 1);
405                 
406                 if (eve && distance < *r_dist) {
407                         *r_dist = distance;
408                         return eve;
409                 }
410                 else {
411                         return NULL;
412                 }
413                         
414         }
415         else {
416                 struct { float mval_fl[2], pass, select, strict; float dist, lastIndex, closestIndex; BMVert *closest; } data;
417                 static int lastSelectedIndex = 0;
418                 static BMVert *lastSelected = NULL;
419                 
420                 if (lastSelected && BM_vert_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
421                         lastSelectedIndex = 0;
422                         lastSelected = NULL;
423                 }
424
425                 data.lastIndex = lastSelectedIndex;
426                 data.mval_fl[0] = vc->mval[0];
427                 data.mval_fl[1] = vc->mval[1];
428                 data.select = sel;
429                 data.dist = *r_dist;
430                 data.strict = strict;
431                 data.closest = NULL;
432                 data.closestIndex = 0;
433
434                 data.pass = 0;
435
436                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
437
438                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
439
440                 if (data.dist > 3) {
441                         data.pass = 1;
442                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
443                 }
444
445                 *r_dist = data.dist;
446                 lastSelected = data.closest;
447                 lastSelectedIndex = data.closestIndex;
448
449                 return data.closest;
450         }
451 }
452
453 /* note; uses v3d, so needs active 3d window */
454 static void findnearestedge__doClosest(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
455 {
456         struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } *data = userData;
457         int distance;
458
459         distance = dist_to_line_segment_v2(data->mval_fl, screen_co_a, screen_co_b);
460                 
461         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
462                 distance += 5;
463         }
464
465         if (distance < data->dist) {
466                 if (data->vc.rv3d->rflag & RV3D_CLIPPING) {
467                         float lambda = line_point_factor_v2(data->mval_fl, screen_co_a, screen_co_b);
468                         float vec[3];
469
470                         vec[0] = eed->v1->co[0] + lambda * (eed->v2->co[0] - eed->v1->co[0]);
471                         vec[1] = eed->v1->co[1] + lambda * (eed->v2->co[1] - eed->v1->co[1]);
472                         vec[2] = eed->v1->co[2] + lambda * (eed->v2->co[2] - eed->v1->co[2]);
473
474                         if (ED_view3d_clipping_test(data->vc.rv3d, vec, TRUE) == 0) {
475                                 data->dist = distance;
476                                 data->closest = eed;
477                         }
478                 }
479                 else {
480                         data->dist = distance;
481                         data->closest = eed;
482                 }
483         }
484 }
485 BMEdge *EDBM_edge_find_nearest(ViewContext *vc, float *r_dist)
486 {
487
488         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
489                 float distance;
490                 unsigned int index;
491                 BMEdge *eed;
492                 
493                 view3d_validate_backbuf(vc);
494                 
495                 index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_solidoffs, bm_wireoffs, &distance, 0, NULL, NULL);
496                 eed = BM_edge_at_index(vc->em->bm, index - 1);
497                 
498                 if (eed && distance < *r_dist) {
499                         *r_dist = distance;
500                         return eed;
501                 }
502                 else {
503                         return NULL;
504                 }
505         }
506         else {
507                 struct { ViewContext vc; float mval_fl[2]; float dist; BMEdge *closest; } data;
508
509                 data.vc = *vc;
510                 data.mval_fl[0] = vc->mval[0];
511                 data.mval_fl[1] = vc->mval[1];
512                 data.dist = *r_dist;
513                 data.closest = NULL;
514                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
515
516                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, V3D_PROJ_TEST_CLIP_WIN);
517
518                 *r_dist = data.dist;
519                 return data.closest;
520         }
521 }
522
523 static void findnearestface__getDistance(void *userData, BMFace *efa, const float screen_co[2], int UNUSED(index))
524 {
525         struct { float mval_fl[2]; float dist; BMFace *toFace; } *data = userData;
526
527         if (efa == data->toFace) {
528                 const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
529
530                 if (dist_test < data->dist) {
531                         data->dist = dist_test;
532                 }
533         }
534 }
535 static void findnearestface__doClosest(void *userData, BMFace *efa, const float screen_co[2], int index)
536 {
537         struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
538
539         if (data->pass == 0) {
540                 if (index <= data->lastIndex)
541                         return;
542         }
543         else {
544                 if (index > data->lastIndex)
545                         return;
546         }
547
548         if (data->dist > 3) {
549                 const float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
550
551                 if (dist_test < data->dist) {
552                         data->dist = dist_test;
553                         data->closest = efa;
554                         data->closestIndex = index;
555                 }
556         }
557 }
558
559 BMFace *EDBM_face_find_nearest(ViewContext *vc, float *r_dist)
560 {
561
562         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
563                 unsigned int index;
564                 BMFace *efa;
565
566                 view3d_validate_backbuf(vc);
567
568                 index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
569                 efa = BM_face_at_index(vc->em->bm, index - 1);
570                 
571                 if (efa) {
572                         struct { float mval_fl[2]; float dist; BMFace *toFace; } data;
573
574                         data.mval_fl[0] = vc->mval[0];
575                         data.mval_fl[1] = vc->mval[1];
576                         data.dist = FLT_MAX;
577                         data.toFace = efa;
578
579                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
580
581                         if ((vc->em->selectmode == SCE_SELECT_FACE) || (data.dist < *r_dist)) {  /* only faces, no dist check */
582                                 *r_dist = data.dist;
583                                 return efa;
584                         }
585                 }
586                 
587                 return NULL;
588         }
589         else {
590                 struct { float mval_fl[2], pass; float dist, lastIndex, closestIndex; BMFace *closest; } data;
591                 static int lastSelectedIndex = 0;
592                 static BMFace *lastSelected = NULL;
593
594                 if (lastSelected && BM_face_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
595                         lastSelectedIndex = 0;
596                         lastSelected = NULL;
597                 }
598
599                 data.lastIndex = lastSelectedIndex;
600                 data.mval_fl[0] = vc->mval[0];
601                 data.mval_fl[1] = vc->mval[1];
602                 data.dist = *r_dist;
603                 data.closest = NULL;
604                 data.closestIndex = 0;
605                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
606
607                 data.pass = 0;
608                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
609
610                 if (data.dist > 3.0f) {
611                         data.pass = 1;
612                         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
613                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
614                 }
615
616                 *r_dist = data.dist;
617                 lastSelected = data.closest;
618                 lastSelectedIndex = data.closestIndex;
619
620                 return data.closest;
621         }
622 }
623
624 /* best distance based on screen coords. 
625  * use em->selectmode to define how to use 
626  * selected vertices and edges get disadvantage
627  * return 1 if found one
628  */
629 static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
630 {
631         BMEditMesh *em = vc->em;
632         float dist = 75.0f;
633         
634         *r_eve = NULL;
635         *r_eed = NULL;
636         *r_efa = NULL;
637         
638         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
639         view3d_validate_backbuf(vc);
640         
641         if (em->selectmode & SCE_SELECT_VERTEX)
642                 *r_eve = EDBM_vert_find_nearest(vc, &dist, BM_ELEM_SELECT, 0);
643         if (em->selectmode & SCE_SELECT_FACE)
644                 *r_efa = EDBM_face_find_nearest(vc, &dist);
645
646         dist -= 20; /* since edges select lines, we give dots advantage of 20 pix */
647         if (em->selectmode & SCE_SELECT_EDGE)
648                 *r_eed = EDBM_edge_find_nearest(vc, &dist);
649
650         /* return only one of 3 pointers, for frontbuffer redraws */
651         if (*r_eed) {
652                 *r_efa = NULL; *r_eve = NULL;
653         }
654         else if (*r_efa) {
655                 *r_eve = NULL;
656         }
657         
658         return (*r_eve || *r_eed || *r_efa);
659 }
660
661 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
662 static EnumPropertyItem prop_similar_compare_types[] = {
663         {SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
664         {SIM_CMP_GT, "GREATER", 0, "Greater", ""},
665         {SIM_CMP_LT, "LESS", 0, "Less", ""},
666
667         {0, NULL, 0, NULL, NULL}
668 };
669
670 static EnumPropertyItem prop_similar_types[] = {
671         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
672         {SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
673         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
674         {SIMVERT_EDGE, "EDGE", 0, "Amount of connecting edges", ""},
675
676         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
677         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
678         {SIMEDGE_FACE, "FACE", 0, "Amount of Faces Around an Edge", ""},
679         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
680         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
681         {SIMEDGE_BEVEL, "BEVEL", 0, "Bevel", ""},
682         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
683         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
684
685         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
686         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
687         {SIMFACE_AREA, "AREA", 0, "Area", ""},
688         {SIMFACE_SIDES, "SIDES", 0, "Polygon Sides", ""},
689         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
690         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
691         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
692
693         {0, NULL, 0, NULL, NULL}
694 };
695
696 /* selects new faces/edges/verts based on the existing selection */
697
698 static int similar_face_select_exec(bContext *C, wmOperator *op)
699 {
700         Object *ob = CTX_data_edit_object(C);
701         BMEditMesh *em = BMEdit_FromObject(ob);
702         BMOperator bmop;
703
704         /* get the type from RNA */
705         const int type = RNA_enum_get(op->ptr, "type");
706         const float thresh = RNA_float_get(op->ptr, "threshold");
707         const int compare = RNA_enum_get(op->ptr, "compare");
708
709         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
710         EDBM_op_init(em, &bmop, op,
711                      "similar_faces faces=%hf type=%i thresh=%f compare=%i",
712                      BM_ELEM_SELECT, type, thresh, compare);
713
714         /* execute the operator */
715         BMO_op_exec(em->bm, &bmop);
716
717         /* clear the existing selection */
718         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
719
720         /* select the output */
721         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "faces.out", BM_FACE, BM_ELEM_SELECT, TRUE);
722
723         /* finish the operator */
724         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
725                 return OPERATOR_CANCELLED;
726         }
727
728         EDBM_update_generic(em, FALSE, FALSE);
729
730         /* we succeeded */
731         return OPERATOR_FINISHED;
732 }       
733
734 /* ***************************************************** */
735
736 /* EDGE GROUP */
737
738 /* wrap the above function but do selection flushing edge to face */
739 static int similar_edge_select_exec(bContext *C, wmOperator *op)
740 {
741         Object *ob = CTX_data_edit_object(C);
742         BMEditMesh *em = BMEdit_FromObject(ob);
743         BMOperator bmop;
744
745         /* get the type from RNA */
746         const int type = RNA_enum_get(op->ptr, "type");
747         const float thresh = RNA_float_get(op->ptr, "threshold");
748         const int compare = RNA_enum_get(op->ptr, "compare");
749
750         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
751         EDBM_op_init(em, &bmop, op,
752                      "similar_edges edges=%he type=%i thresh=%f compare=%i",
753                      BM_ELEM_SELECT, type, thresh, compare);
754
755         /* execute the operator */
756         BMO_op_exec(em->bm, &bmop);
757
758         /* clear the existing selection */
759         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
760
761         /* select the output */
762         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "edges.out", BM_EDGE, BM_ELEM_SELECT, TRUE);
763         EDBM_selectmode_flush(em);
764
765         /* finish the operator */
766         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
767                 return OPERATOR_CANCELLED;
768         }
769
770         EDBM_update_generic(em, FALSE, FALSE);
771
772         /* we succeeded */
773         return OPERATOR_FINISHED;
774 }
775
776 /* ********************************* */
777
778 /*
779  * VERT GROUP
780  * mode 1: same normal
781  * mode 2: same number of face users
782  * mode 3: same vertex groups
783  */
784 static int similar_vert_select_exec(bContext *C, wmOperator *op)
785 {
786         Object *ob = CTX_data_edit_object(C);
787         BMEditMesh *em = BMEdit_FromObject(ob);
788         BMOperator bmop;
789         /* get the type from RNA */
790         const int type = RNA_enum_get(op->ptr, "type");
791         float thresh = RNA_float_get(op->ptr, "threshold");
792         const int compare = RNA_enum_get(op->ptr, "compare");
793
794         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
795         EDBM_op_init(em, &bmop, op,
796                      "similar_verts verts=%hv type=%i thresh=%f compare=%i",
797                      BM_ELEM_SELECT, type, thresh, compare);
798
799         /* execute the operator */
800         BMO_op_exec(em->bm, &bmop);
801
802         /* clear the existing selection */
803         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
804
805         /* select the output */
806         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "verts.out", BM_VERT, BM_ELEM_SELECT, TRUE);
807
808         /* finish the operator */
809         if (!EDBM_op_finish(em, &bmop, op, TRUE)) {
810                 return OPERATOR_CANCELLED;
811         }
812
813         EDBM_selectmode_flush(em);
814
815         EDBM_update_generic(em, FALSE, FALSE);
816
817         /* we succeeded */
818         return OPERATOR_FINISHED;
819 }
820
821 static int edbm_select_similar_exec(bContext *C, wmOperator *op)
822 {
823         ToolSettings *ts = CTX_data_tool_settings(C);
824         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "threshold");
825
826         const int type = RNA_enum_get(op->ptr, "type");
827
828         if (!RNA_property_is_set(op->ptr, prop)) {
829                 RNA_property_float_set(op->ptr, prop, ts->select_thresh);
830         }
831         else {
832                 ts->select_thresh = RNA_property_float_get(op->ptr, prop);
833         }
834
835         if      (type < 100) return similar_vert_select_exec(C, op);
836         else if (type < 200) return similar_edge_select_exec(C, op);
837         else                 return similar_face_select_exec(C, op);
838 }
839
840 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
841                                                    int *free)
842 {
843         Object *obedit;
844
845         if (!C) /* needed for docs and i18n tools */
846                 return prop_similar_types;
847
848         obedit = CTX_data_edit_object(C);
849
850         if (obedit && obedit->type == OB_MESH) {
851                 EnumPropertyItem *item = NULL;
852                 int a, totitem = 0;
853                 BMEditMesh *em = BMEdit_FromObject(obedit);
854
855                 if (em->selectmode & SCE_SELECT_VERTEX) {
856                         for (a = SIMVERT_NORMAL; a < SIMEDGE_LENGTH; a++) {
857                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
858                         }
859                 }
860                 else if (em->selectmode & SCE_SELECT_EDGE) {
861                         for (a = SIMEDGE_LENGTH; a < SIMFACE_MATERIAL; a++) {
862                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
863                         }
864                 }
865                 else if (em->selectmode & SCE_SELECT_FACE) {
866                         for (a = SIMFACE_MATERIAL; a <= SIMFACE_COPLANAR; a++) {
867                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
868                         }
869                 }
870                 RNA_enum_item_end(&item, &totitem);
871
872                 *free = 1;
873
874                 return item;
875         }
876
877         return NULL;
878 }
879
880 void MESH_OT_select_similar(wmOperatorType *ot)
881 {
882         PropertyRNA *prop;
883
884         /* identifiers */
885         ot->name = "Select Similar";
886         ot->idname = "MESH_OT_select_similar";
887         ot->description = "Select similar vertices, edges or faces by property types";
888         
889         /* api callbacks */
890         ot->invoke = WM_menu_invoke;
891         ot->exec = edbm_select_similar_exec;
892         ot->poll = ED_operator_editmesh;
893         
894         /* flags */
895         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
896         
897         /* properties */
898         prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
899         RNA_def_enum_funcs(prop, select_similar_type_itemf);
900
901         RNA_def_enum(ot->srna, "compare", prop_similar_compare_types, SIM_CMP_EQ, "Compare", "");
902
903         RNA_def_float(ot->srna, "threshold", 0.0, 0.0, 1.0, "Threshold", "", 0.0, 1.0);
904 }
905
906
907 /* ****************  Mode Select *************** */
908
909 static int edbm_select_mode_exec(bContext *C, wmOperator *op)
910 {
911         const int type       = RNA_enum_get(op->ptr,    "type");
912         const int action     = RNA_enum_get(op->ptr,    "action");
913         const int use_extend = RNA_boolean_get(op->ptr, "use_extend");
914         const int use_expand = RNA_boolean_get(op->ptr, "use_expand");
915
916         if (EDBM_selectmode_toggle(C, type, action, use_extend, use_expand)) {
917                 return OPERATOR_FINISHED;
918         }
919         else {
920                 return OPERATOR_CANCELLED;
921         }
922 }
923
924 static int edbm_select_mode_invoke(bContext *C, wmOperator *op, wmEvent *event)
925 {
926         // RNA_enum_set(op->ptr, "type");  /* type must be set already */
927         RNA_boolean_set(op->ptr, "use_extend", event->shift);
928         RNA_boolean_set(op->ptr, "use_expand", event->ctrl);
929         return edbm_select_mode_exec(C, op);
930 }
931
932 void MESH_OT_select_mode(wmOperatorType *ot)
933 {
934         PropertyRNA *prop;
935
936         static EnumPropertyItem elem_items[] = {
937                 {SCE_SELECT_VERTEX, "VERT", ICON_VERTEXSEL, "Vertices", ""},
938                 {SCE_SELECT_EDGE,   "EDGE", ICON_EDGESEL, "Edges", ""},
939                 {SCE_SELECT_FACE,   "FACE", ICON_FACESEL, "Faces", ""},
940                 {0, NULL, 0, NULL, NULL},
941         };
942
943         static EnumPropertyItem actions_items[] = {
944                 {0, "DISABLE", 0, "Disable", "Disable selected markers"},
945                 {1, "ENABLE", 0, "Enable", "Enable selected markers"},
946                 {2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
947                 {0, NULL, 0, NULL, NULL}
948         };
949
950         /* identifiers */
951         ot->name = "Select Mode";
952         ot->idname = "MESH_OT_select_mode";
953         ot->description = "Change selection mode";
954
955         /* api callbacks */
956         ot->invoke = edbm_select_mode_invoke;
957         ot->exec = edbm_select_mode_exec;
958         ot->poll = ED_operator_editmesh;
959
960         /* flags */
961         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
962
963         /* properties */
964         prop = RNA_def_boolean(ot->srna, "use_extend", FALSE, "Extend", "");
965         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
966         prop = RNA_def_boolean(ot->srna, "use_expand", FALSE, "Expand", "");
967         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
968         ot->prop = prop = RNA_def_enum(ot->srna, "type", elem_items, 0, "Type", "");
969         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
970
971         RNA_def_enum(ot->srna, "action", actions_items, 2, "Action", "Selection action to execute");
972 }
973
974 /* ***************************************************** */
975
976 /* ****************  LOOP SELECTS *************** */
977
978 static void walker_select(BMEditMesh *em, int walkercode, void *start, int select)
979 {
980         BMesh *bm = em->bm;
981         BMElem *ele;
982         BMWalker walker;
983
984         BMW_init(&walker, bm, walkercode,
985                  BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
986                  BMW_FLAG_TEST_HIDDEN,
987                  BMW_NIL_LAY);
988
989         for (ele = BMW_begin(&walker, start); ele; ele = BMW_step(&walker)) {
990                 if (!select) {
991                         BM_select_history_remove(bm, ele);
992                 }
993                 BM_elem_select_set(bm, ele, select);
994         }
995         BMW_end(&walker);
996 }
997
998 static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
999 {
1000         Object *obedit = CTX_data_edit_object(C);
1001         BMEditMesh *em = BMEdit_FromObject(obedit);
1002         BMEdge *eed;
1003         BMEdge **edarray;
1004         int edindex;
1005         int looptype = RNA_boolean_get(op->ptr, "ring");
1006         
1007         BMIter iter;
1008         int totedgesel = 0;
1009
1010         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1011                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1012                         totedgesel++;
1013                 }
1014         }
1015         
1016         edarray = MEM_mallocN(sizeof(BMEdge *) * totedgesel, "edge array");
1017         edindex = 0;
1018         
1019         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1020                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1021                         edarray[edindex] = eed;
1022                         edindex++;
1023                 }
1024         }
1025         
1026         if (looptype) {
1027                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
1028                         eed = edarray[edindex];
1029                         walker_select(em, BMW_EDGERING, eed, TRUE);
1030                 }
1031                 EDBM_selectmode_flush(em);
1032         }
1033         else {
1034                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
1035                         eed = edarray[edindex];
1036                         walker_select(em, BMW_LOOP, eed, TRUE);
1037                 }
1038                 EDBM_selectmode_flush(em);
1039         }
1040         MEM_freeN(edarray);
1041 //      if (EM_texFaceCheck())
1042         
1043         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
1044
1045         return OPERATOR_FINISHED;
1046 }
1047
1048 void MESH_OT_loop_multi_select(wmOperatorType *ot)
1049 {
1050         /* identifiers */
1051         ot->name = "Multi Select Loops";
1052         ot->idname = "MESH_OT_loop_multi_select";
1053         ot->description = "Select a loop of connected edges by connection type";
1054         
1055         /* api callbacks */
1056         ot->exec = edbm_loop_multiselect_exec;
1057         ot->poll = ED_operator_editmesh;
1058         
1059         /* flags */
1060         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1061         
1062         /* properties */
1063         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
1064 }
1065
1066                 
1067 /* ***************** MAIN MOUSE SELECTION ************** */
1068
1069
1070 /* ***************** loop select (non modal) ************** */
1071
1072 static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short deselect, short toggle, short ring)
1073 {
1074         ViewContext vc;
1075         BMEditMesh *em;
1076         BMEdge *eed;
1077         int select = TRUE;
1078         float dist = 50.0f;
1079         float mvalf[2];
1080
1081         em_setup_viewcontext(C, &vc);
1082         mvalf[0] = (float)(vc.mval[0] = mval[0]);
1083         mvalf[1] = (float)(vc.mval[1] = mval[1]);
1084         em = vc.em;
1085
1086         /* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
1087         view3d_validate_backbuf(&vc);
1088
1089         eed = EDBM_edge_find_nearest(&vc, &dist);
1090         if (eed) {
1091                 if (extend == 0 && deselect == 0 && toggle == 0) {
1092                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1093                 }
1094         
1095                 if (extend) {
1096                         select = TRUE;
1097                 }
1098                 else if (deselect) {
1099                         select = FALSE;
1100                 }
1101                 else if (BM_elem_flag_test(eed, BM_ELEM_SELECT) == 0) {
1102                         select = TRUE;
1103                 }
1104                 else if (toggle) {
1105                         select = FALSE;
1106                 }
1107
1108                 if (em->selectmode & SCE_SELECT_FACE) {
1109                         walker_select(em, BMW_FACELOOP, eed, select);
1110                 }
1111                 else if (em->selectmode & SCE_SELECT_EDGE) {
1112                         if (ring)
1113                                 walker_select(em, BMW_EDGERING, eed, select);
1114                         else
1115                                 walker_select(em, BMW_LOOP, eed, select);
1116                 }
1117                 else if (em->selectmode & SCE_SELECT_VERTEX) {
1118                         if (ring)
1119                                 walker_select(em, BMW_EDGERING, eed, select);
1120
1121                         else
1122                                 walker_select(em, BMW_LOOP, eed, select);
1123                 }
1124
1125                 EDBM_selectmode_flush(em);
1126
1127                 /* sets as active, useful for other tools */
1128                 if (select) {
1129                         if (em->selectmode & SCE_SELECT_VERTEX) {
1130                                 /* Find nearest vert from mouse
1131                                  * (initialize to large values incase only one vertex can be projected) */
1132                                 float v1_co[2], v2_co[2];
1133                                 float length_1 = FLT_MAX;
1134                                 float length_2 = FLT_MAX;
1135
1136                                 /* We can't be sure this has already been set... */
1137                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1138
1139                                 if (ED_view3d_project_float_object(vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1140                                         length_1 = len_squared_v2v2(mvalf, v1_co);
1141                                 }
1142
1143                                 if (ED_view3d_project_float_object(vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1144                                         length_2 = len_squared_v2v2(mvalf, v2_co);
1145                                 }
1146 #if 0
1147                                 printf("mouse to v1: %f\nmouse to v2: %f\n", len_squared_v2v2(mvalf, v1_co),
1148                                        len_squared_v2v2(mvalf, v2_co));
1149 #endif
1150                                 BM_select_history_store(em->bm, (length_1 < length_2) ? eed->v1 : eed->v2);
1151                         }
1152                         else if (em->selectmode & SCE_SELECT_EDGE) {
1153                                 BM_select_history_store(em->bm, eed);
1154                         }
1155                         else if (em->selectmode & SCE_SELECT_FACE) {
1156                                 /* Select the face of eed which is the nearest of mouse. */
1157                                 BMFace *f, *efa = NULL;
1158                                 BMIter iterf;
1159                                 float best_dist = MAXFLOAT;
1160
1161                                 /* We can't be sure this has already been set... */
1162                                 ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
1163
1164                                 BM_ITER_ELEM(f, &iterf, eed, BM_FACES_OF_EDGE) {
1165                                         if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1166                                                 float cent[3];
1167                                                 float co[2], tdist;
1168
1169                                                 BM_face_calc_center_mean(f, cent);
1170                                                 if (ED_view3d_project_float_object(vc.ar, cent, co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
1171                                                         tdist = len_squared_v2v2(mvalf, co);
1172                                                         if (tdist < best_dist) {
1173 /*                                                              printf("Best face: %p (%f)\n", f, tdist);*/
1174                                                                 best_dist = tdist;
1175                                                                 efa = f;
1176                                                         }
1177                                                 }
1178                                         }
1179                                 }
1180                                 if (efa) {
1181                                         BM_active_face_set(em->bm, efa);
1182                                         BM_select_history_store(em->bm, efa);
1183                                 }
1184                         }
1185                 }
1186
1187                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1188         }
1189 }
1190
1191 static int edbm_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
1192 {
1193         
1194         view3d_operator_needs_opengl(C);
1195         
1196         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
1197                         RNA_boolean_get(op->ptr, "deselect"),
1198                         RNA_boolean_get(op->ptr, "toggle"),
1199                         RNA_boolean_get(op->ptr, "ring"));
1200         
1201         /* cannot do tweaks for as long this keymap is after transform map */
1202         return OPERATOR_FINISHED;
1203 }
1204
1205 void MESH_OT_loop_select(wmOperatorType *ot)
1206 {
1207         /* identifiers */
1208         ot->name = "Loop Select";
1209         ot->idname = "MESH_OT_loop_select";
1210         ot->description = "Select a loop of connected edges";
1211         
1212         /* api callbacks */
1213         ot->invoke = edbm_select_loop_invoke;
1214         ot->poll = ED_operator_editmesh_region_view3d;
1215         
1216         /* flags */
1217         ot->flag = OPTYPE_UNDO;
1218         
1219         /* properties */
1220         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
1221         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from the selection");
1222         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle Select", "Toggle the selection");
1223         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "Select ring");
1224 }
1225
1226 void MESH_OT_edgering_select(wmOperatorType *ot)
1227 {
1228         /* description */
1229         ot->name = "Edge Ring Select";
1230         ot->idname = "MESH_OT_edgering_select";
1231         ot->description = "Select an edge ring";
1232         
1233         /* callbacks */
1234         ot->invoke = edbm_select_loop_invoke;
1235         ot->poll = ED_operator_editmesh_region_view3d;
1236         
1237         /* flags */
1238         ot->flag = OPTYPE_UNDO;
1239
1240         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the selection");
1241         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from the selection");
1242         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle Select", "Toggle the selection");
1243         RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
1244 }
1245
1246 /* ******************* generic tag_shortest_path and helpers ****************** */
1247
1248 static float step_cost_3_v3(const float v1[3], const float v2[3], const float v3[3])
1249 {
1250         float cost, d1[3], d2[3];
1251
1252
1253         /* The cost is based on the simple sum of the length of the two edgees... */
1254         sub_v3_v3v3(d1, v2, v1);
1255         sub_v3_v3v3(d2, v3, v2);
1256         cost = normalize_v3(d1) + normalize_v3(d2);
1257
1258         /* but is biased to give higher values to sharp turns, so that it will take
1259          * paths with fewer "turns" when selecting between equal-weighted paths between
1260          * the two edges */
1261         cost = cost * (1.0f + 0.5f * (2.0f - sqrtf(fabsf(dot_v3v3(d1, d2)))));
1262
1263         return cost;
1264 }
1265
1266 /* ******************* edgetag_shortest_path and helpers ****************** */
1267
1268 static float edgetag_cut_cost(BMEdge *e1, BMEdge *e2, BMVert *v)
1269 {
1270         BMVert *v1 = BM_edge_other_vert(e1, v);
1271         BMVert *v2 = BM_edge_other_vert(e2, v);
1272         return step_cost_3_v3(v1->co, v->co, v2->co);
1273 }
1274
1275 static void edgetag_add_adjacent(Heap *heap, BMEdge *e1, BMEdge **edges_prev, float *cost)
1276 {
1277         BMIter viter;
1278         BMVert *v;
1279
1280         BMIter eiter;
1281         BMEdge *e2;
1282
1283         const int e1_index = BM_elem_index_get(e1);
1284
1285         BM_ITER_ELEM (v, &viter, e1, BM_VERTS_OF_EDGE) {
1286                 BM_ITER_ELEM (e2, &eiter, v, BM_EDGES_OF_VERT) {
1287                         if (!BM_elem_flag_test(e2, BM_ELEM_TAG)) {
1288                                 /* we know 'e2' is not visited, check it out! */
1289                                 const int e2_index = BM_elem_index_get(e2);
1290                                 const float cost_cut = edgetag_cut_cost(e1, e2, v);
1291                                 const float cost_new = cost[e1_index] + cost_cut;
1292
1293                                 if (cost[e2_index] > cost_new) {
1294                                         cost[e2_index] = cost_new;
1295                                         edges_prev[e2_index] = e1;
1296                                         BLI_heap_insert(heap, cost_new, e2);
1297                                 }
1298                         }
1299                 }
1300         }
1301 }
1302
1303 static void edgetag_context_set(BMesh *bm, Scene *scene, BMEdge *e, int val)
1304 {
1305         
1306         switch (scene->toolsettings->edge_mode) {
1307                 case EDGE_MODE_SELECT:
1308                         BM_edge_select_set(bm, e, val);
1309                         break;
1310                 case EDGE_MODE_TAG_SEAM:
1311                         BM_elem_flag_set(e, BM_ELEM_SEAM, val);
1312                         break;
1313                 case EDGE_MODE_TAG_SHARP:
1314                         BM_elem_flag_set(e, BM_ELEM_SMOOTH, !val);
1315                         break;
1316                 case EDGE_MODE_TAG_CREASE:
1317                         BM_elem_float_data_set(&bm->edata, e, CD_CREASE, (val) ? 1.0f : 0.0f);
1318                         break;
1319                 case EDGE_MODE_TAG_BEVEL:
1320                         BM_elem_float_data_set(&bm->edata, e, CD_BWEIGHT, (val) ? 1.0f : 0.0f);
1321                         break;
1322         }
1323 }
1324
1325 static int edgetag_context_check(Scene *scene, BMesh *bm, BMEdge *e)
1326 {
1327         switch (scene->toolsettings->edge_mode) {
1328                 case EDGE_MODE_SELECT:
1329                         return BM_elem_flag_test(e, BM_ELEM_SELECT) ? TRUE : FALSE;
1330                 case EDGE_MODE_TAG_SEAM:
1331                         return BM_elem_flag_test(e, BM_ELEM_SEAM);
1332                 case EDGE_MODE_TAG_SHARP:
1333                         return !BM_elem_flag_test(e, BM_ELEM_SMOOTH);
1334                 case EDGE_MODE_TAG_CREASE:
1335                         return BM_elem_float_data_get(&bm->edata, e, CD_CREASE) ? TRUE : FALSE;
1336                 case EDGE_MODE_TAG_BEVEL:
1337                         return BM_elem_float_data_get(&bm->edata, e, CD_BWEIGHT) ? TRUE : FALSE;
1338         }
1339         return 0;
1340 }
1341
1342 static int edgetag_shortest_path(Scene *scene, BMesh *bm, BMEdge *e_src, BMEdge *e_dst)
1343 {
1344         /* BM_ELEM_TAG flag is used to store visited edges */
1345         BMEdge *e;
1346         BMIter eiter;
1347         Heap *heap;
1348         float *cost;
1349         BMEdge **edges_prev;
1350         int i, totedge;
1351
1352         /* note, would pass BM_EDGE except we are looping over all edges anyway */
1353         BM_mesh_elem_index_ensure(bm, BM_VERT /* | BM_EDGE */);
1354
1355         switch (scene->toolsettings->edge_mode) {
1356                 case EDGE_MODE_TAG_CREASE:
1357                         BM_mesh_cd_flag_ensure(bm, BKE_mesh_from_object(OBACT), ME_CDFLAG_EDGE_CREASE);
1358                         break;
1359                 case EDGE_MODE_TAG_BEVEL:
1360                         BM_mesh_cd_flag_ensure(bm, BKE_mesh_from_object(OBACT), ME_CDFLAG_EDGE_BWEIGHT);
1361                         break;
1362                 default:
1363                         break;
1364         }
1365
1366         BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
1367                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) == FALSE) {
1368                         BM_elem_flag_disable(e, BM_ELEM_TAG);
1369                 }
1370                 else {
1371                         BM_elem_flag_enable(e, BM_ELEM_TAG);
1372                 }
1373
1374                 BM_elem_index_set(e, i); /* set_inline */
1375         }
1376         bm->elem_index_dirty &= ~BM_EDGE;
1377
1378         /* alloc */
1379         totedge = bm->totedge;
1380         edges_prev = MEM_callocN(sizeof(*edges_prev) * totedge, "SeamPathPrevious");
1381         cost = MEM_mallocN(sizeof(*cost) * totedge, "SeamPathCost");
1382
1383         fill_vn_fl(cost, totedge, 1e20f);
1384
1385         /*
1386          * Arrays are now filled as follows:
1387          *
1388          * As the search continues, prevedge[n] will be the previous edge on the shortest
1389          * path found so far to edge n. The visitedhash will of course contain entries
1390          * for edges that have been visited, cost[n] will contain the length of the shortest
1391          * path to edge n found so far, Finally, heap is a priority heap which is built on the
1392          * the same data as the cost array, but inverted: it is a worklist of edges prioritized
1393          * by the shortest path found so far to the edge.
1394          */
1395
1396         /* regular dijkstra shortest path, but over edges instead of vertices */
1397         heap = BLI_heap_new();
1398         BLI_heap_insert(heap, 0.0f, e_src);
1399         cost[BM_elem_index_get(e_src)] = 0.0f;
1400
1401         e = NULL;
1402
1403         while (!BLI_heap_is_empty(heap)) {
1404                 e = BLI_heap_popmin(heap);
1405
1406                 if (e == e_dst)
1407                         break;
1408
1409                 if (!BM_elem_flag_test(e, BM_ELEM_TAG)) {
1410                         BM_elem_flag_enable(e, BM_ELEM_TAG);
1411                         edgetag_add_adjacent(heap, e, edges_prev, cost);
1412                 }
1413         }
1414         
1415         if (e == e_dst) {
1416                 short all_set = TRUE;
1417
1418                 /* Check whether the path is already completely tagged.
1419                  * if it is, the tags will be cleared instead of set. */
1420                 e = e_dst;
1421                 do {
1422                         if (!edgetag_context_check(scene, bm, e)) {
1423                                 all_set = FALSE;
1424                                 break;
1425                         }
1426                 } while ((e = edges_prev[BM_elem_index_get(e)]));
1427
1428                 /* Follow path back and source and add or remove tags */
1429                 e = e_dst;
1430                 do {
1431                         edgetag_context_set(bm, scene, e, !all_set);
1432                 } while ((e = edges_prev[BM_elem_index_get(e)]));
1433         }
1434
1435         MEM_freeN(edges_prev);
1436         MEM_freeN(cost);
1437         BLI_heap_free(heap, NULL);
1438
1439         return 1;
1440 }
1441
1442 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
1443
1444 /* since you want to create paths with multiple selects, it doesn't have extend option */
1445 static int mouse_mesh_shortest_path_edge(ViewContext *vc)
1446 {
1447         BMEditMesh *em = vc->em;
1448         BMEdge *e_dst;
1449         float dist = 75.0f;
1450         
1451         e_dst = EDBM_edge_find_nearest(vc, &dist);
1452         if (e_dst) {
1453                 Mesh *me = vc->obedit->data;
1454                 int path = 0;
1455                 
1456                 if (em->bm->selected.last) {
1457                         BMEditSelection *ese = em->bm->selected.last;
1458                         
1459                         if (ese && ese->htype == BM_EDGE) {
1460                                 BMEdge *e_act;
1461                                 e_act = (BMEdge *)ese->ele;
1462                                 if (e_act != e_dst) {
1463                                         if (edgetag_shortest_path(vc->scene, em->bm, e_act, e_dst)) {
1464                                                 BM_select_history_remove(em->bm, e_act);
1465                                                 path = 1;
1466                                         }
1467                                 }
1468                         }
1469                 }
1470                 if (path == 0) {
1471                         int act = (edgetag_context_check(vc->scene, em->bm, e_dst) == 0);
1472                         edgetag_context_set(em->bm, vc->scene, e_dst, act); /* switch the edge option */
1473                 }
1474                 
1475                 EDBM_selectmode_flush(em);
1476
1477                 /* even if this is selected it may not be in the selection list */
1478                 if (edgetag_context_check(vc->scene, em->bm, e_dst) == 0)
1479                         BM_select_history_remove(em->bm, e_dst);
1480                 else
1481                         BM_select_history_store(em->bm, e_dst);
1482         
1483                 /* force drawmode for mesh */
1484                 switch (vc->scene->toolsettings->edge_mode) {
1485                         
1486                         case EDGE_MODE_TAG_SEAM:
1487                                 me->drawflag |= ME_DRAWSEAMS;
1488                                 ED_uvedit_live_unwrap(vc->scene, vc->obedit);
1489                                 break;
1490                         case EDGE_MODE_TAG_SHARP:
1491                                 me->drawflag |= ME_DRAWSHARP;
1492                                 break;
1493                         case EDGE_MODE_TAG_CREASE:
1494                                 me->drawflag |= ME_DRAWCREASES;
1495                                 break;
1496                         case EDGE_MODE_TAG_BEVEL:
1497                                 me->drawflag |= ME_DRAWBWEIGHTS;
1498                                 break;
1499                 }
1500                 
1501                 EDBM_update_generic(em, FALSE, FALSE);
1502
1503                 return TRUE;
1504         }
1505         else {
1506                 return FALSE;
1507         }
1508 }
1509
1510
1511 /* ******************* facetag_shortest_path and helpers ****************** */
1512
1513
1514 static float facetag_cut_cost(BMFace *f1, BMFace *f2, BMEdge *e)
1515 {
1516         float f1_cent[3];
1517         float f2_cent[3];
1518         float e_cent[3];
1519
1520         BM_face_calc_center_mean(f1, f1_cent);
1521         BM_face_calc_center_mean(f2, f2_cent);
1522         mid_v3_v3v3(e_cent, e->v1->co, e->v2->co);
1523
1524         return step_cost_3_v3(f1_cent, e_cent, f2_cent);
1525 }
1526
1527 static void facetag_add_adjacent(Heap *heap, BMFace *f1, BMFace **faces_prev, float *cost)
1528 {
1529         BMIter liter;
1530         BMLoop *l2;
1531         BMFace *f2;
1532
1533         const int f1_index = BM_elem_index_get(f1);
1534
1535         /* loop over faces of face, but do so by first looping over loops */
1536         BM_ITER_ELEM (l2, &liter, f1, BM_LOOPS_OF_FACE) {
1537                 BMLoop *l_first;
1538                 BMLoop *l_iter;
1539
1540                 l_iter = l_first = l2;
1541                 do {
1542                         f2 = l_iter->f;
1543                         if (!BM_elem_flag_test(f2, BM_ELEM_TAG)) {
1544                                 /* we know 'f2' is not visited, check it out! */
1545                                 const int f2_index = BM_elem_index_get(f2);
1546                                 const float cost_cut = facetag_cut_cost(f1, f2, l_iter->e);
1547                                 const float cost_new = cost[f1_index] + cost_cut;
1548
1549                                 if (cost[f2_index] > cost_new) {
1550                                         cost[f2_index] = cost_new;
1551                                         faces_prev[f2_index] = f1;
1552                                         BLI_heap_insert(heap, cost_new, f2);
1553                                 }
1554                         }
1555                 } while ((l_iter = l_iter->radial_next) != l_first);
1556         }
1557 }
1558
1559 static void facetag_context_set(BMesh *bm, Scene *UNUSED(scene), BMFace *f, int val)
1560 {
1561         BM_face_select_set(bm, f, val);
1562 }
1563
1564 static int facetag_context_check(Scene *UNUSED(scene), BMesh *UNUSED(bm), BMFace *f)
1565 {
1566         return BM_elem_flag_test(f, BM_ELEM_SELECT) ? 1 : 0;
1567 }
1568
1569 static int facetag_shortest_path(Scene *scene, BMesh *bm, BMFace *f_src, BMFace *f_dst)
1570 {
1571         /* BM_ELEM_TAG flag is used to store visited edges */
1572         BMFace *f;
1573         BMIter fiter;
1574         Heap *heap;
1575         float *cost;
1576         BMFace **faces_prev;
1577         int i, totface;
1578
1579         /* note, would pass BM_EDGE except we are looping over all faces anyway */
1580         // BM_mesh_elem_index_ensure(bm, BM_VERT /* | BM_EDGE */); // NOT NEEDED FOR FACETAG
1581
1582         BM_ITER_MESH_INDEX (f, &fiter, bm, BM_FACES_OF_MESH, i) {
1583                 if (BM_elem_flag_test(f, BM_ELEM_HIDDEN) == FALSE) {
1584                         BM_elem_flag_disable(f, BM_ELEM_TAG);
1585                 }
1586                 else {
1587                         BM_elem_flag_enable(f, BM_ELEM_TAG);
1588                 }
1589
1590                 BM_elem_index_set(f, i); /* set_inline */
1591         }
1592         bm->elem_index_dirty &= ~BM_FACE;
1593
1594         /* alloc */
1595         totface = bm->totface;
1596         faces_prev = MEM_callocN(sizeof(*faces_prev) * totface, "SeamPathPrevious");
1597         cost = MEM_mallocN(sizeof(*cost) * totface, "SeamPathCost");
1598
1599         fill_vn_fl(cost, totface, 1e20f);
1600
1601         /*
1602          * Arrays are now filled as follows:
1603          *
1604          * As the search continues, faces_prev[n] will be the previous face on the shortest
1605          * path found so far to face n. The visitedhash will of course contain entries
1606          * for faces that have been visited, cost[n] will contain the length of the shortest
1607          * path to face n found so far, Finally, heap is a priority heap which is built on the
1608          * the same data as the cost array, but inverted: it is a worklist of faces prioritized
1609          * by the shortest path found so far to the face.
1610          */
1611
1612         /* regular dijkstra shortest path, but over faces instead of vertices */
1613         heap = BLI_heap_new();
1614         BLI_heap_insert(heap, 0.0f, f_src);
1615         cost[BM_elem_index_get(f_src)] = 0.0f;
1616
1617         f = NULL;
1618
1619         while (!BLI_heap_is_empty(heap)) {
1620                 f = BLI_heap_popmin(heap);
1621
1622                 if (f == f_dst)
1623                         break;
1624
1625                 if (!BM_elem_flag_test(f, BM_ELEM_TAG)) {
1626                         BM_elem_flag_enable(f, BM_ELEM_TAG);
1627                         facetag_add_adjacent(heap, f, faces_prev, cost);
1628                 }
1629         }
1630
1631         if (f == f_dst) {
1632                 short all_set = TRUE;
1633
1634                 /* Check whether the path is already completely tagged.
1635                  * if it is, the tags will be cleared instead of set. */
1636                 f = f_dst;
1637                 do {
1638                         if (!facetag_context_check(scene, bm, f)) {
1639                                 all_set = FALSE;
1640                                 break;
1641                         }
1642                 } while ((f = faces_prev[BM_elem_index_get(f)]));
1643
1644                 /* Follow path back and source and add or remove tags */
1645                 f = f_dst;
1646                 do {
1647                         facetag_context_set(bm, scene, f, !all_set);
1648                 } while ((f = faces_prev[BM_elem_index_get(f)]));
1649         }
1650
1651         MEM_freeN(faces_prev);
1652         MEM_freeN(cost);
1653         BLI_heap_free(heap, NULL);
1654
1655         return 1;
1656 }
1657
1658 static int mouse_mesh_shortest_path_face(ViewContext *vc)
1659 {
1660         BMEditMesh *em = vc->em;
1661         BMFace *f_dst;
1662         float dist = 75.0f;
1663
1664         f_dst = EDBM_face_find_nearest(vc, &dist);
1665         if (f_dst) {
1666                 int path = 0;
1667                 BMFace *f_act = BM_active_face_get(em->bm, FALSE, TRUE);
1668
1669                 if (f_act) {
1670                         if (f_act != f_dst) {
1671                                 if (facetag_shortest_path(vc->scene, em->bm, f_act, f_dst)) {
1672                                         BM_select_history_remove(em->bm, f_act);
1673                                         path = 1;
1674                                 }
1675                         }
1676                 }
1677                 if (path == 0) {
1678                         int act = (facetag_context_check(vc->scene, em->bm, f_dst) == 0);
1679                         facetag_context_set(em->bm, vc->scene, f_dst, act); /* switch the face option */
1680                 }
1681
1682                 EDBM_selectmode_flush(em);
1683
1684                 /* even if this is selected it may not be in the selection list */
1685                 if (facetag_context_check(vc->scene, em->bm, f_dst) == 0)
1686                         BM_select_history_remove(em->bm, f_dst);
1687                 else
1688                         BM_select_history_store(em->bm, f_dst);
1689
1690                 BM_active_face_set(em->bm, f_dst);
1691
1692                 EDBM_update_generic(em, FALSE, FALSE);
1693
1694                 return TRUE;
1695         }
1696         else {
1697                 return FALSE;
1698         }
1699 }
1700
1701
1702 /* ******************* operator for edge and face tag ****************** */
1703
1704 static int edbm_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1705 {
1706         ViewContext vc;
1707         BMEditMesh *em;
1708
1709         view3d_operator_needs_opengl(C);
1710
1711         em_setup_viewcontext(C, &vc);
1712         vc.mval[0] = event->mval[0];
1713         vc.mval[1] = event->mval[1];
1714         em = vc.em;
1715
1716         if (em->selectmode & SCE_SELECT_EDGE) {
1717                 if (mouse_mesh_shortest_path_edge(&vc)) {
1718                         return OPERATOR_FINISHED;
1719                 }
1720                 else {
1721                         return OPERATOR_PASS_THROUGH;
1722                 }
1723         }
1724         else if (em->selectmode & SCE_SELECT_FACE) {
1725                 if (mouse_mesh_shortest_path_face(&vc)) {
1726                         return OPERATOR_FINISHED;
1727                 }
1728                 else {
1729                         return OPERATOR_PASS_THROUGH;
1730                 }
1731         }
1732
1733         return OPERATOR_PASS_THROUGH;
1734 }
1735
1736 static int edbm_shortest_path_select_poll(bContext *C)
1737 {
1738         if (ED_operator_editmesh_region_view3d(C)) {
1739                 Object *obedit = CTX_data_edit_object(C);
1740                 BMEditMesh *em = BMEdit_FromObject(obedit);
1741                 return (em->selectmode & (SCE_SELECT_EDGE | SCE_SELECT_FACE)) != 0;
1742         }
1743         return 0;
1744 }
1745
1746 void MESH_OT_select_shortest_path(wmOperatorType *ot)
1747 {
1748         /* identifiers */
1749         ot->name = "Shortest Path Select";
1750         ot->idname = "MESH_OT_select_shortest_path";
1751         ot->description = "Select shortest path between two selections";
1752         
1753         /* api callbacks */
1754         ot->invoke = edbm_shortest_path_select_invoke;
1755         ot->poll = edbm_shortest_path_select_poll;
1756         
1757         /* flags */
1758         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1759         
1760         /* properties */
1761         RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
1762 }
1763
1764 /* ************************************************** */
1765 /* here actual select happens */
1766 /* gets called via generic mouse select operator */
1767 int EDBM_select_pick(bContext *C, const int mval[2], short extend, short deselect, short toggle)
1768 {
1769         ViewContext vc;
1770         BMVert *eve = NULL;
1771         BMEdge *eed = NULL;
1772         BMFace *efa = NULL;
1773
1774         /* setup view context for argument to callbacks */
1775         em_setup_viewcontext(C, &vc);
1776         vc.mval[0] = mval[0];
1777         vc.mval[1] = mval[1];
1778
1779         if (unified_findnearest(&vc, &eve, &eed, &efa)) {
1780
1781                 /* Deselect everything */
1782                 if (extend == 0 && deselect == 0 && toggle == 0)
1783                         EDBM_flag_disable_all(vc.em, BM_ELEM_SELECT);
1784
1785                 if (efa) {
1786                         if (extend) {
1787                                 /* set the last selected face */
1788                                 BM_active_face_set(vc.em->bm, efa);
1789
1790                                 /* Work-around: deselect first, so we can guarantee it will */
1791                                 /* be active even if it was already selected */
1792                                 BM_select_history_remove(vc.em->bm, efa);
1793                                 BM_face_select_set(vc.em->bm, efa, FALSE);
1794                                 BM_select_history_store(vc.em->bm, efa);
1795                                 BM_face_select_set(vc.em->bm, efa, TRUE);
1796                         }
1797                         else if (deselect) {
1798                                 BM_select_history_remove(vc.em->bm, efa);
1799                                 BM_face_select_set(vc.em->bm, efa, FALSE);
1800                         }
1801                         else {
1802                                 /* set the last selected face */
1803                                 BM_active_face_set(vc.em->bm, efa);
1804
1805                                 if (!BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1806                                         BM_select_history_store(vc.em->bm, efa);
1807                                         BM_face_select_set(vc.em->bm, efa, TRUE);
1808                                 }
1809                                 else if (toggle) {
1810                                         BM_select_history_remove(vc.em->bm, efa);
1811                                         BM_face_select_set(vc.em->bm, efa, FALSE);
1812                                 }
1813                         }
1814                 }
1815                 else if (eed) {
1816                         if (extend) {
1817                                 /* Work-around: deselect first, so we can guarantee it will */
1818                                 /* be active even if it was already selected */
1819                                 BM_select_history_remove(vc.em->bm, eed);
1820                                 BM_edge_select_set(vc.em->bm, eed, FALSE);
1821                                 BM_select_history_store(vc.em->bm, eed);
1822                                 BM_edge_select_set(vc.em->bm, eed, TRUE);
1823                         }
1824                         else if (deselect) {
1825                                 BM_select_history_remove(vc.em->bm, eed);
1826                                 BM_edge_select_set(vc.em->bm, eed, FALSE);
1827                         }
1828                         else {
1829                                 if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1830                                         BM_select_history_store(vc.em->bm, eed);
1831                                         BM_edge_select_set(vc.em->bm, eed, TRUE);
1832                                 }
1833                                 else if (toggle) {
1834                                         BM_select_history_remove(vc.em->bm, eed);
1835                                         BM_edge_select_set(vc.em->bm, eed, FALSE);
1836                                 }
1837                         }
1838                 }
1839                 else if (eve) {
1840                         if (extend) {
1841                                 /* Work-around: deselect first, so we can guarantee it will */
1842                                 /* be active even if it was already selected */
1843                                 BM_select_history_remove(vc.em->bm, eve);
1844                                 BM_vert_select_set(vc.em->bm, eve, FALSE);
1845                                 BM_select_history_store(vc.em->bm, eve);
1846                                 BM_vert_select_set(vc.em->bm, eve, TRUE);
1847                         }
1848                         else if (deselect) {
1849                                 BM_select_history_remove(vc.em->bm, eve);
1850                                 BM_vert_select_set(vc.em->bm, eve, FALSE);
1851                         }
1852                         else {
1853                                 if (!BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
1854                                         BM_select_history_store(vc.em->bm, eve);
1855                                         BM_vert_select_set(vc.em->bm, eve, TRUE);
1856                                 }
1857                                 else if (toggle) {
1858                                         BM_select_history_remove(vc.em->bm, eve);
1859                                         BM_vert_select_set(vc.em->bm, eve, FALSE);
1860                                 }
1861                         }
1862                 }
1863
1864                 EDBM_selectmode_flush(vc.em);
1865
1866                 /* change active material on object */
1867                 if (efa && efa->mat_nr != vc.obedit->actcol - 1) {
1868                         vc.obedit->actcol = efa->mat_nr + 1;
1869                         vc.em->mat_nr = efa->mat_nr;
1870
1871                         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, NULL);
1872
1873                 }
1874
1875                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
1876                 return 1;
1877         }
1878
1879         return 0;
1880 }
1881
1882 static void edbm_strip_selections(BMEditMesh *em)
1883 {
1884         BMEditSelection *ese, *nextese;
1885
1886         if (!(em->selectmode & SCE_SELECT_VERTEX)) {
1887                 ese = em->bm->selected.first;
1888                 while (ese) {
1889                         nextese = ese->next;
1890                         if (ese->htype == BM_VERT) BLI_freelinkN(&(em->bm->selected), ese);
1891                         ese = nextese;
1892                 }
1893         }
1894         if (!(em->selectmode & SCE_SELECT_EDGE)) {
1895                 ese = em->bm->selected.first;
1896                 while (ese) {
1897                         nextese = ese->next;
1898                         if (ese->htype == BM_EDGE) BLI_freelinkN(&(em->bm->selected), ese);
1899                         ese = nextese;
1900                 }
1901         }
1902         if (!(em->selectmode & SCE_SELECT_FACE)) {
1903                 ese = em->bm->selected.first;
1904                 while (ese) {
1905                         nextese = ese->next;
1906                         if (ese->htype == BM_FACE) BLI_freelinkN(&(em->bm->selected), ese);
1907                         ese = nextese;
1908                 }
1909         }
1910 }
1911
1912 /* when switching select mode, makes sure selection is consistent for editing */
1913 /* also for paranoia checks to make sure edge or face mode works */
1914 void EDBM_selectmode_set(BMEditMesh *em)
1915 {
1916         BMVert *eve;
1917         BMEdge *eed;
1918         BMFace *efa;
1919         BMIter iter;
1920         
1921         em->bm->selectmode = em->selectmode;
1922
1923         edbm_strip_selections(em); /* strip BMEditSelections from em->selected that are not relevant to new mode */
1924         
1925         if (em->selectmode & SCE_SELECT_VERTEX) {
1926                 EDBM_select_flush(em);
1927         }
1928         else if (em->selectmode & SCE_SELECT_EDGE) {
1929                 /* deselect vertices, and select again based on edge select */
1930                 eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1931                 for (; eve; eve = BM_iter_step(&iter)) BM_vert_select_set(em->bm, eve, FALSE);
1932                 
1933                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1934                 for (; eed; eed = BM_iter_step(&iter)) {
1935                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1936                                 BM_edge_select_set(em->bm, eed, TRUE);
1937                         }
1938                 }
1939                 
1940                 /* selects faces based on edge status */
1941                 EDBM_selectmode_flush(em);
1942         }
1943         else if (em->selectmode & SCE_SELECT_FACE) {
1944                 /* deselect eges, and select again based on face select */
1945                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1946                 for (; eed; eed = BM_iter_step(&iter)) BM_edge_select_set(em->bm, eed, FALSE);
1947                 
1948                 efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1949                 for (; efa; efa = BM_iter_step(&iter)) {
1950                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1951                                 BM_face_select_set(em->bm, efa, TRUE);
1952                         }
1953                 }
1954         }
1955 }
1956
1957 void EDBM_selectmode_convert(BMEditMesh *em, const short selectmode_old, const short selectmode_new)
1958 {
1959         BMEdge *eed;
1960         BMFace *efa;
1961         BMIter iter;
1962
1963         /* first tag-to-select, then select --- this avoids a feedback loop */
1964
1965         /* have to find out what the selectionmode was previously */
1966         if (selectmode_old == SCE_SELECT_VERTEX) {
1967                 if (selectmode_new == SCE_SELECT_EDGE) {
1968                         /* select all edges associated with every selected vert */
1969                         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1970                                 BM_elem_flag_set(eed, BM_ELEM_TAG, BM_edge_is_any_vert_flag_test(eed, BM_ELEM_SELECT));
1971                         }
1972
1973                         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1974                                 if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1975                                         BM_edge_select_set(em->bm, eed, TRUE);
1976                                 }
1977                         }
1978                 }
1979                 else if (selectmode_new == SCE_SELECT_FACE) {
1980                         /* select all faces associated with every selected vert */
1981                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1982                                 BM_elem_flag_set(efa, BM_ELEM_TAG, BM_face_is_any_vert_flag_test(efa, BM_ELEM_SELECT));
1983                         }
1984
1985                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1986                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1987                                         BM_face_select_set(em->bm, efa, TRUE);
1988                                 }
1989                         }
1990                 }
1991         }
1992         else if (selectmode_old == SCE_SELECT_EDGE) {
1993                 if (selectmode_new == SCE_SELECT_FACE) {
1994                         /* select all faces associated with every selected edge */
1995                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1996                                 BM_elem_flag_set(efa, BM_ELEM_TAG, BM_face_is_any_edge_flag_test(efa, BM_ELEM_SELECT));
1997                         }
1998
1999                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2000                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2001                                         BM_face_select_set(em->bm, efa, TRUE);
2002                                 }
2003                         }
2004                 }
2005         }
2006 }
2007
2008 /* user facing function, does notification and undo push */
2009 int EDBM_selectmode_toggle(bContext *C, const short selectmode_new,
2010                            const int action, const int use_extend, const int use_expand)
2011 {
2012         ToolSettings *ts = CTX_data_tool_settings(C);
2013         Object *obedit = CTX_data_edit_object(C);
2014         BMEditMesh *em = NULL;
2015         int ret = FALSE;
2016
2017         if (obedit && obedit->type == OB_MESH) {
2018                 em = BMEdit_FromObject(obedit);
2019         }
2020
2021         if (em == NULL) {
2022                 return ret;
2023         }
2024
2025         switch (action) {
2026                 case -1:
2027                         /* already set */
2028                         break;
2029                 case 0:  /* disable */
2030                         /* check we have something to do */
2031                         if ((em->selectmode & selectmode_new) == 0) {
2032                                 return FALSE;
2033                         }
2034                         em->selectmode &= ~selectmode_new;
2035                         break;
2036                 case 1:  /* enable */
2037                         /* check we have something to do */
2038                         if ((em->selectmode & selectmode_new) != 0) {
2039                                 return FALSE;
2040                         }
2041                         em->selectmode |= selectmode_new;
2042                         break;
2043                 case 2:  /* toggle */
2044                         /* can't disable this flag if its the only one set */
2045                         if (em->selectmode == selectmode_new) {
2046                                 return FALSE;
2047                         }
2048                         em->selectmode ^= selectmode_new;
2049                         break;
2050                 default:
2051                         BLI_assert(0);
2052         }
2053
2054         switch (selectmode_new) {
2055                 case SCE_SELECT_VERTEX:
2056                         if (use_extend == 0 || em->selectmode == 0)
2057                                 em->selectmode = SCE_SELECT_VERTEX;
2058                         ts->selectmode = em->selectmode;
2059                         EDBM_selectmode_set(em);
2060                         ret = TRUE;
2061                         break;
2062                 case SCE_SELECT_EDGE:
2063                         if (use_extend == 0 || em->selectmode == 0) {
2064                                 if (use_expand) {
2065                                         const short selmode_max = highest_order_bit_s(ts->selectmode);
2066                                         if (selmode_max == SCE_SELECT_VERTEX) {
2067                                                 EDBM_selectmode_convert(em, selmode_max, SCE_SELECT_EDGE);
2068                                         }
2069                                 }
2070                                 em->selectmode = SCE_SELECT_EDGE;
2071                         }
2072                         ts->selectmode = em->selectmode;
2073                         EDBM_selectmode_set(em);
2074                         ret = TRUE;
2075                         break;
2076                 case SCE_SELECT_FACE:
2077                         if (use_extend == 0 || em->selectmode == 0) {
2078                                 if (use_expand) {
2079                                         const short selmode_max = highest_order_bit_s(ts->selectmode);
2080                                         if (ELEM(selmode_max, SCE_SELECT_VERTEX, SCE_SELECT_EDGE)) {
2081                                                 EDBM_selectmode_convert(em, selmode_max, SCE_SELECT_FACE);
2082                                         }
2083                                 }
2084
2085                                 em->selectmode = SCE_SELECT_FACE;
2086                         }
2087                         ts->selectmode = em->selectmode;
2088                         EDBM_selectmode_set(em);
2089                         ret = TRUE;
2090                         break;
2091                 default:
2092                         BLI_assert(0);
2093                         break;
2094         }
2095
2096         if (ret == TRUE) {
2097                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2098                 WM_main_add_notifier(NC_SCENE | ND_TOOLSETTINGS, NULL);
2099         }
2100
2101         return ret;
2102 }
2103
2104 void EDBM_deselect_by_material(BMEditMesh *em, const short index, const short select)
2105 {
2106         BMIter iter;
2107         BMFace *efa;
2108
2109         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2110                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
2111                         continue;
2112                 if (efa->mat_nr == index) {
2113                         BM_face_select_set(em->bm, efa, select);
2114                 }
2115         }
2116 }
2117
2118 void EDBM_select_toggle_all(BMEditMesh *em) /* exported for UV */
2119 {
2120         if (em->bm->totvertsel || em->bm->totedgesel || em->bm->totfacesel)
2121                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2122         else
2123                 EDBM_flag_enable_all(em, BM_ELEM_SELECT);
2124 }
2125
2126 void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
2127 {
2128         BMIter iter;
2129         BMVert *eve;
2130         BMEdge *eed;
2131         BMFace *efa;
2132         
2133         if (em->bm->selectmode & SCE_SELECT_VERTEX) {
2134                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2135                         if (BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
2136                                 continue;
2137                         BM_vert_select_set(em->bm, eve, !BM_elem_flag_test(eve, BM_ELEM_SELECT));
2138                 }
2139         }
2140         else if (em->selectmode & SCE_SELECT_EDGE) {
2141                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
2142                         if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
2143                                 continue;
2144                         BM_edge_select_set(em->bm, eed, !BM_elem_flag_test(eed, BM_ELEM_SELECT));
2145                 }
2146         }
2147         else {
2148                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2149                         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
2150                                 continue;
2151                         BM_face_select_set(em->bm, efa, !BM_elem_flag_test(efa, BM_ELEM_SELECT));
2152                 }
2153
2154         }
2155 //      if (EM_texFaceCheck())
2156 }
2157
2158 int EDBM_select_interior_faces(BMEditMesh *em)
2159 {
2160         BMesh *bm = em->bm;
2161         BMIter iter;
2162         BMIter eiter;
2163         BMFace *efa;
2164         BMEdge *eed;
2165         int ok;
2166         int change = FALSE;
2167
2168         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2169                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
2170                         continue;
2171
2172
2173                 ok = TRUE;
2174                 BM_ITER_ELEM (eed, &eiter, efa, BM_EDGES_OF_FACE) {
2175                         if (BM_edge_face_count(eed) < 3) {
2176                                 ok = FALSE;
2177                                 break;
2178                         }
2179                 }
2180
2181                 if (ok) {
2182                         BM_face_select_set(bm, efa, TRUE);
2183                         change = TRUE;
2184                 }
2185         }
2186
2187         return change;
2188 }
2189
2190 static void linked_limit_default(bContext *C, wmOperator *op)
2191 {
2192         if (!RNA_struct_property_is_set(op->ptr, "limit")) {
2193                 Object *obedit = CTX_data_edit_object(C);
2194                 BMEditMesh *em = BMEdit_FromObject(obedit);
2195                 if (em->selectmode == SCE_SELECT_FACE)
2196                         RNA_boolean_set(op->ptr, "limit", TRUE);
2197                 else
2198                         RNA_boolean_set(op->ptr, "limit", FALSE);
2199         }
2200 }
2201
2202 static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
2203 {
2204         Object *obedit = CTX_data_edit_object(C);
2205         ViewContext vc;
2206         BMesh *bm;
2207         BMWalker walker;
2208         BMEditMesh *em;
2209         BMVert *eve;
2210         BMEdge *e, *eed;
2211         BMFace *efa;
2212         int sel = !RNA_boolean_get(op->ptr, "deselect");
2213
2214         int limit;
2215
2216         linked_limit_default(C, op);
2217
2218         limit = RNA_boolean_get(op->ptr, "limit");
2219
2220         /* unified_finednearest needs ogl */
2221         view3d_operator_needs_opengl(C);
2222         
2223         /* setup view context for argument to callbacks */
2224         em_setup_viewcontext(C, &vc);
2225         em = vc.em;
2226
2227         if (em->bm->totedge == 0)
2228                 return OPERATOR_CANCELLED;
2229         
2230         bm = em->bm;
2231
2232         vc.mval[0] = event->mval[0];
2233         vc.mval[1] = event->mval[1];
2234         
2235         /* return warning! */
2236         
2237         if (unified_findnearest(&vc, &eve, &eed, &efa) == 0) {
2238                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2239         
2240                 return OPERATOR_CANCELLED;
2241         }
2242         
2243         if (em->selectmode == SCE_SELECT_FACE) {
2244                 BMIter iter;
2245
2246                 if (efa == NULL)
2247                         return OPERATOR_CANCELLED;
2248
2249                 if (limit) {
2250                         /* grr, shouldn't need to alloc BMO flags here */
2251                         BM_mesh_elem_toolflags_ensure(bm);
2252                         /* hflag no-seam --> bmo-tag */
2253                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
2254                                 /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
2255                                 BMO_elem_flag_set(bm, e, BM_ELEM_SELECT, !BM_elem_flag_test(e, BM_ELEM_SEAM));
2256                         }
2257                 }
2258
2259                 /* walk */
2260                 BMW_init(&walker, bm, BMW_ISLAND,
2261                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP,
2262                          BMW_FLAG_TEST_HIDDEN,
2263                          BMW_NIL_LAY);
2264
2265                 for (efa = BMW_begin(&walker, efa); efa; efa = BMW_step(&walker)) {
2266                         BM_face_select_set(bm, efa, sel);
2267                 }
2268                 BMW_end(&walker);
2269         }
2270         else {
2271                 if (efa) {
2272                         eed = BM_FACE_FIRST_LOOP(efa)->e;
2273                 }
2274                 else if (!eed) {
2275                         if (!eve || !eve->e)
2276                                 return OPERATOR_CANCELLED;
2277
2278                         eed = eve->e;
2279                 }
2280
2281                 BMW_init(&walker, bm, BMW_SHELL,
2282                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
2283                          BMW_FLAG_TEST_HIDDEN,
2284                          BMW_NIL_LAY);
2285
2286                 for (e = BMW_begin(&walker, eed->v1); e; e = BMW_step(&walker)) {
2287                         BM_edge_select_set(bm, e, sel);
2288                 }
2289                 BMW_end(&walker);
2290
2291                 EDBM_selectmode_flush(em);
2292         }
2293
2294         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2295         return OPERATOR_FINISHED;
2296 }
2297
2298 void MESH_OT_select_linked_pick(wmOperatorType *ot)
2299 {
2300         /* identifiers */
2301         ot->name = "Select Linked";
2302         ot->idname = "MESH_OT_select_linked_pick";
2303         ot->description = "(De)select all vertices linked to the edge under the mouse cursor";
2304         
2305         /* api callbacks */
2306         ot->invoke = edbm_select_linked_pick_invoke;
2307         ot->poll = ED_operator_editmesh;
2308         
2309         /* flags */
2310         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2311         
2312         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
2313         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2314 }
2315
2316
2317 static int edbm_select_linked_exec(bContext *C, wmOperator *op)
2318 {
2319         Object *obedit = CTX_data_edit_object(C);
2320         BMEditMesh *em = BMEdit_FromObject(obedit);
2321         BMesh *bm = em->bm;
2322         BMIter iter;
2323         BMVert *v;
2324         BMEdge *e;
2325         BMWalker walker;
2326
2327         int limit;
2328
2329         linked_limit_default(C, op);
2330
2331         limit = RNA_boolean_get(op->ptr, "limit");
2332
2333         if (em->selectmode == SCE_SELECT_FACE) {
2334                 BMFace *efa;
2335
2336                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2337                         BM_elem_flag_set(efa, BM_ELEM_TAG, (BM_elem_flag_test(efa, BM_ELEM_SELECT) &&
2338                                                             !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)));
2339                 }
2340
2341                 if (limit) {
2342                         /* grr, shouldn't need to alloc BMO flags here */
2343                         BM_mesh_elem_toolflags_ensure(bm);
2344                         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
2345                                 /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
2346                                 BMO_elem_flag_set(bm, e, BM_ELEM_SELECT, !BM_elem_flag_test(e, BM_ELEM_SEAM));
2347                         }
2348                 }
2349
2350                 BMW_init(&walker, bm, BMW_ISLAND,
2351                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP,
2352                          BMW_FLAG_TEST_HIDDEN,
2353                          BMW_NIL_LAY);
2354
2355                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2356                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2357                                 for (efa = BMW_begin(&walker, efa); efa; efa = BMW_step(&walker)) {
2358                                         BM_face_select_set(bm, efa, TRUE);
2359                                 }
2360                         }
2361                 }
2362                 BMW_end(&walker);
2363
2364                 if (limit) {
2365                         BM_mesh_elem_toolflags_clear(bm);
2366                 }
2367         }
2368         else {
2369                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2370                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2371                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
2372                         }
2373                         else {
2374                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2375                         }
2376                 }
2377
2378                 BMW_init(&walker, em->bm, BMW_SHELL,
2379                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
2380                          BMW_FLAG_TEST_HIDDEN,
2381                          BMW_NIL_LAY);
2382
2383                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2384                         if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2385                                 for (e = BMW_begin(&walker, v); e; e = BMW_step(&walker)) {
2386                                         BM_edge_select_set(em->bm, e, true);
2387                                 }
2388                         }
2389                 }
2390                 BMW_end(&walker);
2391
2392                 EDBM_selectmode_flush(em);
2393         }
2394
2395         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2396
2397         return OPERATOR_FINISHED;
2398 }
2399
2400 void MESH_OT_select_linked(wmOperatorType *ot)
2401 {
2402         /* identifiers */
2403         ot->name = "Select Linked All";
2404         ot->idname = "MESH_OT_select_linked";
2405         ot->description = "Select all vertices linked to the active mesh";
2406         
2407         /* api callbacks */
2408         ot->exec = edbm_select_linked_exec;
2409         ot->poll = ED_operator_editmesh;
2410         
2411         /* flags */
2412         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2413         
2414         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
2415 }
2416
2417 /* ******************** **************** */
2418
2419 static int edbm_select_more_exec(bContext *C, wmOperator *UNUSED(op))
2420 {
2421         Object *obedit = CTX_data_edit_object(C);
2422         BMEditMesh *em = BMEdit_FromObject(obedit);
2423
2424         EDBM_select_more(em);
2425
2426         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2427         return OPERATOR_FINISHED;
2428 }
2429
2430 void MESH_OT_select_more(wmOperatorType *ot)
2431 {
2432         /* identifiers */
2433         ot->name = "Select More";
2434         ot->idname = "MESH_OT_select_more";
2435         ot->description = "Select more vertices, edges or faces connected to initial selection";
2436
2437         /* api callbacks */
2438         ot->exec = edbm_select_more_exec;
2439         ot->poll = ED_operator_editmesh;
2440         
2441         /* flags */
2442         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2443 }
2444
2445 static int edbm_select_less_exec(bContext *C, wmOperator *UNUSED(op))
2446 {
2447         Object *obedit = CTX_data_edit_object(C);
2448         BMEditMesh *em = BMEdit_FromObject(obedit);
2449
2450         EDBM_select_less(em);
2451
2452         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2453         return OPERATOR_FINISHED;
2454 }
2455
2456 void MESH_OT_select_less(wmOperatorType *ot)
2457 {
2458         /* identifiers */
2459         ot->name = "Select Less";
2460         ot->idname = "MESH_OT_select_less";
2461         ot->description = "Deselect vertices, edges or faces at the boundary of each selection region";
2462
2463         /* api callbacks */
2464         ot->exec = edbm_select_less_exec;
2465         ot->poll = ED_operator_editmesh;
2466         
2467         /* flags */
2468         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2469 }
2470
2471 /* Walk all reachable elements of the same type as h_act in breadth-first
2472  * order, starting from h_act. Deselects elements if the depth when they
2473  * are reached is not a multiple of "nth". */
2474 static void walker_deselect_nth(BMEditMesh *em, int nth, int offset, BMHeader *h_act)
2475 {
2476         BMElem *ele;
2477         BMesh *bm = em->bm;
2478         BMWalker walker;
2479         BMIter iter;
2480         int walktype = 0, itertype = 0, flushtype = 0;
2481         short mask_vert = 0, mask_edge = 0, mask_face = 0;
2482
2483         /* No active element from which to start - nothing to do */
2484         if (h_act == NULL) {
2485                 return;
2486         }
2487
2488         /* Determine which type of iter, walker, and select flush to use
2489          * based on type of the elements being deselected */
2490         switch (h_act->htype) {
2491                 case BM_VERT:
2492                         itertype = BM_VERTS_OF_MESH;
2493                         walktype = BMW_CONNECTED_VERTEX;
2494                         flushtype = SCE_SELECT_VERTEX;
2495                         mask_vert = BM_ELEM_SELECT;
2496                         break;
2497                 case BM_EDGE:
2498                         itertype = BM_EDGES_OF_MESH;
2499                         walktype = BMW_SHELL;
2500                         flushtype = SCE_SELECT_EDGE;
2501                         mask_edge = BM_ELEM_SELECT;
2502                         break;
2503                 case BM_FACE:
2504                         itertype = BM_FACES_OF_MESH;
2505                         walktype = BMW_ISLAND;
2506                         flushtype = SCE_SELECT_FACE;
2507                         mask_face = BM_ELEM_SELECT;
2508                         break;
2509         }
2510
2511         /* grr, shouldn't need to alloc BMO flags here */
2512         BM_mesh_elem_toolflags_ensure(bm);
2513
2514         /* Walker restrictions uses BMO flags, not header flags,
2515          * so transfer BM_ELEM_SELECT from HFlags onto a BMO flag layer. */
2516         BMO_push(bm, NULL);
2517         BM_ITER_MESH (ele, &iter, bm, itertype) {
2518                 if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
2519                         /* BMESH_TODO, don't use 'BM_ELEM_SELECT' here, its a HFLAG only! */
2520                         BMO_elem_flag_enable(bm, (BMElemF *)ele, BM_ELEM_SELECT);
2521                 }
2522         }
2523
2524         /* Walk over selected elements starting at active */
2525         BMW_init(&walker, bm, walktype,
2526                  mask_vert, mask_edge, mask_face,
2527                  BMW_FLAG_NOP, /* don't use BMW_FLAG_TEST_HIDDEN here since we want to desel all */
2528                  BMW_NIL_LAY);
2529
2530         /* use tag to avoid touching the same verts twice */
2531         BM_ITER_MESH (ele, &iter, bm, itertype) {
2532                 BM_elem_flag_disable(ele, BM_ELEM_TAG);
2533         }
2534
2535         BLI_assert(walker.order == BMW_BREADTH_FIRST);
2536         for (ele = BMW_begin(&walker, h_act); ele != NULL; ele = BMW_step(&walker)) {
2537                 if (!BM_elem_flag_test(ele, BM_ELEM_TAG)) {
2538                         /* Deselect elements that aren't at "nth" depth from active */
2539                         if ((offset + BMW_current_depth(&walker)) % nth) {
2540                                 BM_elem_select_set(bm, ele, FALSE);
2541                         }
2542                         BM_elem_flag_enable(ele, BM_ELEM_TAG);
2543                 }
2544         }
2545         BMW_end(&walker);
2546
2547         BMO_pop(bm);
2548
2549         /* Flush selection up */
2550         EDBM_selectmode_flush_ex(em, flushtype);
2551 }
2552
2553 static void deselect_nth_active(BMEditMesh *em, BMVert **r_eve, BMEdge **r_eed, BMFace **r_efa)
2554 {
2555         BMVert *v;
2556         BMEdge *e;
2557         BMFace *f;
2558         BMIter iter;
2559         BMEditSelection *ese;
2560
2561         *r_eve = NULL;
2562         *r_eed = NULL;
2563         *r_efa = NULL;
2564
2565         EDBM_selectmode_flush(em);
2566         ese = (BMEditSelection *)em->bm->selected.last;
2567
2568         if (ese) {
2569                 switch (ese->htype) {
2570                         case BM_VERT:
2571                                 *r_eve = (BMVert *)ese->ele;
2572                                 return;
2573                         case BM_EDGE:
2574                                 *r_eed = (BMEdge *)ese->ele;
2575                                 return;
2576                         case BM_FACE:
2577                                 *r_efa = (BMFace *)ese->ele;
2578                                 return;
2579                 }
2580         }
2581
2582         if (em->selectmode & SCE_SELECT_VERTEX) {
2583                 BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2584                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2585                                 *r_eve = v;
2586                                 return;
2587                         }
2588                 }
2589         }
2590         else if (em->selectmode & SCE_SELECT_EDGE) {
2591                 BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2592                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2593                                 *r_eed = e;
2594                                 return;
2595                         }
2596                 }
2597         }
2598         else if (em->selectmode & SCE_SELECT_FACE) {
2599                 f = BM_active_face_get(em->bm, TRUE, FALSE);
2600                 if (f) {
2601                         *r_efa = f;
2602                         return;
2603                 }
2604         }
2605 }
2606
2607 static int edbm_deselect_nth(BMEditMesh *em, int nth, int offset)
2608 {
2609         BMVert *v;
2610         BMEdge *e;
2611         BMFace *f;
2612
2613         deselect_nth_active(em, &v, &e, &f);
2614
2615         if (v) {
2616                 walker_deselect_nth(em, nth, offset, &v->head);
2617                 return 1;
2618         }
2619         else if (e) {
2620                 walker_deselect_nth(em, nth, offset, &e->head);
2621                 return 1;
2622         }
2623         else if (f) {
2624                 walker_deselect_nth(em, nth, offset, &f->head);
2625                 return 1;
2626         }
2627
2628         return 0;
2629 }
2630
2631 static int edbm_select_nth_exec(bContext *C, wmOperator *op)
2632 {
2633         Object *obedit = CTX_data_edit_object(C);
2634         BMEditMesh *em = BMEdit_FromObject(obedit);
2635         int nth = RNA_int_get(op->ptr, "nth");
2636         int offset = RNA_int_get(op->ptr, "offset");
2637
2638         /* so input of offset zero ends up being (nth - 1) */
2639         offset = (offset + (nth - 1)) % nth;
2640
2641         if (edbm_deselect_nth(em, nth, offset) == 0) {
2642                 BKE_report(op->reports, RPT_ERROR, "Mesh has no active vert/edge/face");
2643                 return OPERATOR_CANCELLED;
2644         }
2645
2646         EDBM_update_generic(em, FALSE, FALSE);
2647
2648         return OPERATOR_FINISHED;
2649 }
2650
2651
2652 void MESH_OT_select_nth(wmOperatorType *ot)
2653 {
2654         /* identifiers */
2655         ot->name = "Checker Deselect";
2656         ot->idname = "MESH_OT_select_nth";
2657         ot->description = "Deselect every Nth element starting from a selected vertex, edge or face";
2658
2659         /* api callbacks */
2660         ot->exec = edbm_select_nth_exec;
2661         ot->poll = ED_operator_editmesh;
2662
2663         /* flags */
2664         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2665
2666         RNA_def_int(ot->srna, "nth", 2, 2, INT_MAX, "Nth Selection", "", 2, 100);
2667         RNA_def_int(ot->srna, "offset", 0, 0, INT_MAX, "Offset", "", 0, 100);
2668 }
2669
2670 void em_setup_viewcontext(bContext *C, ViewContext *vc)
2671 {
2672         view3d_set_viewcontext(C, vc);
2673         
2674         if (vc->obedit) {
2675                 vc->em = BMEdit_FromObject(vc->obedit);
2676         }
2677 }
2678
2679 /* poll call for mesh operators requiring a view3d context */
2680 int EM_view3d_poll(bContext *C)
2681 {
2682         if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
2683                 return 1;
2684
2685         return 0;
2686 }
2687
2688
2689 static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op)
2690 {
2691         /* Find edges that have exactly two neighboring faces,
2692          * check the angle between those faces, and if angle is
2693          * small enough, select the edge
2694          */
2695         Object *obedit = CTX_data_edit_object(C);
2696         BMEditMesh *em = BMEdit_FromObject(obedit);
2697         BMIter iter;
2698         BMEdge *e;
2699         BMLoop *l1, *l2;
2700         const float sharp = RNA_float_get(op->ptr, "sharpness");
2701
2702         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2703                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) == FALSE &&
2704                     BM_edge_loop_pair(e, &l1, &l2))
2705                 {
2706                         /* edge has exactly two neighboring faces, check angle */
2707                         const float angle = angle_normalized_v3v3(l1->f->no, l2->f->no);
2708
2709                         if (fabsf(angle) > sharp) {
2710                                 BM_edge_select_set(em->bm, e, TRUE);
2711                         }
2712                 }
2713         }
2714
2715         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2716
2717         return OPERATOR_FINISHED;
2718 }
2719
2720 void MESH_OT_edges_select_sharp(wmOperatorType *ot)
2721 {
2722         PropertyRNA *prop;
2723
2724         /* identifiers */
2725         ot->name = "Select Sharp Edges";
2726         ot->description = "Select all sharp-enough edges";
2727         ot->idname = "MESH_OT_edges_select_sharp";
2728         
2729         /* api callbacks */
2730         ot->exec = edbm_select_sharp_edges_exec;
2731         ot->poll = ED_operator_editmesh;
2732         
2733         /* flags */
2734         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2735         
2736         /* props */
2737         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2738                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2739         RNA_def_property_float_default(prop, DEG2RADF(30.0f));
2740 }
2741
2742 static int edbm_select_linked_flat_faces_exec(bContext *C, wmOperator *op)
2743 {
2744         Object *obedit = CTX_data_edit_object(C);
2745         BMEditMesh *em = BMEdit_FromObject(obedit);
2746         BMIter iter, liter, liter2;
2747         BMFace *f, **stack = NULL;
2748         BLI_array_declare(stack);
2749         BMLoop *l, *l2;
2750         float sharp = RNA_float_get(op->ptr, "sharpness");
2751         int i;
2752
2753         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2754                 BM_elem_flag_disable(f, BM_ELEM_TAG);
2755         }
2756
2757         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2758                 if (BM_elem_flag_test(f, BM_ELEM_HIDDEN) || !BM_elem_flag_test(f, BM_ELEM_SELECT) || BM_elem_flag_test(f, BM_ELEM_TAG))
2759                         continue;
2760
2761                 BLI_array_empty(stack);
2762                 i = 1;
2763
2764                 BLI_array_grow_one(stack);
2765                 stack[i - 1] = f;
2766
2767                 while (i) {
2768                         f = stack[i - 1];
2769                         i--;
2770
2771                         BM_face_select_set(em->bm, f, TRUE);
2772
2773                         BM_elem_flag_enable(f, BM_ELEM_TAG);
2774
2775                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2776                                 BM_ITER_ELEM (l2, &liter2, l, BM_LOOPS_OF_LOOP) {
2777                                         float angle;
2778
2779                                         if (BM_elem_flag_test(l2->f, BM_ELEM_TAG) || BM_elem_flag_test(l2->f, BM_ELEM_HIDDEN))
2780                                                 continue;
2781
2782                                         /* edge has exactly two neighboring faces, check angle */
2783                                         angle = angle_normalized_v3v3(f->no, l2->f->no);
2784
2785                                         /* invalidate: edge too sharp */
2786                                         if (angle < sharp) {
2787                                                 BLI_array_grow_one(stack);
2788                                                 stack[i] = l2->f;
2789                                                 i++;
2790                                         }
2791                                 }
2792                         }
2793                 }
2794         }
2795
2796         BLI_array_free(stack);
2797
2798         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2799
2800         return OPERATOR_FINISHED;
2801 }
2802
2803 void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
2804 {
2805         PropertyRNA *prop;
2806
2807         /* identifiers */
2808         ot->name = "Select Linked Flat Faces";
2809         ot->description = "Select linked faces by angle";
2810         ot->idname = "MESH_OT_faces_select_linked_flat";
2811         
2812         /* api callbacks */
2813         ot->exec = edbm_select_linked_flat_faces_exec;
2814         ot->poll = ED_operator_editmesh;
2815         
2816         /* flags */
2817         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2818         
2819         /* props */
2820         prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
2821                                       "Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
2822         RNA_def_property_float_default(prop, DEG2RADF(1.0f));
2823 }
2824
2825 static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
2826 {
2827         Object *obedit = CTX_data_edit_object(C);
2828         BMEditMesh *em = BMEdit_FromObject(obedit);
2829         BMVert *v;
2830         BMEdge *e;
2831         BMIter iter;
2832
2833         if (!RNA_boolean_get(op->ptr, "extend"))
2834                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2835
2836         /* Selects isolated verts, and edges that do not have 2 neighboring
2837          * faces
2838          */
2839         
2840         if (em->selectmode == SCE_SELECT_FACE) {
2841                 BKE_report(op->reports, RPT_ERROR, "Does not work in face selection mode");
2842                 return OPERATOR_CANCELLED;
2843         }
2844         
2845         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2846                 if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN) && !BM_vert_is_manifold(v)) {
2847                         BM_vert_select_set(em->bm, v, TRUE);
2848                 }
2849         }
2850         
2851         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
2852                 if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN) && !BM_edge_is_manifold(e)) {
2853                         BM_edge_select_set(em->bm, e, TRUE);
2854                 }
2855         }
2856
2857         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2858
2859         return OPERATOR_FINISHED;
2860 }
2861
2862 void MESH_OT_select_non_manifold(wmOperatorType *ot)
2863 {
2864         /* identifiers */
2865         ot->name = "Select Non Manifold";
2866         ot->description = "Select all non-manifold vertices or edges";
2867         ot->idname = "MESH_OT_select_non_manifold";
2868         
2869         /* api callbacks */
2870         ot->exec = edbm_select_non_manifold_exec;
2871         ot->poll = ED_operator_editmesh;
2872         
2873         /* flags */
2874         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2875
2876         /* props */
2877         RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend the selection");
2878 }
2879
2880 static int edbm_select_random_exec(bContext *C, wmOperator *op)
2881 {
2882         Object *obedit = CTX_data_edit_object(C);
2883         BMEditMesh *em = BMEdit_FromObject(obedit);
2884         BMVert *eve;
2885         BMEdge *eed;
2886         BMFace *efa;
2887         BMIter iter;
2888         float randfac =  RNA_float_get(op->ptr, "percent") / 100.0f;
2889
2890         BLI_srand(BLI_rand()); /* random seed */
2891         
2892         if (!RNA_boolean_get(op->ptr, "extend"))
2893                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2894
2895         if (em->selectmode & SCE_SELECT_VERTEX) {
2896                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2897                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2898                                 BM_vert_select_set(em->bm, eve, TRUE);
2899                         }
2900                 }
2901                 EDBM_selectmode_flush(em);
2902         }
2903         else if (em->selectmode & SCE_SELECT_EDGE) {
2904                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
2905                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2906                                 BM_edge_select_set(em->bm, eed, TRUE);
2907                         }
2908                 }
2909                 EDBM_selectmode_flush(em);
2910         }
2911         else {
2912                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2913                         if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2914                                 BM_face_select_set(em->bm, efa, TRUE);
2915                         }
2916                 }
2917                 EDBM_selectmode_flush(em);
2918         }
2919         
2920         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2921         
2922         return OPERATOR_FINISHED;
2923 }
2924
2925 void MESH_OT_select_random(wmOperatorType *ot)
2926 {
2927         /* identifiers */
2928         ot->name = "Select Random";
2929         ot->description = "Randomly select vertices";
2930         ot->idname = "MESH_OT_select_random";
2931
2932         /* api callbacks */
2933         ot->exec = edbm_select_random_exec;
2934         ot->poll = ED_operator_editmesh;
2935
2936         /* flags */
2937         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2938         
2939         /* props */
2940         RNA_def_float_percentage(ot->srna, "percent", 50.f, 0.0f, 100.0f,
2941                                  "Percent", "Percentage of elements to select randomly", 0.f, 100.0f);
2942         RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
2943 }
2944
2945 static int edbm_select_next_loop_exec(bContext *C, wmOperator *UNUSED(op))
2946 {
2947         Object *obedit = CTX_data_edit_object(C);
2948         BMEditMesh *em = BMEdit_FromObject(obedit);
2949         BMFace *f;
2950         BMVert *v;
2951         BMIter iter;
2952         
2953         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2954                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2955         }
2956         
2957         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
2958                 BMLoop *l;
2959                 BMIter liter;
2960                 
2961                 BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
2962                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
2963                                 BM_elem_flag_enable(l->next->v, BM_ELEM_TAG);
2964                                 BM_vert_select_set(em->bm, l->v, FALSE);
2965                         }
2966                 }
2967         }
2968
2969         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
2970                 if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2971                         BM_vert_select_set(em->bm, v, TRUE);
2972                 }
2973         }
2974
2975         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
2976         return OPERATOR_FINISHED;
2977 }
2978
2979 void MESH_OT_select_next_loop(wmOperatorType *ot)
2980 {
2981         /* identifiers */
2982         ot->name = "Select Next Loop";
2983         ot->idname = "MESH_OT_select_next_loop";
2984         ot->description = "Select next edge loop adjacent to a selected loop";
2985
2986         /* api callbacks */
2987         ot->exec = edbm_select_next_loop_exec;
2988         ot->poll = ED_operator_editmesh;
2989         
2990         /* flags */
2991         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2992 }
2993
2994
2995 static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op))
2996 {
2997         Object *obedit = CTX_data_edit_object(C);
2998         BMEditMesh *em = BMEdit_FromObject(obedit);
2999         BMFace *f;
3000         BMEdge *e;
3001         BMIter iter;
3002
3003         BM_mesh_elem_hflag_disable_all(em->bm, BM_EDGE, BM_ELEM_TAG, FALSE);
3004
3005         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
3006                 BMLoop *l1, *l2;
3007                 BMIter liter1, liter2;
3008                 
3009                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
3010                         int tot = 0, totsel = 0;
3011                         
3012                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
3013                                 tot++;
3014                                 totsel += BM_elem_flag_test(l2->f, BM_ELEM_SELECT) != 0;
3015                         }
3016                         
3017                         if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
3018                                 BM_elem_flag_enable(l1->e, BM_ELEM_TAG);
3019                 }
3020         }
3021
3022         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
3023         
3024         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
3025                 if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
3026                         BM_edge_select_set(em->bm, e, TRUE);
3027                 }
3028         }
3029
3030         /* If in face-only select mode, switch to edge select mode so that
3031          * an edge-only selection is not inconsistent state */
3032         if (em->selectmode == SCE_SELECT_FACE) {
3033                 em->selectmode = SCE_SELECT_EDGE;
3034                 EDBM_selectmode_set(em);
3035                 EDBM_selectmode_to_scene(C);
3036         }
3037
3038         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
3039
3040         return OPERATOR_FINISHED;
3041 }
3042
3043 void MESH_OT_region_to_loop(wmOperatorType *ot)
3044 {
3045         /* identifiers */
3046         ot->name = "Select Boundary Loop";
3047         ot->idname = "MESH_OT_region_to_loop";
3048         ot->description = "Select boundary edges around the selected faces";
3049
3050         /* api callbacks */
3051         ot->exec = edbm_region_to_loop_exec;
3052         ot->poll = ED_operator_editmesh;
3053
3054         /* flags */
3055         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3056 }
3057
3058 static int loop_find_region(BMLoop *l, int flag,
3059                             SmallHash *fhash, BMFace ***region_out)
3060 {
3061         BLI_array_declare(region);
3062         BLI_array_declare(stack);
3063         BMFace **region = NULL;
3064         BMFace **stack = NULL;
3065         BMFace *f;
3066         
3067         BLI_array_append(stack, l->f);
3068         BLI_smallhash_insert(fhash, (uintptr_t)l->f, NULL);
3069         
3070         while (BLI_array_count(stack) > 0) {
3071                 BMIter liter1, liter2;
3072                 BMLoop *l1, *l2;
3073                 
3074                 f = BLI_array_pop(stack);
3075                 BLI_array_append(region, f);
3076                 
3077                 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
3078                         if (BM_elem_flag_test(l1->e, flag))
3079                                 continue;
3080                         
3081                         BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
3082                                 if (BLI_smallhash_haskey(fhash, (uintptr_t)l2->f))
3083                                         continue;
3084                                 
3085                                 BLI_array_append(stack, l2->f);
3086                                 BLI_smallhash_insert(fhash, (uintptr_t)l2->f, NULL);
3087                         }
3088                 }
3089         }
3090         
3091         BLI_array_free(stack);
3092         
3093         *region_out = region;
3094         return BLI_array_count(region);
3095 }
3096
3097 static int verg_radial(const void *va, const void *vb)
3098 {
3099         BMEdge *e1 = *((void **)va);
3100         BMEdge *e2 = *((void **)vb);
3101         int a, b;
3102         
3103         a = BM_edge_face_count(e1);
3104         b = BM_edge_face_count(e2);
3105         
3106         if (a > b)  return -1;
3107         if (a == b) return  0;
3108         if (a < b)  return  1;
3109         
3110         return -1;
3111 }
3112
3113 static int loop_find_regions(BMEditMesh *em, int selbigger)
3114 {
3115         SmallHash visithash;
3116         BMIter iter;
3117         BMEdge *e, **edges = NULL;
3118         BLI_array_declare(edges);
3119         BMFace *f;
3120         int count = 0, i;
3121         
3122         BLI_smallhash_init(&visithash);
3123         
3124         BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
3125                 BM_elem_flag_disable(f, BM_ELEM_TAG);
3126         }
3127
3128         BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
3129                 if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
3130                         BLI_array_append(edges, e);
3131                         BM_elem_flag_enable(e, BM_ELEM_TAG);
3132                 }
3133                 else {
3134                         BM_elem_flag_disable(e, BM_ELEM_TAG);
3135                 }
3136         }
3137         
3138         /* sort edges by radial cycle length */
3139         qsort(edges,  BLI_array_count(edges), sizeof(void *), verg_radial);
3140         
3141         for (i = 0; i < BLI_array_count(edges); i++) {
3142                 BMIter liter;
3143                 BMLoop *l;
3144                 BMFace **region = NULL, **region_out;
3145                 int c, tot = 0;
3146                 
3147                 e = edges[i];
3148                 
3149                 if (!BM_elem_flag_test(e, BM_ELEM_TAG))
3150                         continue;
3151                 
3152                 BM_ITER_ELEM (l, &liter, e, BM_LOOPS_OF_EDGE) {
3153                         if (BLI_smallhash_haskey(&visithash, (uintptr_t)l->f))
3154                                 continue;
3155                                                 
3156                         c = loop_find_region(l, BM_ELEM_SELECT, &visithash, &region_out);
3157
3158                         if (!region || (selbigger ? c >= tot : c < tot)) {
3159                                 /* this region is the best seen so far */
3160                                 tot = c;
3161                                 if (region) {
3162                                         /* free the previous best */
3163                                         MEM_freeN(region);
3164                                 }
3165                                 /* track the current region as the new best */
3166                                 region = region_out;
3167                         }
3168                         else {
3169                                 /* this region is not as good as best so far, just free it */
3170                                 MEM_freeN(region_out);
3171                         }
3172                 }
3173                 
3174                 if (region) {
3175                         int j;
3176                         
3177                         for (j = 0; j < tot; j++) {
3178                                 BM_elem_flag_enable(region[j], BM_ELEM_TAG);
3179                                 BM_ITER_ELEM (l, &liter, region[j], BM_LOOPS_OF_FACE) {
3180                                         BM_elem_flag_disable(l->e, BM_ELEM_TAG);
3181                                 }
3182                         }
3183                         
3184                         count += tot;
3185