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