BMesh api function naming.
[blender.git] / source / blender / editors / mesh / bmesh_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 #include "MEM_guardedalloc.h"
29
30 #include "BLI_blenlib.h"
31 #include "BLI_math.h"
32 #include "BLI_rand.h"
33 #include "BLI_array.h"
34 #include "BLI_smallhash.h"
35 #include "BLI_heap.h"
36
37 #include "BKE_context.h"
38 #include "BKE_displist.h"
39 #include "BKE_depsgraph.h"
40 #include "BKE_report.h"
41 #include "BKE_paint.h"
42 #include "BKE_tessmesh.h"
43
44 #include "IMB_imbuf_types.h"
45 #include "IMB_imbuf.h"
46
47 #include "WM_api.h"
48 #include "WM_types.h"
49
50 #include "RNA_access.h"
51 #include "RNA_define.h"
52
53 #include "ED_mesh.h"
54 #include "ED_screen.h"
55 #include "ED_view3d.h"
56
57 #include "BIF_gl.h"
58
59 #include "DNA_scene_types.h"
60 #include "DNA_object_types.h"
61 #include "DNA_mesh_types.h"
62
63 #include "mesh_intern.h"
64
65
66 /* ****************************** MIRROR **************** */
67
68 void EDBM_select_mirrored(Object *UNUSED(obedit), BMEditMesh *em, int extend)
69 {
70         BMVert *v1, *v2;
71         BMIter iter;
72
73         BM_ITER(v1, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
74                 if (!BM_elem_flag_test(v1, BM_ELEM_SELECT) || BM_elem_flag_test(v1, BM_ELEM_HIDDEN)) {
75                         BM_elem_flag_disable(v1, BM_ELEM_TAG);
76                 }
77                 else {
78                         BM_elem_flag_enable(v1, BM_ELEM_TAG);
79                 }
80         }
81
82         EDBM_CacheMirrorVerts(em, TRUE);
83
84         if (!extend)
85                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
86
87         BM_ITER(v1, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
88                 if (!BM_elem_flag_test(v1, BM_ELEM_TAG) || BM_elem_flag_test(v1, BM_ELEM_HIDDEN))
89                         continue;
90
91                 v2 = EDBM_GetMirrorVert(em, v1);
92                 if (v2 && !BM_elem_flag_test(v2, BM_ELEM_HIDDEN)) {
93                         BM_elem_select_set(em->bm, v2, TRUE);
94                 }
95         }
96
97         EDBM_EndMirrorCache(em);
98 }
99
100 void EDBM_automerge(Scene *scene, Object *obedit, int update)
101 {
102         BMEditMesh *em;
103         
104         if ((scene->toolsettings->automerge) &&
105             (obedit && obedit->type == OB_MESH))
106         {
107                 em = ((Mesh *)obedit->data)->edit_btmesh;
108                 if (!em)
109                         return;
110
111                 BMO_op_callf(em->bm, "automerge verts=%hv dist=%f", BM_ELEM_SELECT, scene->toolsettings->doublimit);
112                 if (update) {
113                         DAG_id_tag_update(obedit->data, OB_RECALC_DATA);
114                 }
115         }
116 }
117
118 /* ****************************** SELECTION ROUTINES **************** */
119
120 unsigned int bm_solidoffs = 0, bm_wireoffs = 0, bm_vertoffs = 0;        /* set in drawobject.c ... for colorindices */
121
122 /* facilities for border select and circle select */
123 static char *selbuf = NULL;
124
125 /* opengl doesn't support concave... */
126 static void draw_triangulated(int mcords[][2], short tot)
127 {
128         ListBase lb = {NULL, NULL};
129         DispList *dl;
130         float *fp;
131         int a;
132         
133         /* make displist */
134         dl = MEM_callocN(sizeof(DispList), "poly disp");
135         dl->type = DL_POLY;
136         dl->parts = 1;
137         dl->nr = tot;
138         dl->verts = fp = MEM_callocN(tot * 3 * sizeof(float), "poly verts");
139         BLI_addtail(&lb, dl);
140         
141         for (a = 0; a < tot; a++, fp += 3) {
142                 fp[0] = (float)mcords[a][0];
143                 fp[1] = (float)mcords[a][1];
144         }
145         
146         /* do the fill */
147         filldisplist(&lb, &lb, 0);
148
149         /* do the draw */
150         dl = lb.first;  /* filldisplist adds in head of list */
151         if (dl->type == DL_INDEX3) {
152                 int *index;
153                 
154                 a = dl->parts;
155                 fp = dl->verts;
156                 index = dl->index;
157                 glBegin(GL_TRIANGLES);
158                 while (a--) {
159                         glVertex3fv(fp + 3 * index[0]);
160                         glVertex3fv(fp + 3 * index[1]);
161                         glVertex3fv(fp + 3 * index[2]);
162                         index += 3;
163                 }
164                 glEnd();
165         }
166         
167         freedisplist(&lb);
168 }
169
170
171 /* reads rect, and builds selection array for quick lookup */
172 /* returns if all is OK */
173 int EDBM_init_backbuf_border(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
174 {
175         struct ImBuf *buf;
176         unsigned int *dr;
177         int a;
178         
179         if (vc->obedit == NULL || vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
180                 return 0;
181         }
182         
183         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
184         if (buf == NULL) return 0;
185         if (bm_vertoffs == 0) return 0;
186
187         dr = buf->rect;
188         
189         /* build selection lookup */
190         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
191         
192         a = (xmax - xmin + 1) * (ymax-ymin + 1);
193         while (a--) {
194                 if (*dr > 0 && *dr <= bm_vertoffs)
195                         selbuf[*dr] = 1;
196                 dr++;
197         }
198         IMB_freeImBuf(buf);
199         return 1;
200 }
201
202 int EDBM_check_backbuf(unsigned int index)
203 {
204         if (selbuf == NULL) return 1;
205         if (index > 0 && index <= bm_vertoffs)
206                 return selbuf[index];
207         return 0;
208 }
209
210 void EDBM_free_backbuf(void)
211 {
212         if (selbuf) MEM_freeN(selbuf);
213         selbuf = NULL;
214 }
215
216 /* mcords is a polygon mask
217    - grab backbuffer,
218    - draw with black in backbuffer, 
219    - grab again and compare
220    returns 'OK' 
221 */
222 int EDBM_mask_init_backbuf_border(ViewContext *vc, int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
223 {
224         unsigned int *dr, *drm;
225         struct ImBuf *buf, *bufmask;
226         int a;
227         
228         /* method in use for face selecting too */
229         if (vc->obedit == NULL) {
230                 if (paint_facesel_test(vc->obact));
231                 else if (paint_vertsel_test(vc->obact));
232                 else return 0;
233         }
234         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) {
235                 return 0;
236         }
237
238         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
239         if (buf == NULL) return 0;
240         if (bm_vertoffs == 0) return 0;
241
242         dr = buf->rect;
243
244         /* draw the mask */
245         glDisable(GL_DEPTH_TEST);
246         
247         glColor3ub(0, 0, 0);
248         
249         /* yah, opengl doesn't do concave... tsk! */
250         ED_region_pixelspace(vc->ar);
251         draw_triangulated(mcords, tot);
252         
253         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
254         for (a = 0; a < tot; a++) {
255                 glVertex2iv(mcords[a]);
256         }
257         glEnd();
258         
259         glFinish();     /* to be sure readpixels sees mask */
260         
261         /* grab mask */
262         bufmask = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
263         drm = bufmask->rect;
264         if (bufmask == NULL) {
265                 return 0; /* only when mem alloc fails, go crash somewhere else! */
266         }
267         
268         /* build selection lookup */
269         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
270         
271         a = (xmax - xmin + 1) * (ymax - ymin + 1);
272         while (a--) {
273                 if (*dr > 0 && *dr <= bm_vertoffs && *drm == 0) selbuf[*dr] = 1;
274                 dr++; drm++;
275         }
276         IMB_freeImBuf(buf);
277         IMB_freeImBuf(bufmask);
278
279         return 1;
280 }
281
282 /* circle shaped sample area */
283 int EDBM_init_backbuf_circle(ViewContext *vc, short xs, short ys, short rads)
284 {
285         struct ImBuf *buf;
286         unsigned int *dr;
287         short xmin, ymin, xmax, ymax, xc, yc;
288         int radsq;
289         
290         /* method in use for face selecting too */
291         if (vc->obedit == NULL) {
292                 if (paint_facesel_test(vc->obact));
293                 else if (paint_vertsel_test(vc->obact));
294                 else return 0;
295         }
296         else if (vc->v3d->drawtype < OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT) == 0) return 0;
297         
298         xmin = xs - rads; xmax = xs + rads;
299         ymin = ys - rads; ymax = ys + rads;
300         buf = view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
301         if (bm_vertoffs == 0) return 0;
302         if (buf == NULL) return 0;
303
304         dr = buf->rect;
305         
306         /* build selection lookup */
307         selbuf = MEM_callocN(bm_vertoffs + 1, "selbuf");
308         radsq = rads * rads;
309         for (yc = -rads; yc <= rads; yc++) {
310                 for (xc = -rads; xc <= rads; xc++, dr++) {
311                         if (xc * xc + yc * yc < radsq) {
312                                 if (*dr > 0 && *dr <= bm_vertoffs) selbuf[*dr] = 1;
313                         }
314                 }
315         }
316
317         IMB_freeImBuf(buf);
318         return 1;
319         
320 }
321
322 static void findnearestvert__doClosest(void *userData, BMVert *eve, int x, int y, int index)
323 {
324         struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } *data = userData;
325
326         if (data->pass == 0) {
327                 if (index <= data->lastIndex)
328                         return;
329         }
330         else {
331                 if (index > data->lastIndex)
332                         return;
333         }
334
335         if (data->dist > 3) {
336                 int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
337                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) == data->select) {
338                         if (data->strict == 1)
339                                 return;
340                         else
341                                 temp += 5;
342                 }
343
344                 if (temp < data->dist) {
345                         data->dist = temp;
346                         data->closest = eve;
347                         data->closestIndex = index;
348                 }
349         }
350 }
351
352
353
354
355 static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
356 {
357         BMEditMesh *em = (BMEditMesh *)handle;
358         BMVert *eve = BM_vert_at_index(em->bm, index - 1);
359
360         if (eve && BM_elem_flag_test(eve, BM_ELEM_SELECT)) return 0;
361         return 1;
362 }
363 /**
364  * findnearestvert
365  * 
366  * dist (in/out): minimal distance to the nearest and at the end, actual distance
367  * sel: selection bias
368  *              if SELECT, selected vertice are given a 5 pixel bias to make them farter than unselect verts
369  *              if 0, unselected vertice are given the bias
370  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
371  */
372 BMVert *EDBM_findnearestvert(ViewContext *vc, int *dist, short sel, short strict)
373 {
374         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
375                 int distance;
376                 unsigned int index;
377                 BMVert *eve;
378                 
379                 if (strict) {
380                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
381                                                            strict, vc->em, findnearestvert__backbufIndextest);
382                 }
383                 else {
384                         index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_wireoffs, 0xFFFFFF, &distance,
385                                                            0, NULL, NULL);
386                 }
387                 
388                 eve = BM_vert_at_index(vc->em->bm, index - 1);
389                 
390                 if (eve && distance < *dist) {
391                         *dist = distance;
392                         return eve;
393                 }
394                 else {
395                         return NULL;
396                 }
397                         
398         }
399         else {
400                 struct { short mval[2], pass, select, strict; int dist, lastIndex, closestIndex; BMVert *closest; } data;
401                 static int lastSelectedIndex = 0;
402                 static BMVert *lastSelected = NULL;
403                 
404                 if (lastSelected && BM_vert_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
405                         lastSelectedIndex = 0;
406                         lastSelected = NULL;
407                 }
408
409                 data.lastIndex = lastSelectedIndex;
410                 data.mval[0] = vc->mval[0];
411                 data.mval[1] = vc->mval[1];
412                 data.select = sel;
413                 data.dist = *dist;
414                 data.strict = strict;
415                 data.closest = NULL;
416                 data.closestIndex = 0;
417
418                 data.pass = 0;
419
420                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
421
422                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
423
424                 if (data.dist > 3) {
425                         data.pass = 1;
426                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
427                 }
428
429                 *dist = data.dist;
430                 lastSelected = data.closest;
431                 lastSelectedIndex = data.closestIndex;
432
433                 return data.closest;
434         }
435 }
436
437 /* returns labda for closest distance v1 to line-piece v2 - v3 */
438 float labda_PdistVL2Dfl(const float v1[3], const float v2[3], const float v3[3])
439 {
440         float rc[2], len;
441         
442         rc[0] = v3[0] - v2[0];
443         rc[1] = v3[1] - v2[1];
444         len = rc[0] * rc[0] + rc[1] * rc[1];
445         if (len == 0.0f)
446                 return 0.0f;
447         
448         return (rc[0] * (v1[0] - v2[0]) + rc[1] * (v1[1] - v2[1]) ) / len;
449 }
450
451 /* note; uses v3d, so needs active 3d window */
452 static void findnearestedge__doClosest(void *userData, BMEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
453 {
454         struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } *data = userData;
455         float v1[2], v2[2];
456         int distance;
457                 
458         v1[0] = x0;
459         v1[1] = y0;
460         v2[0] = x1;
461         v2[1] = y1;
462                 
463         distance = dist_to_line_segment_v2(data->mval, v1, v2);
464                 
465         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
466                 distance += 5;
467         }
468
469         if (distance < data->dist) {
470                 if (data->vc.rv3d->rflag & RV3D_CLIPPING) {
471                         float labda = labda_PdistVL2Dfl(data->mval, v1, v2);
472                         float vec[3];
473
474                         vec[0] = eed->v1->co[0] + labda * (eed->v2->co[0] - eed->v1->co[0]);
475                         vec[1] = eed->v1->co[1] + labda * (eed->v2->co[1] - eed->v1->co[1]);
476                         vec[2] = eed->v1->co[2] + labda * (eed->v2->co[2] - eed->v1->co[2]);
477                         mul_m4_v3(data->vc.obedit->obmat, vec);
478
479                         if (ED_view3d_test_clipping(data->vc.rv3d, vec, 1) == 0) {
480                                 data->dist = distance;
481                                 data->closest = eed;
482                         }
483                 }
484                 else {
485                         data->dist = distance;
486                         data->closest = eed;
487                 }
488         }
489 }
490 BMEdge *EDBM_findnearestedge(ViewContext *vc, int *dist)
491 {
492
493         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
494                 int distance;
495                 unsigned int index;
496                 BMEdge *eed;
497                 
498                 view3d_validate_backbuf(vc);
499                 
500                 index = view3d_sample_backbuf_rect(vc, vc->mval, 50, bm_solidoffs, bm_wireoffs, &distance,0, NULL, NULL);
501                 eed = BM_edge_at_index(vc->em->bm, index - 1);
502                 
503                 if (eed && distance < *dist) {
504                         *dist = distance;
505                         return eed;
506                 }
507                 else {
508                         return NULL;
509                 }
510         }
511         else {
512                 struct { ViewContext vc; float mval[2]; int dist; BMEdge *closest; } data;
513
514                 data.vc = *vc;
515                 data.mval[0] = vc->mval[0];
516                 data.mval[1] = vc->mval[1];
517                 data.dist = *dist;
518                 data.closest = NULL;
519                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
520
521                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, 2);
522
523                 *dist = data.dist;
524                 return data.closest;
525         }
526 }
527
528 static void findnearestface__getDistance(void *userData, BMFace *efa, int x, int y, int UNUSED(index))
529 {
530         struct { short mval[2]; int dist; BMFace *toFace; } *data = userData;
531
532         if (efa == data->toFace) {
533                 int temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
534
535                 if (temp < data->dist)
536                         data->dist = temp;
537         }
538 }
539 static void findnearestface__doClosest(void *userData, BMFace *efa, int x, int y, int index)
540 {
541         struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } *data = userData;
542
543         if (data->pass == 0) {
544                 if (index <= data->lastIndex)
545                         return;
546         }
547         else {
548                 if (index > data->lastIndex)
549                         return;
550         }
551
552         if (data->dist > 3) {
553                 int temp = abs(data->mval[0] - x) + abs(data->mval[1] - y);
554
555                 if (temp < data->dist) {
556                         data->dist = temp;
557                         data->closest = efa;
558                         data->closestIndex = index;
559                 }
560         }
561 }
562
563 BMFace *EDBM_findnearestface(ViewContext *vc, int *dist)
564 {
565
566         if (vc->v3d->drawtype > OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
567                 unsigned int index;
568                 BMFace *efa;
569
570                 view3d_validate_backbuf(vc);
571
572                 index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
573                 efa = BM_face_at_index(vc->em->bm, index - 1);
574                 
575                 if (efa) {
576                         struct { short mval[2]; int dist; BMFace *toFace; } data;
577
578                         data.mval[0] = vc->mval[0];
579                         data.mval[1] = vc->mval[1];
580                         data.dist = 0x7FFF;             /* largest short */
581                         data.toFace = efa;
582
583                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
584
585                         if (vc->em->selectmode == SCE_SELECT_FACE || data.dist < *dist) {       /* only faces, no dist check */
586                                 *dist = data.dist;
587                                 return efa;
588                         }
589                 }
590                 
591                 return NULL;
592         }
593         else {
594                 struct { short mval[2], pass; int dist, lastIndex, closestIndex; BMFace *closest; } data;
595                 static int lastSelectedIndex = 0;
596                 static BMFace *lastSelected = NULL;
597
598                 if (lastSelected && BM_face_at_index(vc->em->bm, lastSelectedIndex) != lastSelected) {
599                         lastSelectedIndex = 0;
600                         lastSelected = NULL;
601                 }
602
603                 data.lastIndex = lastSelectedIndex;
604                 data.mval[0] = vc->mval[0];
605                 data.mval[1] = vc->mval[1];
606                 data.dist = *dist;
607                 data.closest = NULL;
608                 data.closestIndex = 0;
609                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
610
611                 data.pass = 0;
612                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
613
614                 if (data.dist > 3) {
615                         data.pass = 1;
616                         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
617                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
618                 }
619
620                 *dist = data.dist;
621                 lastSelected = data.closest;
622                 lastSelectedIndex = data.closestIndex;
623
624                 return data.closest;
625         }
626 }
627
628 /* best distance based on screen coords. 
629    use em->selectmode to define how to use 
630    selected vertices and edges get disadvantage
631    return 1 if found one
632 */
633 static int unified_findnearest(ViewContext *vc, BMVert **eve, BMEdge **eed, BMFace **efa) 
634 {
635         BMEditMesh *em = vc->em;
636         int dist = 75;
637         
638         *eve = NULL;
639         *eed = NULL;
640         *efa = NULL;
641         
642         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
643         view3d_validate_backbuf(vc);
644         
645         if (em->selectmode & SCE_SELECT_VERTEX)
646                 *eve = EDBM_findnearestvert(vc, &dist, BM_ELEM_SELECT, 0);
647         if (em->selectmode & SCE_SELECT_FACE)
648                 *efa = EDBM_findnearestface(vc, &dist);
649
650         dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
651         if (em->selectmode & SCE_SELECT_EDGE)
652                 *eed = EDBM_findnearestedge(vc, &dist);
653
654         /* return only one of 3 pointers, for frontbuffer redraws */
655         if (*eed) {
656                 *efa = NULL; *eve = NULL;
657         }
658         else if (*efa) {
659                 *eve = NULL;
660         }
661         
662         return (*eve || *eed || *efa);
663 }
664
665 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
666
667 static EnumPropertyItem prop_similar_types[] = {
668         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
669         {SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
670         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
671
672         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
673         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
674         {SIMEDGE_FACE, "FACE", 0, "Amount of Faces Around an Edge", ""},
675         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
676         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
677         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
678         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
679
680         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
681         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
682         {SIMFACE_AREA, "AREA", 0, "Area", ""},
683         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
684         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
685         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
686
687         {0, NULL, 0, NULL, NULL}
688 };
689
690 /* selects new faces/edges/verts based on the existing selection */
691
692 static int similar_face_select_exec(bContext *C, wmOperator *op)
693 {
694         Object *ob = CTX_data_edit_object(C);
695         BMEditMesh *em = ((Mesh *)ob->data)->edit_btmesh;
696         BMOperator bmop;
697
698         /* get the type from RNA */
699         int type = RNA_enum_get(op->ptr, "type");
700
701         float thresh = CTX_data_tool_settings(C)->select_thresh;
702
703         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
704         EDBM_InitOpf(em, &bmop, op, "similarfaces faces=%hf type=%d thresh=%f", BM_ELEM_SELECT, type, thresh);
705
706         /* execute the operator */
707         BMO_op_exec(em->bm, &bmop);
708
709         /* clear the existing selection */
710         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
711
712         /* select the output */
713         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "faceout", BM_ELEM_SELECT, BM_ALL);
714
715         /* finish the operator */
716         if (!EDBM_FinishOp(em, &bmop, op, TRUE)) {
717                 return OPERATOR_CANCELLED;
718         }
719
720         /* dependencies graph and notification stuff */
721         DAG_id_tag_update(ob->data, OB_RECALC_DATA);
722         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
723
724         /* we succeeded */
725         return OPERATOR_FINISHED;
726 }       
727
728 /* ***************************************************** */
729
730 /* EDGE GROUP */
731
732 /* wrap the above function but do selection flushing edge to face */
733 static int similar_edge_select_exec(bContext *C, wmOperator *op)
734 {
735         Object *ob = CTX_data_edit_object(C);
736         BMEditMesh *em = ((Mesh *)ob->data)->edit_btmesh;
737         BMOperator bmop;
738
739         /* get the type from RNA */
740         int type = RNA_enum_get(op->ptr, "type");
741
742         float thresh = CTX_data_tool_settings(C)->select_thresh;
743
744         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
745         EDBM_InitOpf(em, &bmop, op, "similaredges edges=%he type=%d thresh=%f", BM_ELEM_SELECT, type, thresh);
746
747         /* execute the operator */
748         BMO_op_exec(em->bm, &bmop);
749
750         /* clear the existing selection */
751         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
752
753         /* select the output */
754         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "edgeout", BM_ELEM_SELECT, BM_ALL);
755         EDBM_selectmode_flush(em);
756
757         /* finish the operator */
758         if (!EDBM_FinishOp(em, &bmop, op, TRUE)) {
759                 return OPERATOR_CANCELLED;
760         }
761
762         /* dependencies graph and notification stuff */
763         DAG_id_tag_update(ob->data, OB_RECALC_DATA);
764         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
765
766         /* we succeeded */
767         return OPERATOR_FINISHED;
768 }
769
770 /* ********************************* */
771
772 /*
773 VERT GROUP
774  mode 1: same normal
775  mode 2: same number of face users
776  mode 3: same vertex groups
777 */
778
779
780 static int similar_vert_select_exec(bContext *C, wmOperator *op)
781 {
782         Object *ob = CTX_data_edit_object(C);
783         BMEditMesh *em = ((Mesh *)ob->data)->edit_btmesh;
784         BMOperator bmop;
785         /* get the type from RNA */
786         int type = RNA_enum_get(op->ptr, "type");
787         float thresh = CTX_data_tool_settings(C)->select_thresh;
788
789         /* initialize the bmop using EDBM api, which does various ui error reporting and other stuff */
790         EDBM_InitOpf(em, &bmop, op, "similarverts verts=%hv type=%d thresh=%f", BM_ELEM_SELECT, type, thresh);
791
792         /* execute the operator */
793         BMO_op_exec(em->bm, &bmop);
794
795         /* clear the existing selection */
796         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
797
798         /* select the output */
799         BMO_slot_buffer_hflag_enable(em->bm, &bmop, "vertout", BM_ELEM_SELECT, BM_ALL);
800
801         /* finish the operator */
802         if (!EDBM_FinishOp(em, &bmop, op, TRUE)) {
803                 return OPERATOR_CANCELLED;
804         }
805
806         EDBM_selectmode_flush(em);
807
808         /* dependencies graph and notification stuff */
809         DAG_id_tag_update(ob->data, OB_RECALC_DATA);
810         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
811
812         /* we succeeded */
813         return OPERATOR_FINISHED;
814 }
815
816 static int select_similar_exec(bContext *C, wmOperator *op)
817 {
818         int type = RNA_enum_get(op->ptr, "type");
819
820         if (type < 100)
821                 return similar_vert_select_exec(C, op);
822         else if (type < 200)
823                 return similar_edge_select_exec(C, op);
824         else
825                 return similar_face_select_exec(C, op);
826 }
827
828 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
829                                                    int *free)
830 {
831         Object *obedit = CTX_data_edit_object(C);
832
833         if (obedit && obedit->type == OB_MESH) {
834                 EnumPropertyItem *item = NULL;
835                 int a, totitem = 0;
836                 BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
837
838                 if (em->selectmode & SCE_SELECT_VERTEX) {
839                         for (a = SIMVERT_NORMAL; a < SIMEDGE_LENGTH; a++) {
840                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
841                         }
842                 }
843                 else if (em->selectmode & SCE_SELECT_EDGE) {
844                         for (a = SIMEDGE_LENGTH; a < SIMFACE_MATERIAL; a++) {
845                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
846                         }
847                 }
848                 else if (em->selectmode & SCE_SELECT_FACE) {
849                         for (a = SIMFACE_MATERIAL; a <= SIMFACE_COPLANAR; a++) {
850                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
851                         }
852                 }
853                 RNA_enum_item_end(&item, &totitem);
854
855                 *free = 1;
856
857                 return item;
858         }
859         
860         return NULL;
861 }
862
863 void MESH_OT_select_similar(wmOperatorType *ot)
864 {
865         PropertyRNA *prop;
866
867         /* identifiers */
868         ot->name = "Select Similar";
869         ot->idname = "MESH_OT_select_similar";
870         
871         /* api callbacks */
872         ot->invoke = WM_menu_invoke;
873         ot->exec = select_similar_exec;
874         ot->poll = ED_operator_editmesh;
875         ot->description = "Select similar vertices, edges or faces by property types";
876         
877         /* flags */
878         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
879         
880         /* properties */
881         prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
882         RNA_def_enum_funcs(prop, select_similar_type_itemf);
883 }
884
885 /* ***************************************************** */
886
887 /* ****************  LOOP SELECTS *************** */
888
889 static void walker_select(BMEditMesh *em, int walkercode, void *start, int select)
890 {
891         BMesh *bm = em->bm;
892         BMHeader *h;
893         BMWalker walker;
894
895         BMW_init(&walker, bm, walkercode,
896                  BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
897                  BMW_NIL_LAY);
898         h = BMW_begin(&walker, start);
899         for ( ; h; h = BMW_step(&walker)) {
900                 if (!select) {
901                         BM_select_history_remove(bm, h);
902                 }
903                 BM_elem_select_set(bm, h, select);
904         }
905         BMW_end(&walker);
906 }
907
908 static int loop_multiselect(bContext *C, wmOperator *op)
909 {
910         Object *obedit = CTX_data_edit_object(C);
911         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
912         BMEdge *eed;
913         BMEdge **edarray;
914         int edindex;
915         int looptype = RNA_boolean_get(op->ptr, "ring");
916         
917         BMIter iter;
918         int totedgesel = 0;
919
920         for (eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
921             eed; eed = BM_iter_step(&iter)) {
922
923                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
924                         totedgesel++;
925                 }
926         }
927
928         
929         edarray = MEM_mallocN(sizeof(BMEdge *)*totedgesel,"edge array");
930         edindex = 0;
931         
932         for (eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
933              eed;
934              eed = BM_iter_step(&iter))
935         {
936
937                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
938                         edarray[edindex] = eed;
939                         edindex++;
940                 }
941         }
942         
943         if (looptype) {
944                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
945                         eed = edarray[edindex];
946                         walker_select(em, BMW_EDGERING, eed, 1);
947                 }
948                 EDBM_selectmode_flush(em);
949         }
950         else{
951                 for (edindex = 0; edindex < totedgesel; edindex += 1) {
952                         eed = edarray[edindex];
953                         walker_select(em, BMW_LOOP, eed, 1);
954                 }
955                 EDBM_selectmode_flush(em);
956         }
957         MEM_freeN(edarray);
958 //      if (EM_texFaceCheck())
959         
960         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
961
962         return OPERATOR_FINISHED;
963 }
964
965 void MESH_OT_loop_multi_select(wmOperatorType *ot)
966 {
967         /* identifiers */
968         ot->name = "Multi Select Loops";
969         ot->idname = "MESH_OT_loop_multi_select";
970         
971         /* api callbacks */
972         ot->exec = loop_multiselect;
973         ot->poll = ED_operator_editmesh;
974         ot->description = "Select a loop of connected edges by connection type";
975         
976         /* flags */
977         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
978         
979         /* properties */
980         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
981 }
982
983                 
984 /* ***************** MAIN MOUSE SELECTION ************** */
985
986
987 /* ***************** loop select (non modal) ************** */
988
989 static void mouse_mesh_loop(bContext *C, int mval[2], short extend, short ring)
990 {
991         ViewContext vc;
992         BMEditMesh *em;
993         BMEdge *eed;
994         int select = TRUE;
995         int dist = 50;
996         
997         em_setup_viewcontext(C, &vc);
998         vc.mval[0] = mval[0];
999         vc.mval[1] = mval[1];
1000         em = vc.em;
1001         
1002         /* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
1003         view3d_validate_backbuf(&vc);
1004
1005         eed = EDBM_findnearestedge(&vc, &dist);
1006         if (eed) {
1007                 if (extend == 0) {
1008                         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1009                 }
1010         
1011                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT) == 0) {
1012                         select = TRUE;
1013                 }
1014                 else if (extend) {
1015                         select = FALSE;
1016                 }
1017
1018                 if (em->selectmode & SCE_SELECT_FACE) {
1019                         walker_select(em, BMW_FACELOOP, eed, select);
1020                 }
1021                 else if (em->selectmode & SCE_SELECT_EDGE) {
1022                         if (ring)
1023                                 walker_select(em, BMW_EDGERING, eed, select);
1024                         else
1025                                 walker_select(em, BMW_LOOP, eed, select);
1026                 }
1027                 else if (em->selectmode & SCE_SELECT_VERTEX) {
1028                         if (ring)
1029                                 walker_select(em, BMW_EDGERING, eed, select);
1030
1031                         else
1032                                 walker_select(em, BMW_LOOP, eed, select);
1033                 }
1034
1035                 EDBM_selectmode_flush(em);
1036 //                      if (EM_texFaceCheck())
1037                 
1038                 /* sets as active, useful for other tools */
1039                 if (select) {
1040                         if (em->selectmode & SCE_SELECT_VERTEX) {
1041                                 /* TODO: would be nice if the edge vertex chosen here
1042                                  * was the one closer to the selection pointer, instead
1043                                  * of arbitrarily selecting the first one */
1044                                 EDBM_store_selection(em, eed->v1);
1045                         }
1046                         else if (em->selectmode & SCE_SELECT_EDGE) {
1047                                 EDBM_store_selection(em, eed);
1048                         }
1049                         /* TODO: would be nice if the nearest face that
1050                          * belongs to the selected edge could be set to
1051                          * active here in face select mode */
1052                 }
1053
1054                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit);
1055         }
1056 }
1057
1058 static int mesh_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
1059 {
1060         
1061         view3d_operator_needs_opengl(C);
1062         
1063         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
1064                                         RNA_boolean_get(op->ptr, "ring"));
1065         
1066         /* cannot do tweaks for as long this keymap is after transform map */
1067         return OPERATOR_FINISHED;
1068 }
1069
1070 void MESH_OT_loop_select(wmOperatorType *ot)
1071 {
1072         /* identifiers */
1073         ot->name = "Loop Select";
1074         ot->idname = "MESH_OT_loop_select";
1075         ot->description = "Select a loop";
1076         
1077         /* api callbacks */
1078         ot->invoke = mesh_select_loop_invoke;
1079         ot->poll = ED_operator_editmesh_region_view3d;
1080         ot->description = "Select a loop of connected edges";
1081         
1082         /* flags */
1083         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1084         
1085         /* properties */
1086         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
1087         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "Select ring");
1088 }
1089
1090 void MESH_OT_edgering_select (wmOperatorType *ot)
1091 {
1092         /* description */
1093         ot->name = "Edge Ring Select";
1094         ot->idname = "MESH_OT_edgering_select";
1095         ot->description = "Select an edge ring";
1096         
1097         /* callbacks */
1098         ot->invoke = mesh_select_loop_invoke;
1099         ot->poll = ED_operator_editmesh_region_view3d;
1100         
1101         /* flags */
1102         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1103
1104         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the selection");
1105         RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
1106 }
1107
1108 /* ******************* edgetag_shortest_path and helpers ****************** */
1109
1110 static float edgetag_cut_cost(BMEditMesh *UNUSED(em), BMEdge *e1, BMEdge *e2, BMVert *v)
1111 {
1112         BMVert *v1 = (e1->v1 == v) ? e1->v2 : e1->v1;
1113         BMVert *v2 = (e2->v1 == v) ? e2->v2 : e2->v1;
1114         float cost, d1[3], d2[3];
1115
1116         /* The cost is based on the simple sum of the length of the two edgees... */
1117         sub_v3_v3v3(d1, v->co, v1->co);
1118         sub_v3_v3v3(d2, v2->co, v->co);
1119         cost = len_v3(d1);
1120         cost += len_v3(d2);
1121
1122         /*.but is biased to give higher values to sharp turns, so that it will take
1123          * paths with fewer "turns" when selecting between equal-weighted paths between
1124          * the two edges */
1125         cost = cost + 0.5f * cost * (2.0f - sqrt(fabs(dot_v3v3(d1, d2))));
1126
1127         return cost;
1128 }
1129
1130 static void edgetag_add_adjacent(BMEditMesh *em, SmallHash *visithash, Heap *heap, int mednum, int vertnum, 
1131                                                                  int *nedges, int *edges, int *prevedge, float *cost)
1132 {
1133         BMEdge *e1 = EDBM_get_edge_for_index(em, mednum);
1134         BMVert *v = EDBM_get_vert_for_index(em, vertnum);
1135         int startadj, endadj = nedges[vertnum + 1];
1136
1137         for (startadj = nedges[vertnum]; startadj < endadj; startadj++) {
1138                 int adjnum = edges[startadj];
1139                 BMEdge *e2 = EDBM_get_edge_for_index(em, adjnum);
1140                 float newcost;
1141                 float cutcost;
1142
1143                 if (BLI_smallhash_haskey(visithash, (uintptr_t)e2))
1144                         continue;
1145
1146                 cutcost = edgetag_cut_cost(em, e1, e2, v);
1147                 newcost = cost[mednum] + cutcost;
1148
1149                 if (cost[adjnum] > newcost) {
1150                         cost[adjnum] = newcost;
1151                         prevedge[adjnum] = mednum;
1152                         BLI_heap_insert(heap, newcost, SET_INT_IN_POINTER(adjnum));
1153                 }
1154         }
1155 }
1156
1157 static void edgetag_context_set(BMEditMesh *em, Scene *scene, BMEdge *e, int val)
1158 {
1159         
1160         switch (scene->toolsettings->edge_mode) {
1161         case EDGE_MODE_SELECT:
1162                 BM_elem_select_set(em->bm, e, val);
1163                 break;
1164         case EDGE_MODE_TAG_SEAM:
1165                 if (val)                {BM_elem_flag_enable(e, BM_ELEM_SEAM);}
1166                 else                    {BM_elem_flag_disable(e, BM_ELEM_SEAM);}
1167                 break;
1168         case EDGE_MODE_TAG_SHARP:
1169                 if (val)                {BM_elem_flag_enable(e, BM_ELEM_SEAM);}
1170                 else                    {BM_elem_flag_disable(e, BM_ELEM_SEAM);}
1171                 break;
1172         case EDGE_MODE_TAG_CREASE:
1173          {
1174                 float *crease = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_CREASE);
1175                 
1176                 if (val)                {*crease = 1.0f;}
1177                 else                    {*crease = 0.0f;}
1178                 break;
1179          }
1180         case EDGE_MODE_TAG_BEVEL:
1181          {
1182                 float *bweight = CustomData_bmesh_get(&em->bm->edata, e->head.data, CD_BWEIGHT);
1183
1184                 if (val)                {*bweight = 1.0f;}
1185                 else                    {*bweight = 0.0f;}
1186                 break;
1187          }
1188         }
1189 }
1190
1191 static int edgetag_context_check(Scene *scene, BMEditMesh *em, BMEdge *e)
1192 {
1193         switch (scene->toolsettings->edge_mode) {
1194         case EDGE_MODE_SELECT:
1195                 return BM_elem_flag_test(e, BM_ELEM_SELECT) ? 1 : 0;
1196         case EDGE_MODE_TAG_SEAM:
1197                 return BM_elem_flag_test(e, BM_ELEM_SEAM);
1198         case EDGE_MODE_TAG_SHARP:
1199                 return BM_elem_flag_test(e, BM_ELEM_SHARP);
1200         case EDGE_MODE_TAG_CREASE:      
1201                 return BM_elem_float_data_get(&em->bm->edata, e, CD_CREASE) ? 1 : 0;
1202         case EDGE_MODE_TAG_BEVEL:
1203                 return BM_elem_float_data_get(&em->bm->edata, e, CD_BWEIGHT) ? 1 : 0;
1204         }
1205         return 0;
1206 }
1207
1208 static int edgetag_shortest_path(Scene *scene, BMEditMesh *em, BMEdge *source, BMEdge *target)
1209 {
1210         BMEdge *e;
1211         BMIter iter;
1212         Heap *heap;
1213         SmallHash visithash;
1214         float *cost;
1215         int i, totvert = 0, totedge = 0, *nedges, *edges, *prevedge, mednum = -1, nedgeswap = 0;
1216         int targetnum;
1217
1218         BLI_smallhash_init(&visithash);
1219
1220         /* note, would pass BM_EDGE except we are looping over all edges anyway */
1221         BM_mesh_elem_index_ensure(em->bm, BM_VERT /* | BM_EDGE */);
1222
1223         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
1224                 e->head.flags[0].f = 0;
1225                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
1226                         BLI_smallhash_insert(&visithash, (uintptr_t)e, NULL);
1227                 }
1228
1229                 BM_elem_index_set(e, totedge); /* set_inline */
1230                 totedge++;
1231         }
1232         em->bm->elem_index_dirty &= ~BM_EDGE;
1233
1234         /* alloc */
1235         totvert = em->bm->totvert;
1236         nedges = MEM_callocN(sizeof(*nedges) * totvert + 1, "SeamPathNEdges");
1237         edges = MEM_mallocN(sizeof(*edges) * totedge * 2, "SeamPathEdges");
1238         prevedge = MEM_mallocN(sizeof(*prevedge) * totedge, "SeamPathPrevious");
1239         cost = MEM_mallocN(sizeof(*cost) * totedge, "SeamPathCost");
1240
1241         /* count edges, compute adjacent edges offsets and fill adjacent */
1242         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
1243                 nedges[BM_elem_index_get(e->v1) + 1]++;
1244                 nedges[BM_elem_index_get(e->v2) + 1]++;
1245         }
1246
1247         for (i = 1; i < totvert; i++) {
1248                 int newswap = nedges[i + 1];
1249                 nedges[i + 1] = nedgeswap + nedges[i];
1250                 nedgeswap = newswap;
1251         }
1252         nedges[0] = nedges[1] = 0;
1253
1254         i = 0;
1255         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
1256                 edges[nedges[BM_elem_index_get(e->v1) + 1]++] = i;
1257                 edges[nedges[BM_elem_index_get(e->v2) + 1]++] = i;
1258
1259                 cost[i] = 1e20f;
1260                 prevedge[i] = -1;
1261                 i++;
1262         }
1263
1264         /*
1265          * Arrays are now filled as follows:
1266          *
1267          *      nedges[n] = sum of the # of edges incident to all vertices numbered 0 thru n - 1
1268          *      edges[edges[n]..edges[n - 1]] = the indices of of the edges incident to vertex n
1269          *
1270          * As the search continues, prevedge[n] will be the previous edge on the shortest
1271          * path found so far to edge n. The visitedhash will of course contain entries
1272          * for edges that have been visited, cost[n] will contain the length of the shortest
1273          * path to edge n found so far, Finally, heap is a priority heap which is built on the
1274          * the same data as the cost arry, but inverted: it is a worklist of edges prioritized
1275          * by the shortest path found so far to the edge.
1276         */
1277
1278 #if 0 /* UNUSED */ /* this block does nothing, not sure why its here? - campbell */
1279         for (i = 0; i < totvert; i++) {
1280                 int start = nedges[i], end = nedges[i + 1], cur;
1281                 for (cur = start; cur < end; cur++) {
1282                         BMEdge *e = EDBM_get_edge_for_index(em, edges[cur]);
1283                 }
1284         }
1285 #endif
1286
1287         /* regular dijkstra shortest path, but over edges instead of vertices */
1288         heap = BLI_heap_new();
1289         BLI_heap_insert(heap, 0.0f, SET_INT_IN_POINTER(BM_elem_index_get(source)));
1290         cost[BM_elem_index_get(source)] = 0.0f;
1291         EDBM_init_index_arrays(em, 1, 1, 0);
1292         targetnum = BM_elem_index_get(target);
1293
1294         while (!BLI_heap_empty(heap)) {
1295                 mednum = GET_INT_FROM_POINTER(BLI_heap_popmin(heap));
1296                 e = EDBM_get_edge_for_index(em, mednum);
1297
1298                 if (mednum == targetnum)
1299                         break;
1300
1301                 if (BLI_smallhash_haskey(&visithash, (uintptr_t)e))
1302                         continue;
1303
1304                 BLI_smallhash_insert(&visithash, (uintptr_t)e, NULL);
1305
1306                 edgetag_add_adjacent(em, &visithash, heap, mednum, BM_elem_index_get(e->v1), nedges, edges, prevedge, cost);
1307                 edgetag_add_adjacent(em, &visithash, heap, mednum, BM_elem_index_get(e->v2), nedges, edges, prevedge, cost);
1308         }
1309         
1310         if (mednum == targetnum) {
1311                 short allseams = 1;
1312
1313                 /* Check whether the path is already completely tagged.
1314                  * if it is, the tags will be cleared instead of set. */
1315                 mednum = targetnum;
1316                 do {
1317                         e = EDBM_get_edge_for_index(em, mednum);
1318                         if (!edgetag_context_check(scene, em, e)) {
1319                                 allseams = 0;
1320                                 break;
1321                         }
1322                         mednum = prevedge[mednum];
1323                 } while (mednum != BM_elem_index_get(source));
1324
1325                 /* Follow path back and source and add or remove tags */
1326                 mednum = targetnum;
1327                 do {
1328                         e = EDBM_get_edge_for_index(em, mednum);
1329                         if (allseams)
1330                                 edgetag_context_set(em, scene, e, 0);
1331                         else
1332                                 edgetag_context_set(em, scene, e, 1);
1333                         mednum = prevedge[mednum];
1334                 } while (mednum != -1);
1335         }
1336
1337         EDBM_free_index_arrays(em);
1338         MEM_freeN(nedges);
1339         MEM_freeN(edges);
1340         MEM_freeN(prevedge);
1341         MEM_freeN(cost);
1342         BLI_heap_free(heap, NULL);
1343         BLI_smallhash_release(&visithash);
1344
1345         return 1;
1346 }
1347
1348 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
1349
1350 /* since you want to create paths with multiple selects, it doesn't have extend option */
1351 static void mouse_mesh_shortest_path(bContext *C, int mval[2])
1352 {
1353         Object *ob = CTX_data_edit_object(C);
1354         ViewContext vc;
1355         BMEditMesh *em;
1356         BMEdge *e;
1357         int dist = 50;
1358         
1359         em_setup_viewcontext(C, &vc);
1360         vc.mval[0] = mval[0];
1361         vc.mval[1] = mval[1];
1362         em = vc.em;
1363         
1364         e = EDBM_findnearestedge(&vc, &dist);
1365         if (e) {
1366                 Mesh *me = vc.obedit->data;
1367                 int path = 0;
1368                 
1369                 if (em->bm->selected.last) {
1370                         BMEditSelection *ese = em->bm->selected.last;
1371                         
1372                         if (ese && ese->htype == BM_EDGE) {
1373                                 BMEdge *e_act;
1374                                 e_act = (BMEdge *)ese->data;
1375                                 if (e_act != e) {
1376                                         if (edgetag_shortest_path(vc.scene, em, e_act, e)) {
1377                                                 EDBM_remove_selection(em, e_act);
1378                                                 path = 1;
1379                                         }
1380                                 }
1381                         }
1382                 }
1383                 if (path == 0) {
1384                         int act = (edgetag_context_check(vc.scene, em, e) == 0);
1385                         edgetag_context_set(em, vc.scene, e, act); /* switch the edge option */
1386                 }
1387                 
1388                 EDBM_selectmode_flush(em);
1389
1390                 /* even if this is selected it may not be in the selection list */
1391                 if (edgetag_context_check(vc.scene, em, e) == 0)
1392                         EDBM_remove_selection(em, e);
1393                 else
1394                         EDBM_store_selection(em, e);
1395         
1396                 /* force drawmode for mesh */
1397                 switch (CTX_data_tool_settings(C)->edge_mode) {
1398                         
1399                         case EDGE_MODE_TAG_SEAM:
1400                                 me->drawflag |= ME_DRAWSEAMS;
1401                                 break;
1402                         case EDGE_MODE_TAG_SHARP:
1403                                 me->drawflag |= ME_DRAWSHARP;
1404                                 break;
1405                         case EDGE_MODE_TAG_CREASE:      
1406                                 me->drawflag |= ME_DRAWCREASES;
1407                                 break;
1408                         case EDGE_MODE_TAG_BEVEL:
1409                                 me->drawflag |= ME_DRAWBWEIGHTS;
1410                                 break;
1411                 }
1412                 
1413                 DAG_id_tag_update(ob->data, OB_RECALC_DATA);
1414                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
1415         }
1416 }
1417
1418
1419 static int mesh_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1420 {
1421         
1422         view3d_operator_needs_opengl(C);
1423
1424         mouse_mesh_shortest_path(C, event->mval);
1425         
1426         return OPERATOR_FINISHED;
1427 }
1428         
1429 void MESH_OT_select_shortest_path(wmOperatorType *ot)
1430 {
1431         /* identifiers */
1432         ot->name = "Shortest Path Select";
1433         ot->idname = "MESH_OT_select_shortest_path";
1434         
1435         /* api callbacks */
1436         ot->invoke = mesh_shortest_path_select_invoke;
1437         ot->poll = ED_operator_editmesh;
1438         ot->description = "Select shortest path between two selections";
1439         
1440         /* flags */
1441         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1442         
1443         /* properties */
1444         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
1445 }
1446
1447 /* ************************************************** */
1448 /* here actual select happens */
1449 /* gets called via generic mouse select operator */
1450 int mouse_mesh(bContext *C, const int mval[2], short extend)
1451 {
1452         ViewContext vc;
1453         BMVert *eve = NULL;
1454         BMEdge *eed = NULL;
1455         BMFace *efa = NULL;
1456         
1457         /* setup view context for argument to callbacks */
1458         em_setup_viewcontext(C, &vc);
1459         vc.mval[0] = mval[0];
1460         vc.mval[1] = mval[1];
1461         
1462         if (unified_findnearest(&vc, &eve, &eed, &efa)) {
1463                 
1464                 if (extend == 0) EDBM_flag_disable_all(vc.em, BM_ELEM_SELECT);
1465                 
1466                 if (efa) {
1467                         /* set the last selected face */
1468                         BM_active_face_set(vc.em->bm, efa);
1469                         
1470                         if (!BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1471                                 EDBM_store_selection(vc.em, efa);
1472                                 BM_elem_select_set(vc.em->bm, efa, TRUE);
1473                         }
1474                         else if (extend) {
1475                                 EDBM_remove_selection(vc.em, efa);
1476                                 BM_elem_select_set(vc.em->bm, efa, FALSE);
1477                         }
1478                 }
1479                 else if (eed) {
1480                         if (!BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1481                                 EDBM_store_selection(vc.em, eed);
1482                                 BM_elem_select_set(vc.em->bm, eed, TRUE);
1483                         }
1484                         else if (extend) {
1485                                 EDBM_remove_selection(vc.em, eed);
1486                                 BM_elem_select_set(vc.em->bm, eed, FALSE);
1487                         }
1488                 }
1489                 else if (eve) {
1490                         if (!BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
1491                                 EDBM_store_selection(vc.em, eve);
1492                                 BM_elem_select_set(vc.em->bm, eve, TRUE);
1493                         }
1494                         else if (extend) {
1495                                 EDBM_remove_selection(vc.em, eve);
1496                                 BM_elem_select_set(vc.em->bm, eve, FALSE);
1497                         }
1498                 }
1499                 
1500                 EDBM_selectmode_flush(vc.em);
1501                   
1502 //              if (EM_texFaceCheck()) {
1503
1504                 if (efa && efa->mat_nr != vc.obedit->actcol - 1) {
1505                         vc.obedit->actcol = efa->mat_nr + 1;
1506                         vc.em->mat_nr = efa->mat_nr;
1507 //                      BIF_preview_changed(ID_MA);
1508                 }
1509
1510                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit);
1511                 return 1;
1512         }
1513
1514         return 0;
1515 }
1516
1517 static void EDBM_strip_selections(BMEditMesh *em)
1518 {
1519         BMEditSelection *ese, *nextese;
1520
1521         if (!(em->selectmode & SCE_SELECT_VERTEX)) {
1522                 ese = em->bm->selected.first;
1523                 while (ese) {
1524                         nextese = ese->next;
1525                         if (ese->htype == BM_VERT) BLI_freelinkN(&(em->bm->selected), ese);
1526                         ese = nextese;
1527                 }
1528         }
1529         if (!(em->selectmode & SCE_SELECT_EDGE)) {
1530                 ese = em->bm->selected.first;
1531                 while (ese) {
1532                         nextese = ese->next;
1533                         if (ese->htype == BM_EDGE) BLI_freelinkN(&(em->bm->selected), ese);
1534                         ese = nextese;
1535                 }
1536         }
1537         if (!(em->selectmode & SCE_SELECT_FACE)) {
1538                 ese = em->bm->selected.first;
1539                 while (ese) {
1540                         nextese = ese->next;
1541                         if (ese->htype == BM_FACE) BLI_freelinkN(&(em->bm->selected), ese);
1542                         ese = nextese;
1543                 }
1544         }
1545 }
1546
1547 /* when switching select mode, makes sure selection is consistant for editing */
1548 /* also for paranoia checks to make sure edge or face mode works */
1549 void EDBM_selectmode_set(BMEditMesh *em)
1550 {
1551         BMVert *eve;
1552         BMEdge *eed;
1553         BMFace *efa;
1554         BMIter iter;
1555         
1556         em->bm->selectmode = em->selectmode;
1557
1558         EDBM_strip_selections(em); /* strip BMEditSelections from em->selected that are not relevant to new mode */
1559         
1560         if (em->selectmode & SCE_SELECT_VERTEX) {
1561                 EDBM_select_flush(em);
1562         }
1563         else if (em->selectmode & SCE_SELECT_EDGE) {
1564                 /* deselect vertices, and select again based on edge select */
1565                 eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1566                 for ( ; eve; eve = BM_iter_step(&iter)) BM_elem_select_set(em->bm, eve, FALSE);
1567                 
1568                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1569                 for ( ; eed; eed = BM_iter_step(&iter)) {
1570                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1571                                 BM_elem_select_set(em->bm, eed, TRUE);
1572                         }
1573                 }
1574                 
1575                 /* selects faces based on edge status */
1576                 EDBM_selectmode_flush(em);
1577         }
1578         else if (em->selectmode & SCE_SELECT_FACE) {
1579                 /* deselect eges, and select again based on face select */
1580                 eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1581                 for ( ; eed; eed = BM_iter_step(&iter)) BM_elem_select_set(em->bm, eed, FALSE);
1582                 
1583                 efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1584                 for ( ; efa; efa = BM_iter_step(&iter)) {
1585                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1586                                 BM_elem_select_set(em->bm, efa, TRUE);
1587                         }
1588                 }
1589         }
1590 }
1591
1592 void EDBM_convertsel(BMEditMesh *em, short oldmode, short selectmode)
1593 {
1594         BMEdge *eed;
1595         BMFace *efa;
1596         BMIter iter;
1597
1598         /* have to find out what the selectionmode was previously */
1599         if (oldmode == SCE_SELECT_VERTEX) {
1600                 if (selectmode == SCE_SELECT_EDGE) {
1601                         /* select all edges associated with every selected vertex */
1602                         eed = BM_iter_new(&iter, em->bm, BM_EDGES_OF_MESH, NULL);
1603                         for ( ; eed; eed = BM_iter_step(&iter)) {
1604                                 if ( (BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) ||
1605                                       BM_elem_flag_test(eed->v2, BM_ELEM_SELECT)))
1606                                 {
1607                                         BM_elem_select_set(em->bm, eed, TRUE);
1608                                 }
1609                         }
1610                 }               
1611                 else if (selectmode == SCE_SELECT_FACE) {
1612                         BMIter liter;
1613                         BMLoop *l;
1614
1615                         /* select all faces associated with every selected vertex */
1616                         efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1617                         for ( ; efa; efa = BM_iter_step(&iter)) {
1618                                 l = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
1619                                 for (; l; l = BM_iter_step(&liter)) {
1620                                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
1621                                                 BM_elem_select_set(em->bm, efa, TRUE);
1622                                                 break;
1623                                         }
1624                                 }
1625                         }
1626                 }
1627         }
1628         
1629         if (oldmode == SCE_SELECT_EDGE) {
1630                 if (selectmode == SCE_SELECT_FACE) {
1631                         BMIter liter;
1632                         BMLoop *l;
1633
1634                         /* select all faces associated with every selected vertex */
1635                         efa = BM_iter_new(&iter, em->bm, BM_FACES_OF_MESH, NULL);
1636                         for ( ; efa; efa = BM_iter_step(&iter)) {
1637                                 l = BM_iter_new(&liter, em->bm, BM_LOOPS_OF_FACE, efa);
1638                                 for (; l; l = BM_iter_step(&liter)) {
1639                                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT)) {
1640                                                 BM_elem_select_set(em->bm, efa, TRUE);
1641                                                 break;
1642                                         }
1643                                 }
1644                         }
1645                 }
1646         }
1647 }
1648
1649
1650 void EDBM_deselect_by_material(struct BMEditMesh *em, const short index, const short select)
1651 {
1652         BMIter iter;
1653         BMFace *efa;
1654
1655         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1656                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1657                         continue;
1658                 if (efa->mat_nr == index) {
1659                         BM_elem_select_set(em->bm, efa, select);
1660                 }
1661         }
1662 }
1663
1664
1665 void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
1666 {
1667         BMIter iter;
1668         BMVert *eve;
1669         BMEdge *eed;
1670         BMFace *efa;
1671         
1672         if (em->bm->selectmode & SCE_SELECT_VERTEX) {
1673                 BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1674                         if (BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
1675                                 continue;
1676                         BM_elem_select_set(em->bm, eve, !BM_elem_flag_test(eve, BM_ELEM_SELECT));
1677                 }
1678         }
1679         else if (em->selectmode & SCE_SELECT_EDGE) {
1680                 BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
1681                         if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
1682                                 continue;
1683                         BM_elem_select_set(em->bm, eed, !BM_elem_flag_test(eed, BM_ELEM_SELECT));
1684                 }
1685         }
1686         else {
1687                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1688                         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1689                                 continue;
1690                         BM_elem_select_set(em->bm, efa, !BM_elem_flag_test(efa, BM_ELEM_SELECT));
1691                 }
1692
1693         }
1694 //      if (EM_texFaceCheck())
1695 }
1696
1697 static void linked_limit_default(bContext *C, wmOperator *op)
1698 {
1699         if (!RNA_struct_property_is_set(op->ptr, "limit")) {
1700                 Object *obedit = CTX_data_edit_object(C);
1701                 BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
1702                 if (em->selectmode == SCE_SELECT_FACE)
1703                         RNA_boolean_set(op->ptr, "limit", TRUE);
1704                 else
1705                         RNA_boolean_set(op->ptr, "limit", FALSE);
1706         }
1707 }
1708
1709 static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
1710 {
1711         Object *obedit = CTX_data_edit_object(C);
1712         ViewContext vc;
1713         BMesh *bm;
1714         BMWalker walker;
1715         BMEditMesh *em;
1716         BMVert *eve;
1717         BMEdge *e, *eed;
1718         BMFace *efa;
1719         int sel = !RNA_boolean_get(op->ptr, "deselect");
1720
1721         int limit;
1722
1723         linked_limit_default(C, op);
1724
1725         limit = RNA_boolean_get(op->ptr, "limit");
1726
1727         /* unified_finednearest needs ogl */
1728         view3d_operator_needs_opengl(C);
1729         
1730         /* setup view context for argument to callbacks */
1731         em_setup_viewcontext(C, &vc);
1732         em = vc.em;
1733
1734         if (em->bm->totedge == 0)
1735                 return OPERATOR_CANCELLED;
1736         
1737         bm = em->bm;
1738
1739         vc.mval[0] = event->mval[0];
1740         vc.mval[1] = event->mval[1];
1741         
1742         /* return warning! */
1743         
1744         if (unified_findnearest(&vc, &eve, &eed, &efa) == 0) {
1745                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
1746         
1747                 return OPERATOR_CANCELLED;
1748         }
1749         
1750         if (em->selectmode == SCE_SELECT_FACE) {
1751                 BMIter iter;
1752
1753                 if (efa == NULL)
1754                         return OPERATOR_CANCELLED;
1755
1756                 if (limit) {
1757                         BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
1758                                 if (!BM_elem_flag_test(e, BM_ELEM_SEAM)) BMO_elem_flag_enable(bm, e, BM_ELEM_SELECT);
1759                                 else                           BMO_elem_flag_disable(bm, e, BM_ELEM_SELECT); /* is this needed ? */
1760                         }
1761                 }
1762
1763                 /* walk */
1764                 BMW_init(&walker, bm, BMW_ISLAND,
1765                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1766                          BMW_NIL_LAY);
1767
1768                 e = BMW_begin(&walker, efa);
1769                 for (; efa; efa = BMW_step(&walker)) {
1770                         BM_elem_select_set(bm, efa, sel);
1771                 }
1772                 BMW_end(&walker);
1773         }
1774         else {
1775                 if (efa) {
1776                         eed = BM_FACE_FIRST_LOOP(efa)->e;
1777                 }
1778                 else if (!eed) {
1779                         if (!eve || !eve->e)
1780                                 return OPERATOR_CANCELLED;
1781
1782                         eed = eve->e;
1783                 }
1784
1785                 BMW_init(&walker, bm, BMW_SHELL,
1786                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1787                          BMW_NIL_LAY);
1788
1789                 e = BMW_begin(&walker, eed->v1);
1790                 for ( ; e; e = BMW_step(&walker)) {
1791                         BM_elem_select_set(bm, e, sel);
1792                 }
1793                 BMW_end(&walker);
1794         }
1795
1796         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
1797         return OPERATOR_FINISHED;
1798 }
1799
1800 void MESH_OT_select_linked_pick(wmOperatorType *ot)
1801 {
1802         /* identifiers */
1803         ot->name = "Select Linked";
1804         ot->idname = "MESH_OT_select_linked_pick";
1805         
1806         /* api callbacks */
1807         ot->invoke = select_linked_pick_invoke;
1808         ot->poll = ED_operator_editmesh;
1809         ot->description = "select/deselect all vertices linked to the edge under the mouse cursor";
1810         
1811         /* flags */
1812         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1813         
1814         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
1815         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
1816 }
1817
1818
1819 static int select_linked_exec(bContext *C, wmOperator *op)
1820 {
1821         Object *obedit = CTX_data_edit_object(C);
1822         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
1823         BMesh *bm = em->bm;
1824         BMIter iter;
1825         BMVert *v;
1826         BMEdge *e;
1827         BMWalker walker;
1828
1829         int limit;
1830
1831         linked_limit_default(C, op);
1832
1833         limit = RNA_boolean_get(op->ptr, "limit");
1834
1835         if (em->selectmode == SCE_SELECT_FACE) {
1836                 BMFace *efa;
1837
1838                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1839                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1840                                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
1841                         }
1842                         else {
1843                                 BM_elem_flag_disable(efa, BM_ELEM_TAG);
1844                         }
1845                 }
1846
1847                 if (limit) {
1848                         BM_ITER(e, &iter, bm, BM_EDGES_OF_MESH, NULL) {
1849                                 if (!BM_elem_flag_test(e, BM_ELEM_SEAM)) BMO_elem_flag_enable(bm, e, BM_ELEM_SELECT);
1850                                 else                           BMO_elem_flag_disable(bm, e, BM_ELEM_SELECT); /* is this needed ? */
1851                         }
1852                 }
1853
1854                 BMW_init(&walker, bm, BMW_ISLAND,
1855                          BMW_MASK_NOP, limit ? BM_ELEM_SELECT : BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1856                          BMW_NIL_LAY);
1857
1858                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1859                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
1860                                 e = BMW_begin(&walker, efa);
1861                                 for (; efa; efa = BMW_step(&walker)) {
1862                                         BM_elem_select_set(bm, efa, TRUE);
1863                                 }
1864                         }
1865                 }
1866                 BMW_end(&walker);
1867         }
1868         else  {
1869                 BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1870                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) && !BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
1871                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
1872                         }
1873                         else {
1874                                 BM_elem_flag_disable(v, BM_ELEM_TAG);
1875                         }
1876                 }
1877
1878                 BMW_init(&walker, em->bm, BMW_SHELL,
1879                          BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP, BMW_MASK_NOP,
1880                          BMW_NIL_LAY);
1881                 BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1882                         if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
1883                                 e = BMW_begin(&walker, v);
1884                                 for (; e; e = BMW_step(&walker)) {
1885                                         BM_elem_select_set(em->bm, e->v1, TRUE);
1886                                         BM_elem_select_set(em->bm, e->v2, TRUE);
1887                                 }
1888                         }
1889                 }
1890                 BMW_end(&walker);
1891         }
1892         EDBM_selectmode_flush_ex(em, SCE_SELECT_VERTEX);
1893
1894         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
1895
1896         return OPERATOR_FINISHED;
1897 }
1898
1899 void MESH_OT_select_linked(wmOperatorType *ot)
1900 {
1901         /* identifiers */
1902         ot->name = "Select Linked All";
1903         ot->idname = "MESH_OT_select_linked";
1904         
1905         /* api callbacks */
1906         ot->exec = select_linked_exec;
1907         ot->poll = ED_operator_editmesh;
1908         ot->description = "Select all vertices linked to the active mesh";
1909         
1910         /* flags */
1911         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1912         
1913         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "");
1914 }
1915
1916 /* ******************** **************** */
1917
1918 static int select_more(bContext *C, wmOperator *UNUSED(op))
1919 {
1920         Object *obedit = CTX_data_edit_object(C);
1921         BMEditMesh *em = (((Mesh *)obedit->data))->edit_btmesh;
1922
1923         EDBM_select_more(em);
1924
1925         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
1926         return OPERATOR_FINISHED;
1927 }
1928
1929 void MESH_OT_select_more(wmOperatorType *ot)
1930 {
1931         /* identifiers */
1932         ot->name = "Select More";
1933         ot->idname = "MESH_OT_select_more";
1934         ot->description = "Select more vertices, edges or faces connected to initial selection";
1935
1936         /* api callbacks */
1937         ot->exec = select_more;
1938         ot->poll = ED_operator_editmesh;
1939         
1940         /* flags */
1941         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1942 }
1943
1944 static int select_less(bContext *C, wmOperator *UNUSED(op))
1945 {
1946         Object *obedit = CTX_data_edit_object(C);
1947         BMEditMesh *em = (((Mesh *)obedit->data))->edit_btmesh;
1948
1949         EDBM_select_less(em);
1950
1951         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
1952         return OPERATOR_FINISHED;
1953 }
1954
1955 void MESH_OT_select_less(wmOperatorType *ot)
1956 {
1957         /* identifiers */
1958         ot->name = "Select Less";
1959         ot->idname = "MESH_OT_select_less";
1960         ot->description = "Deselect vertices, edges or faces at the boundary of each selection region";
1961
1962         /* api callbacks */
1963         ot->exec = select_less;
1964         ot->poll = ED_operator_editmesh;
1965         
1966         /* flags */
1967         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1968 }
1969
1970 /* Walk all reachable elements of the same type as h_act in breadth-first
1971    order, starting from h_act. Deselects elements if the depth when they
1972    are reached is not a multiple of "nth". */
1973 static void walker_deselect_nth(BMEditMesh *em, int nth, int offset, BMHeader *h_act)
1974 {
1975         BMHeader *h;
1976         BMesh *bm = em->bm;
1977         BMWalker walker;
1978         BMIter iter;
1979         int walktype = 0, itertype = 0, flushtype = 0;
1980         short mask_vert = 0, mask_edge = 0, mask_loop = 0, mask_face = 0;
1981
1982         /* No active element from which to start - nothing to do */
1983         if (h_act == NULL) {
1984                 return;
1985         }
1986
1987         /* Determine which type of iter, walker, and select flush to use
1988          * based on type of the elements being deselected */
1989         switch (h_act->htype) {
1990         case BM_VERT:
1991                 itertype = BM_VERTS_OF_MESH;
1992                 walktype = BMW_CONNECTED_VERTEX;
1993                 flushtype = SCE_SELECT_VERTEX;
1994                 mask_vert = BM_ELEM_SELECT;
1995                 break;
1996         case BM_EDGE:
1997                 itertype = BM_EDGES_OF_MESH;
1998                 walktype = BMW_SHELL;
1999                 flushtype = SCE_SELECT_EDGE;
2000                 mask_edge = BM_ELEM_SELECT;
2001                 break;
2002         case BM_FACE:
2003                 itertype = BM_FACES_OF_MESH;
2004                 walktype = BMW_ISLAND;
2005                 flushtype = SCE_SELECT_FACE;
2006                 mask_face = BM_ELEM_SELECT;
2007                 break;
2008         }
2009
2010         /* Walker restrictions uses BMO flags, not header flags,
2011          * so transfer BM_ELEM_SELECT from HFlags onto a BMO flag layer. */
2012         BMO_push(bm, NULL);
2013         BM_ITER(h, &iter, bm, itertype, NULL) {
2014                 if (BM_elem_flag_test(h, BM_ELEM_SELECT)) {
2015                         BMO_elem_flag_enable(bm, h, BM_ELEM_SELECT);
2016                 }
2017         }
2018
2019         /* Walk over selected elements starting at active */
2020         BMW_init(&walker, bm, walktype,
2021                  mask_vert, mask_edge, mask_loop, mask_face,
2022                  BMW_NIL_LAY);
2023
2024         BLI_assert(walker.order == BMW_BREADTH_FIRST);
2025         for (h = BMW_begin(&walker, h_act); h != NULL; h = BMW_step(&walker)) {
2026                 /* Deselect elements that aren't at "nth" depth from active */
2027                 if ((offset + BMW_current_depth(&walker)) % nth) {
2028                         BM_elem_select_set(bm, h, FALSE);
2029                 }
2030         }
2031         BMW_end(&walker);
2032
2033         BMO_pop(bm);
2034
2035         /* Flush selection up */
2036         EDBM_selectmode_flush_ex(em, flushtype);
2037 }
2038
2039 static void deselect_nth_active(BMEditMesh *em, BMVert **v_p, BMEdge **e_p, BMFace **f_p)
2040 {
2041         BMVert *v;
2042         BMEdge *e;
2043         BMFace *f;
2044         BMIter iter;
2045         BMEditSelection *ese;
2046
2047         *v_p = NULL;
2048         *e_p = NULL;
2049         *f_p = NULL;
2050
2051         EDBM_selectmode_flush(em);
2052         ese = (BMEditSelection *)em->bm->selected.last;
2053
2054         if (ese) {
2055                 switch(ese->htype) {
2056                 case BM_VERT:
2057                         *v_p = (BMVert *)ese->data;
2058                         return;
2059                 case BM_EDGE:
2060                         *e_p = (BMEdge *)ese->data;
2061                         return;
2062                 case BM_FACE:
2063                         *f_p = (BMFace *)ese->data;
2064                         return;
2065                 }
2066         }
2067
2068         if (em->selectmode & SCE_SELECT_VERTEX) {
2069                 BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
2070                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
2071                                 *v_p = v;
2072                                 return;
2073                         }
2074                 }
2075         }
2076         else if (em->selectmode & SCE_SELECT_EDGE) {
2077                 BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2078                         if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2079                                 *e_p = e;
2080                                 return;
2081                         }
2082                 }
2083         }
2084         else if (em->selectmode & SCE_SELECT_FACE) {
2085                 f = BM_active_face_get(em->bm, TRUE);
2086                 if (f) {
2087                         *f_p = f;
2088                         return;
2089                 }
2090         }
2091 }
2092
2093 static int EM_deselect_nth(BMEditMesh *em, int nth, int offset)
2094 {
2095         BMVert *v;
2096         BMEdge *e;
2097         BMFace *f;
2098
2099         deselect_nth_active(em, &v, &e, &f);
2100
2101         if (v) {
2102                 walker_deselect_nth(em, nth, offset, &v->head);
2103                 return 1;
2104         }
2105         else if (e) {
2106                 walker_deselect_nth(em, nth, offset, &e->head);
2107                 return 1;
2108         }
2109         else if (f) {
2110                 walker_deselect_nth(em, nth, offset, &f->head);
2111                 return 1;
2112         }
2113
2114         return 0;
2115 }
2116
2117 static int mesh_select_nth_exec(bContext *C, wmOperator *op)
2118 {
2119         Object *obedit = CTX_data_edit_object(C);
2120         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2121         int nth = RNA_int_get(op->ptr, "nth");
2122         int offset = RNA_int_get(op->ptr, "offset");
2123
2124         offset = MIN2(nth, offset);
2125
2126         if (EM_deselect_nth(em, nth, offset) == 0) {
2127                 BKE_report(op->reports, RPT_ERROR, "Mesh has no active vert/edge/face");
2128                 return OPERATOR_CANCELLED;
2129         }
2130
2131         DAG_id_tag_update(obedit->data, OB_RECALC_DATA);
2132         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
2133
2134         return OPERATOR_FINISHED;
2135 }
2136
2137
2138 void MESH_OT_select_nth(wmOperatorType *ot)
2139 {
2140         /* identifiers */
2141         ot->name = "Select Nth";
2142         ot->description = "";
2143         ot->idname = "MESH_OT_select_nth";
2144
2145         /* api callbacks */
2146         ot->exec = mesh_select_nth_exec;
2147         ot->poll = ED_operator_editmesh;
2148
2149         /* flags */
2150         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2151
2152         RNA_def_int(ot->srna, "nth", 2, 2, 100, "Nth Selection", "", 1, INT_MAX);
2153         RNA_def_int(ot->srna, "offset", 0, 0, 100, "Offset", "", 0, INT_MAX);
2154 }
2155
2156 void em_setup_viewcontext(bContext *C, ViewContext *vc)
2157 {
2158         view3d_set_viewcontext(C, vc);
2159         
2160         if (vc->obedit) {
2161                 Mesh *me = vc->obedit->data;
2162                 vc->em = me->edit_btmesh;
2163         }
2164 }
2165
2166 /* poll call for mesh operators requiring a view3d context */
2167 int EM_view3d_poll(bContext *C)
2168 {
2169         if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
2170                 return 1;
2171         return 0;
2172 }
2173
2174
2175 static int select_sharp_edges_exec(bContext *C, wmOperator *op)
2176 {
2177         /* Find edges that have exactly two neighboring faces,
2178         * check the angle between those faces, and if angle is
2179         * small enough, select the edge
2180         */
2181         Object *obedit = CTX_data_edit_object(C);
2182         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2183         BMIter iter;
2184         BMEdge *e;
2185         BMLoop *l1, *l2;
2186         float sharp = RNA_float_get(op->ptr, "sharpness"), angle;
2187
2188         sharp = DEG2RADF(sharp);
2189
2190         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2191                 if (BM_elem_flag_test(e, BM_ELEM_HIDDEN) || !e->l)
2192                         continue;
2193
2194                 l1 = e->l;
2195                 l2 = l1->radial_next;
2196
2197                 if (l1 == l2)
2198                         continue;
2199
2200                 /* edge has exactly two neighboring faces, check angle */
2201                 angle = angle_normalized_v3v3(l1->f->no, l2->f->no);
2202
2203                 if (fabsf(angle) > sharp) {
2204                         BM_elem_select_set(em->bm, e, TRUE);
2205                 }
2206
2207         }
2208
2209         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2210
2211         return OPERATOR_FINISHED;
2212 }
2213
2214 void MESH_OT_edges_select_sharp(wmOperatorType *ot)
2215 {
2216         /* identifiers */
2217         ot->name = "Select Sharp Edges";
2218         ot->description = "Marked selected edges as sharp";
2219         ot->idname = "MESH_OT_edges_select_sharp";
2220         
2221         /* api callbacks */
2222         ot->exec = select_sharp_edges_exec;
2223         ot->poll = ED_operator_editmesh;
2224         
2225         /* flags */
2226         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2227         
2228         /* props */
2229         RNA_def_float(ot->srna, "sharpness", 1.0f, 0.01f, FLT_MAX, "sharpness", "", 1.0f, 180.0f);
2230 }
2231
2232 static int select_linked_flat_faces_exec(bContext *C, wmOperator *op)
2233 {
2234         Object *obedit = CTX_data_edit_object(C);
2235         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2236         BMIter iter, liter, liter2;
2237         BMFace *f, **stack = NULL;
2238         BLI_array_declare(stack);
2239         BMLoop *l, *l2;
2240         float sharp = RNA_float_get(op->ptr, "sharpness");
2241         int i;
2242
2243         sharp = (sharp * M_PI) / 180.0;
2244
2245         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2246                 BM_elem_flag_disable(f, BM_ELEM_TAG);
2247         }
2248
2249         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2250                 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))
2251                         continue;
2252
2253                 BLI_array_empty(stack);
2254                 i = 1;
2255
2256                 BLI_array_growone(stack);
2257                 stack[i - 1] = f;
2258
2259                 while (i) {
2260                         f = stack[i - 1];
2261                         i--;
2262
2263                         BM_elem_select_set(em->bm, f, TRUE);
2264
2265                         BM_elem_flag_enable(f, BM_ELEM_TAG);
2266
2267                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, f) {
2268                                 BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_LOOP, l) {
2269                                         float angle;
2270
2271                                         if (BM_elem_flag_test(l2->f, BM_ELEM_TAG) || BM_elem_flag_test(l2->f, BM_ELEM_HIDDEN))
2272                                                 continue;
2273
2274                                         /* edge has exactly two neighboring faces, check angle */
2275                                         angle = angle_normalized_v3v3(f->no, l2->f->no);
2276
2277                                         /* invalidate: edge too sharp */
2278                                         if (angle < sharp) {
2279                                                 BLI_array_growone(stack);
2280                                                 stack[i] = l2->f;
2281                                                 i++;
2282                                         }
2283                                 }
2284                         }
2285                 }
2286         }
2287
2288         BLI_array_free(stack);
2289
2290         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2291
2292         return OPERATOR_FINISHED;
2293 }
2294
2295 void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
2296 {
2297         /* identifiers */
2298         ot->name = "Select Linked Flat Faces";
2299         ot->description = "Select linked faces by angle";
2300         ot->idname = "MESH_OT_faces_select_linked_flat";
2301         
2302         /* api callbacks */
2303         ot->exec = select_linked_flat_faces_exec;
2304         ot->poll = ED_operator_editmesh;
2305         
2306         /* flags */
2307         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2308         
2309         /* props */
2310         RNA_def_float(ot->srna, "sharpness", 1.0f, 0.01f, FLT_MAX, "sharpness", "", 1.0f, 180.0f);
2311 }
2312
2313 static int select_non_manifold_exec(bContext *C, wmOperator *op)
2314 {
2315         Object *obedit = CTX_data_edit_object(C);
2316         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2317         BMVert *v;
2318         BMEdge *e;
2319         BMIter iter;
2320
2321         /* Selects isolated verts, and edges that do not have 2 neighboring
2322          * faces
2323          */
2324         
2325         if (em->selectmode == SCE_SELECT_FACE) {
2326                 BKE_report(op->reports, RPT_ERROR, "Doesn't work in face selection mode");
2327                 return OPERATOR_CANCELLED;
2328         }
2329         
2330         BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
2331                 if (!BM_elem_flag_test(em->bm, BM_ELEM_HIDDEN) && BM_vert_is_nonmanifold(em->bm, v)) {
2332                         BM_elem_select_set(em->bm, v, TRUE);
2333                 }
2334         }
2335         
2336         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2337                 if (!BM_elem_flag_test(em->bm, BM_ELEM_HIDDEN) && BM_edge_face_count(e) != 2) {
2338                         BM_elem_select_set(em->bm, e, TRUE);
2339                 }
2340         }
2341
2342         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2343
2344         return OPERATOR_FINISHED;
2345 }
2346
2347 void MESH_OT_select_non_manifold(wmOperatorType *ot)
2348 {
2349         /* identifiers */
2350         ot->name = "Select Non Manifold";
2351         ot->description = "Select all non-manifold vertices or edges";
2352         ot->idname = "MESH_OT_select_non_manifold";
2353         
2354         /* api callbacks */
2355         ot->exec = select_non_manifold_exec;
2356         ot->poll = ED_operator_editmesh;
2357         
2358         /* flags */
2359         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2360 }
2361
2362 static int mesh_select_random_exec(bContext *C, wmOperator *op)
2363 {
2364         Object *obedit = CTX_data_edit_object(C);
2365         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2366         BMVert *eve;
2367         BMEdge *eed;
2368         BMFace *efa;
2369         BMIter iter;
2370         float randfac =  RNA_float_get(op->ptr, "percent")/100.0f;
2371
2372         BLI_srand(BLI_rand()); /* random seed */
2373         
2374         if (!RNA_boolean_get(op->ptr, "extend"))
2375                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2376
2377         if (em->selectmode & SCE_SELECT_VERTEX) {
2378                 BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
2379                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2380                                 BM_elem_select_set(em->bm, eve, TRUE);
2381                         }
2382                 }
2383                 EDBM_selectmode_flush(em);
2384         }
2385         else if (em->selectmode & SCE_SELECT_EDGE) {
2386                 BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2387                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2388                                 BM_elem_select_set(em->bm, eed, TRUE);
2389                         }
2390                 }
2391                 EDBM_selectmode_flush(em);
2392         }
2393         else {
2394                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2395                         if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && BLI_frand() < randfac) {
2396                                 BM_elem_select_set(em->bm, efa, TRUE);
2397                         }
2398                 }
2399                 EDBM_selectmode_flush(em);
2400         }
2401         
2402         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2403         
2404         return OPERATOR_FINISHED;
2405 }
2406
2407 void MESH_OT_select_random(wmOperatorType *ot)
2408 {
2409         /* identifiers */
2410         ot->name = "Select Random";
2411         ot->description = "Randomly select vertices";
2412         ot->idname = "MESH_OT_select_random";
2413
2414         /* api callbacks */
2415         ot->exec = mesh_select_random_exec;
2416         ot->poll = ED_operator_editmesh;
2417
2418         /* flags */
2419         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2420         
2421         /* props */
2422         RNA_def_float_percentage(ot->srna, "percent", 50.f, 0.0f, 100.0f,
2423                                  "Percent", "Percentage of elements to select randomly", 0.f, 100.0f);
2424         RNA_def_boolean(ot->srna, "extend", 0,
2425                         "Extend Selection", "Extend selection instead of deselecting everything first");
2426 }
2427
2428 static int select_next_loop(bContext *C, wmOperator *UNUSED(op))
2429 {
2430         Object *obedit = CTX_data_edit_object(C);
2431         BMEditMesh *em = (((Mesh *)obedit->data))->edit_btmesh;
2432         BMFace *f;
2433         BMVert *v;
2434         BMIter iter;
2435         
2436         BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
2437                 BM_elem_flag_disable(v, BM_ELEM_TAG);
2438         }
2439         
2440         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2441                 BMLoop *l;
2442                 BMIter liter;
2443                 
2444                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, f) {
2445                         if (BM_elem_flag_test(l->v, BM_ELEM_SELECT) && !BM_elem_flag_test(l->v, BM_ELEM_HIDDEN)) {
2446                                 BM_elem_flag_enable(l->next->v, BM_ELEM_TAG);
2447                                 BM_elem_select_set(em->bm, l->v, FALSE);
2448                         }
2449                 }
2450         }
2451
2452         BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
2453                 if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
2454                         BM_elem_select_set(em->bm, v, TRUE);
2455                 }
2456         }
2457
2458         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit);
2459         return OPERATOR_FINISHED;
2460 }
2461
2462 void MESH_OT_select_next_loop(wmOperatorType *ot)
2463 {
2464         /* identifiers */
2465         ot->name = "Select Next Loop";
2466         ot->idname = "MESH_OT_select_next_loop";
2467         ot->description = "";
2468
2469         /* api callbacks */
2470         ot->exec = select_next_loop;
2471         ot->poll = ED_operator_editmesh;
2472         
2473         /* flags */
2474         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2475 }
2476
2477
2478 static int region_to_loop(bContext *C, wmOperator *UNUSED(op))
2479 {
2480         Object *obedit = CTX_data_edit_object(C);
2481         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2482         BMFace *f;
2483         BMEdge *e;
2484         BMIter iter;
2485         ViewContext vc;
2486         
2487         em_setup_viewcontext(C, &vc);
2488         
2489         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2490                 BM_elem_flag_disable(e, BM_ELEM_TAG);
2491         }
2492
2493         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2494                 BMLoop *l1, *l2;
2495                 BMIter liter1, liter2;
2496                 
2497                 BM_ITER(l1, &liter1, em->bm, BM_LOOPS_OF_FACE, f) {
2498                         int tot = 0, totsel = 0;
2499                         
2500                         BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_EDGE, l1->e) {
2501                                 tot++;
2502                                 totsel += BM_elem_flag_test(l2->f, BM_ELEM_SELECT) != 0;
2503                         }
2504                         
2505                         if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
2506                                 BM_elem_flag_enable(l1->e, BM_ELEM_TAG);
2507                 }
2508         }
2509
2510         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2511         
2512         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2513                 if (BM_elem_flag_test(e, BM_ELEM_TAG) && !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
2514                         BM_edge_select_set(em->bm, e, TRUE);
2515         }
2516
2517         /* If in face-only select mode, switch to edge select mode so that
2518            an edge-only selection is not inconsistent state */
2519         if (em->selectmode == SCE_SELECT_FACE) {
2520                 em->selectmode = SCE_SELECT_EDGE;
2521                 EDBM_selectmode_set(em);
2522                 EDBM_selectmode_to_scene(C);
2523         }
2524
2525         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2526
2527         return OPERATOR_FINISHED;
2528 }
2529
2530 void MESH_OT_region_to_loop(wmOperatorType *ot)
2531 {
2532         /* identifiers */
2533         ot->name = "Select Boundary Loop";
2534         ot->idname = "MESH_OT_region_to_loop";
2535
2536         /* api callbacks */
2537         ot->exec = region_to_loop;
2538         ot->poll = ED_operator_editmesh;
2539
2540         /* flags */
2541         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2542 }
2543
2544 static int loop_find_region(BMEditMesh *em, BMLoop *l, int flag, 
2545         SmallHash *fhash, BMFace ***region_out)
2546 {
2547         BLI_array_declare(region);
2548         BLI_array_declare(stack);
2549         BMFace **region = NULL, *f;
2550         BMFace **stack = NULL;
2551         
2552         BLI_array_append(stack, l->f);
2553         BLI_smallhash_insert(fhash, (uintptr_t)l->f, NULL);
2554         
2555         while (BLI_array_count(stack) > 0) {
2556                 BMIter liter1, liter2;
2557                 BMLoop *l1, *l2;
2558                 
2559                 f = BLI_array_pop(stack);
2560                 BLI_array_append(region, f);
2561                 
2562                 BM_ITER(l1, &liter1, em->bm, BM_LOOPS_OF_FACE, f) {
2563                         if (BM_elem_flag_test(l1->e, flag))
2564                                 continue;
2565                         
2566                         BM_ITER(l2, &liter2, em->bm, BM_LOOPS_OF_EDGE, l1->e) {
2567                                 if (BLI_smallhash_haskey(fhash, (uintptr_t)l2->f))
2568                                         continue;
2569                                 
2570                                 BLI_array_append(stack, l2->f);
2571                                 BLI_smallhash_insert(fhash, (uintptr_t)l2->f, NULL);
2572                         }
2573                 }
2574         }
2575         
2576         BLI_array_free(stack);
2577         
2578         *region_out = region;
2579         return BLI_array_count(region);
2580 }
2581
2582 static int verg_radial(const void *va, const void *vb)
2583 {
2584         BMEdge *e1 = *((void **)va);
2585         BMEdge *e2 = *((void **)vb);
2586         int a, b;
2587         
2588         a = BM_edge_face_count(e1);
2589         b = BM_edge_face_count(e2);
2590         
2591         if (a > b)  return -1;
2592         if (a == b) return  0;
2593         if (a < b)  return  1;
2594         
2595         return -1;
2596 }
2597
2598 static int loop_find_regions(BMEditMesh *em, int selbigger)
2599 {
2600         SmallHash visithash;
2601         BMIter iter;
2602         BMEdge *e, **edges = NULL;
2603         BLI_array_declare(edges);
2604         BMFace *f;
2605         int count = 0, i;
2606         
2607         BLI_smallhash_init(&visithash);
2608         
2609         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2610                 BM_elem_flag_disable(f, BM_ELEM_TAG);
2611         }
2612
2613         BM_ITER(e, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
2614                 if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
2615                         BLI_array_append(edges, e);
2616                         BM_elem_flag_enable(e, BM_ELEM_TAG);
2617                 }
2618                 else {
2619                         BM_elem_flag_disable(e, BM_ELEM_TAG);
2620                 }
2621         }
2622         
2623         /* sort edges by radial cycle length */
2624         qsort(edges,  BLI_array_count(edges), sizeof(void *), verg_radial);
2625         
2626         for (i = 0; i < BLI_array_count(edges); i++) {
2627                 BMIter liter;
2628                 BMLoop *l;
2629                 BMFace **region = NULL, **r;
2630                 int c, tot = 0;
2631                 
2632                 e = edges[i];
2633                 
2634                 if (!BM_elem_flag_test(e, BM_ELEM_TAG))
2635                         continue;
2636                 
2637                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_EDGE, e) {
2638                         if (BLI_smallhash_haskey(&visithash, (uintptr_t)l->f))
2639                                 continue;
2640                                                 
2641                         c = loop_find_region(em, l, BM_ELEM_SELECT, &visithash, &r);
2642
2643                         if (!region || (selbigger ? c >= tot : c < tot)) {
2644                                 /* this region is the best seen so far */
2645                                 tot = c;
2646                                 if (region) {
2647                                         /* free the previous best */
2648                                         MEM_freeN(region);
2649                                 }
2650                                 /* track the current region as the new best */
2651                                 region = r;
2652                         }
2653                         else {
2654                                 /* this region is not as good as best so far, just free it */
2655                                 MEM_freeN(r);
2656                         }
2657                 }
2658                 
2659                 if (region) {
2660                         int j;
2661                         
2662                         for (j = 0; j < tot; j++) {
2663                                 BM_elem_flag_enable(region[j], BM_ELEM_TAG);
2664                                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, region[j]) {
2665                                         BM_elem_flag_disable(l->e, BM_ELEM_TAG);
2666                                 }
2667                         }
2668                         
2669                         count += tot;
2670                         
2671                         MEM_freeN(region);
2672                 }
2673         }
2674         
2675         BLI_array_free(edges);
2676         BLI_smallhash_release(&visithash);
2677         
2678         return count;
2679 }
2680
2681 static int loop_to_region(bContext *C, wmOperator *op)
2682 {
2683         Object *obedit = CTX_data_edit_object(C);
2684         BMEditMesh *em = ((Mesh *)obedit->data)->edit_btmesh;
2685         BMIter iter;
2686         BMFace *f;
2687         int selbigger = RNA_boolean_get(op->ptr, "select_bigger");
2688         int a, b;
2689
2690         /* find the set of regions with smallest number of total faces */
2691         a = loop_find_regions(em, selbigger);
2692         b = loop_find_regions(em, !selbigger);
2693         
2694         if ((a <= b) ^ selbigger) {
2695                 loop_find_regions(em, selbigger);
2696         }
2697         
2698         EDBM_flag_disable_all(em, BM_ELEM_SELECT);
2699         
2700         BM_ITER(f, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2701                 if (BM_elem_flag_test(f, BM_ELEM_TAG) && !BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
2702                         BM_face_select_set(em->bm, f, TRUE);
2703                 }
2704         }
2705         
2706         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2707         return OPERATOR_FINISHED;
2708 }
2709
2710 void MESH_OT_loop_to_region(wmOperatorType *ot)
2711 {
2712         /* identifiers */
2713         ot->name = "Select Loop Inner-Region";
2714         ot->idname = "MESH_OT_loop_to_region";
2715
2716         /* api callbacks */
2717         ot->exec = loop_to_region;
2718         ot->poll = ED_operator_editmesh;
2719
2720         /* flags */
2721         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2722         
2723         RNA_def_boolean(ot->srna, "select_bigger", 0, "Select Bigger", "Select bigger regions instead of smaller ones");
2724 }