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