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