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