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