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