rename RNA_property_is_set() --> RNA_struct_property_is_set() in preperation to add...
[blender-staging.git] / source / blender / editors / mesh / editmesh_mods.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_mods.c
29  *  \ingroup edmesh
30  */
31
32
33 /*
34
35 editmesh_mods.c, UI level access, no geometry changes 
36
37 */
38
39 #include <stdlib.h>
40 #include <string.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_material_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_modifier_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_editVert.h"
53 #include "BLI_rand.h"
54 #include "BLI_utildefines.h"
55
56 #include "BKE_context.h"
57 #include "BKE_displist.h"
58 #include "BKE_depsgraph.h"
59 #include "BKE_mesh.h"
60 #include "BKE_material.h"
61 #include "BKE_paint.h"
62 #include "BKE_report.h"
63 #include "BKE_texture.h"
64
65 #include "IMB_imbuf_types.h"
66 #include "IMB_imbuf.h"
67
68 #include "RE_render_ext.h"  /* externtex */
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73
74 #include "RNA_access.h"
75 #include "RNA_define.h"
76
77 #include "ED_mesh.h"
78 #include "ED_screen.h"
79 #include "ED_view3d.h"
80 #include "ED_uvedit.h"
81
82 #include "BIF_gl.h"
83
84 #include "mesh_intern.h"
85
86 #include "BLO_sys_types.h" // for intptr_t support
87
88 /* XXX */
89 static void waitcursor(int UNUSED(val)) {}
90 static int pupmenu(const char *UNUSED(arg)) {return 0;}
91
92 /* ****************************** MIRROR **************** */
93
94 void EM_cache_x_mirror_vert(struct Object *ob, struct EditMesh *em)
95 {
96         EditVert *eve, *eve_mirror;
97         int index= 0;
98
99         for(eve= em->verts.first; eve; eve= eve->next) {
100                 eve->tmp.v= NULL;
101         }
102
103         for(eve= em->verts.first; eve; eve= eve->next, index++) {
104                 if(eve->tmp.v==NULL) {
105                         eve_mirror = editmesh_get_x_mirror_vert(ob, em, eve, eve->co, index);
106                         if(eve_mirror) {
107                                 eve->tmp.v= eve_mirror;
108                                 eve_mirror->tmp.v = eve;
109                         }
110                 }
111         }
112 }
113
114 static void EM_select_mirrored(Object *obedit, EditMesh *em, int extend)
115 {
116
117         EditVert *eve;
118
119         EM_cache_x_mirror_vert(obedit, em);
120
121         for(eve= em->verts.first; eve; eve= eve->next) {
122                 if(eve->f & SELECT && eve->tmp.v && (eve->tmp.v != eve->tmp.v->tmp.v)) {
123                         eve->tmp.v->f |= SELECT;
124
125                         if(extend==FALSE)
126                                 eve->f &= ~SELECT;
127
128                         /* remove the interference */
129                         eve->tmp.v->tmp.v= NULL;
130                         eve->tmp.v= NULL;
131                 }
132         }
133 }
134
135 void EM_automerge(Scene *scene, Object *obedit, int update)
136 {
137         Mesh *me= obedit ? obedit->data : NULL; /* can be NULL */
138         /* int len; */ /* UNUSED */
139
140         if ((scene->toolsettings->automerge) &&
141                 (obedit && obedit->type==OB_MESH && (obedit->mode & OB_MODE_EDIT))
142           ) {
143                 EditMesh *em= me->edit_mesh;
144                 int totvert= em->totvert, totedge= em->totedge, totface= em->totface;
145
146                 /* len = */ /* UNUSED */ removedoublesflag(em, 1, 1, scene->toolsettings->doublimit);
147                 if (totvert != em->totvert || totedge != em->totedge || totface != em->totface) {
148                         if (update) {
149                                 DAG_id_tag_update(&me->id, 0);
150                         }
151                 }
152         }
153 }
154
155 /* ****************************** SELECTION ROUTINES **************** */
156
157 unsigned int em_solidoffs=0, em_wireoffs=0, em_vertoffs=0;      /* set in drawobject.c ... for colorindices */
158
159 /* facilities for border select and circle select */
160 static char *selbuf= NULL;
161
162 /* opengl doesn't support concave... */
163 static void draw_triangulated(int mcords[][2], short tot)
164 {
165         ListBase lb={NULL, NULL};
166         DispList *dl;
167         float *fp;
168         int a;
169         
170         /* make displist */
171         dl= MEM_callocN(sizeof(DispList), "poly disp");
172         dl->type= DL_POLY;
173         dl->parts= 1;
174         dl->nr= tot;
175         dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
176         BLI_addtail(&lb, dl);
177         
178         for(a=0; a<tot; a++, fp+=3) {
179                 fp[0]= (float)mcords[a][0];
180                 fp[1]= (float)mcords[a][1];
181         }
182         
183         /* do the fill */
184         filldisplist(&lb, &lb, 0);
185
186         /* do the draw */
187         dl= lb.first;   /* filldisplist adds in head of list */
188         if(dl->type==DL_INDEX3) {
189                 int *index;
190                 
191                 a= dl->parts;
192                 fp= dl->verts;
193                 index= dl->index;
194                 glBegin(GL_TRIANGLES);
195                 while(a--) {
196                         glVertex3fv(fp+3*index[0]);
197                         glVertex3fv(fp+3*index[1]);
198                         glVertex3fv(fp+3*index[2]);
199                         index+= 3;
200                 }
201                 glEnd();
202         }
203         
204         freedisplist(&lb);
205 }
206
207
208 /* reads rect, and builds selection array for quick lookup */
209 /* returns if all is OK */
210 int EM_init_backbuf_border(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
211 {
212         struct ImBuf *buf;
213         unsigned int *dr;
214         int a;
215         
216         if(vc->obedit==NULL || vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
217         
218         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
219         if(buf==NULL) return 0;
220         if(em_vertoffs==0) return 0;
221
222         dr = buf->rect;
223         
224         /* build selection lookup */
225         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
226         
227         a= (xmax-xmin+1)*(ymax-ymin+1);
228         while(a--) {
229                 if(*dr>0 && *dr<=em_vertoffs) 
230                         selbuf[*dr]= 1;
231                 dr++;
232         }
233         IMB_freeImBuf(buf);
234         return 1;
235 }
236
237 int EM_check_backbuf(unsigned int index)
238 {
239         if(selbuf==NULL) return 1;
240         if(index>0 && index<=em_vertoffs)
241                 return selbuf[index];
242         return 0;
243 }
244
245 void EM_free_backbuf(void)
246 {
247         if(selbuf) MEM_freeN(selbuf);
248         selbuf= NULL;
249 }
250
251 /* mcords is a polygon mask
252    - grab backbuffer,
253    - draw with black in backbuffer, 
254    - grab again and compare
255    returns 'OK' 
256 */
257 int EM_mask_init_backbuf_border(ViewContext *vc, int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
258 {
259         unsigned int *dr, *drm;
260         struct ImBuf *buf, *bufmask;
261         int a;
262         GLboolean is_cull;
263         
264         /* method in use for face selecting too */
265         if(vc->obedit==NULL) {
266                 if(paint_facesel_test(vc->obact));
267                 else if(paint_vertsel_test(vc->obact));
268                 else return 0;
269         }
270         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
271
272         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
273         if(buf==NULL) return 0;
274         if(em_vertoffs==0) return 0;
275
276         dr = buf->rect;
277
278         /* draw the mask */
279         glDisable(GL_DEPTH_TEST);
280         
281         glColor3ub(0, 0, 0);
282
283         /* some opengl drivers have problems with draw direction */
284         glGetBooleanv(GL_CULL_FACE, &is_cull);
285         if(is_cull) glDisable(GL_CULL_FACE);
286         
287         /* yah, opengl doesn't do concave... tsk! */
288         ED_region_pixelspace(vc->ar);
289         draw_triangulated(mcords, tot);
290         
291         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
292         for(a=0; a<tot; a++) glVertex2iv(mcords[a]);
293         glEnd();
294         
295         glFinish();     /* to be sure readpixels sees mask */
296         
297         /* grab mask */
298         bufmask= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
299         drm = bufmask->rect;
300         if(bufmask==NULL) return 0; /* only when mem alloc fails, go crash somewhere else! */
301         
302         /* build selection lookup */
303         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
304         
305         a= (xmax-xmin+1)*(ymax-ymin+1);
306         while(a--) {
307                 if(*dr>0 && *dr<=em_vertoffs && *drm==0) selbuf[*dr]= 1;
308                 dr++; drm++;
309         }
310         IMB_freeImBuf(buf);
311         IMB_freeImBuf(bufmask);
312         
313         if(is_cull) glEnable(GL_CULL_FACE);
314
315         return 1;
316         
317 }
318
319 /* circle shaped sample area */
320 int EM_init_backbuf_circle(ViewContext *vc, short xs, short ys, short rads)
321 {
322         struct ImBuf *buf;
323         unsigned int *dr;
324         short xmin, ymin, xmax, ymax, xc, yc;
325         int radsq;
326         
327         /* method in use for face selecting too */
328         if(vc->obedit==NULL) {
329                 if(paint_facesel_test(vc->obact));
330                 else if (paint_vertsel_test(vc->obact));
331                 else return 0;
332         }
333         else if(vc->v3d->drawtype<OB_SOLID || (vc->v3d->flag & V3D_ZBUF_SELECT)==0) return 0;
334         
335         xmin= xs-rads; xmax= xs+rads;
336         ymin= ys-rads; ymax= ys+rads;
337         buf= view3d_read_backbuf(vc, xmin, ymin, xmax, ymax);
338         if(em_vertoffs==0) return 0;
339         if(buf==NULL) return 0;
340
341         dr = buf->rect;
342         
343         /* build selection lookup */
344         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
345         radsq= rads*rads;
346         for(yc= -rads; yc<=rads; yc++) {
347                 for(xc= -rads; xc<=rads; xc++, dr++) {
348                         if(xc*xc + yc*yc < radsq) {
349                                 if(*dr>0 && *dr<=em_vertoffs) selbuf[*dr]= 1;
350                         }
351                 }
352         }
353
354         IMB_freeImBuf(buf);
355         return 1;
356         
357 }
358
359 static void findnearestvert__doClosest(void *userData, EditVert *eve, int x, int y, int index)
360 {
361         struct { int mval[2]; short pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } *data = userData;
362
363         if (data->pass==0) {
364                 if (index<=data->lastIndex)
365                         return;
366         } else {
367                 if (index>data->lastIndex)
368                         return;
369         }
370
371         if (data->dist>3) {
372                 int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
373                 if ((eve->f&1) == data->select) {
374                         if (data->strict == 1)
375                                 return;
376                         else
377                                 temp += 5;
378                 }
379
380                 if (temp<data->dist) {
381                         data->dist = temp;
382                         data->closest = eve;
383                         data->closestIndex = index;
384                 }
385         }
386 }
387
388
389
390
391 static unsigned int findnearestvert__backbufIndextest(void *handle, unsigned int index)
392 {
393         EditMesh *em= (EditMesh *)handle;
394         EditVert *eve = BLI_findlink(&em->verts, index-1);
395
396         if(eve && (eve->f & SELECT)) return 0;
397         return 1; 
398 }
399 /**
400  * findnearestvert
401  * 
402  * dist (in/out): minimal distance to the nearest and at the end, actual distance
403  * sel: selection bias
404  *              if SELECT, selected vertice are given a 5 pixel bias to make them farter than unselect verts
405  *              if 0, unselected vertice are given the bias
406  * strict: if 1, the vertice corresponding to the sel parameter are ignored and not just biased 
407  */
408 EditVert *findnearestvert(ViewContext *vc, int *dist, short sel, short strict)
409 {
410         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)){
411                 int distance;
412                 unsigned int index;
413                 EditVert *eve;
414                 
415                 if(strict) index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, strict, vc->em, findnearestvert__backbufIndextest); 
416                 else index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_wireoffs, 0xFFFFFF, &distance, 0, NULL, NULL); 
417                 
418                 eve = BLI_findlink(&vc->em->verts, index-1);
419                 
420                 if(eve && distance < *dist) {
421                         *dist = distance;
422                         return eve;
423                 } else {
424                         return NULL;
425                 }
426                         
427         }
428         else {
429                 struct { int mval[2]; short pass, select, strict; int dist, lastIndex, closestIndex; EditVert *closest; } data;
430                 static int lastSelectedIndex=0;
431                 static EditVert *lastSelected=NULL;
432
433                 if (lastSelected && BLI_findlink(&vc->em->verts, lastSelectedIndex)!=lastSelected) {
434                         lastSelectedIndex = 0;
435                         lastSelected = NULL;
436                 }
437
438                 data.lastIndex = lastSelectedIndex;
439                 data.mval[0] = vc->mval[0];
440                 data.mval[1] = vc->mval[1];
441                 data.select = sel;
442                 data.dist = *dist;
443                 data.strict = strict;
444                 data.closest = NULL;
445                 data.closestIndex = 0;
446
447                 data.pass = 0;
448
449                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
450
451                 mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
452
453                 if (data.dist>3) {
454                         data.pass = 1;
455                         mesh_foreachScreenVert(vc, findnearestvert__doClosest, &data, V3D_CLIP_TEST_RV3D_CLIPPING);
456                 }
457
458                 *dist = data.dist;
459                 lastSelected = data.closest;
460                 lastSelectedIndex = data.closestIndex;
461
462                 return data.closest;
463         }
464 }
465
466 /* returns labda for closest distance v1 to line-piece v2-v3 */
467 static float labda_PdistVL2Dfl( float *v1, float *v2, float *v3) 
468 {
469         float rc[2], len;
470         
471         rc[0]= v3[0]-v2[0];
472         rc[1]= v3[1]-v2[1];
473         len= rc[0]*rc[0]+ rc[1]*rc[1];
474         if(len==0.0f)
475                 return 0.0f;
476         
477         return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
478 }
479
480 /* note; uses v3d, so needs active 3d window */
481 static void findnearestedge__doClosest(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int UNUSED(index))
482 {
483         struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } *data = userData;
484         float v1[2], v2[2];
485         int distance;
486
487         ED_view3d_local_clipping(data->vc.rv3d, data->vc.obedit->obmat); /* for local clipping lookups */
488
489         v1[0] = x0;
490         v1[1] = y0;
491         v2[0] = x1;
492         v2[1] = y1;
493
494         distance= dist_to_line_segment_v2(data->mval, v1, v2);
495
496
497         if(eed->f & SELECT) distance+=5;
498         if(distance < data->dist) {
499                 if(data->vc.rv3d->rflag & RV3D_CLIPPING) {
500                         float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
501                         float vec[3];
502
503                         vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
504                         vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
505                         vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
506
507                         if(ED_view3d_test_clipping(data->vc.rv3d, vec, 1)==0) {
508                                 data->dist = distance;
509                                 data->closest = eed;
510                         }
511                 }
512                 else {
513                         data->dist = distance;
514                         data->closest = eed;
515                 }
516         }
517 }
518 EditEdge *findnearestedge(ViewContext *vc, int *dist)
519 {
520
521         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
522                 int distance;
523                 unsigned int index = view3d_sample_backbuf_rect(vc, vc->mval, 50, em_solidoffs, em_wireoffs, &distance,0, NULL, NULL);
524                 EditEdge *eed = BLI_findlink(&vc->em->edges, index-1);
525
526                 if (eed && distance<*dist) {
527                         *dist = distance;
528                         return eed;
529                 } else {
530                         return NULL;
531                 }
532         }
533         else {
534                 struct { ViewContext vc; float mval[2]; int dist; EditEdge *closest; } data;
535
536                 data.vc= *vc;
537                 data.mval[0] = vc->mval[0];
538                 data.mval[1] = vc->mval[1];
539                 data.dist = *dist;
540                 data.closest = NULL;
541
542                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
543                 mesh_foreachScreenEdge(vc, findnearestedge__doClosest, &data, V3D_CLIP_TEST_REGION);
544
545                 *dist = data.dist;
546                 return data.closest;
547         }
548 }
549
550 static void findnearestface__getDistance(void *userData, EditFace *efa, int x, int y, int UNUSED(index))
551 {
552         struct { int mval[2]; int dist; EditFace *toFace; } *data = userData;
553
554         if (efa==data->toFace) {
555                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
556
557                 if (temp<data->dist)
558                         data->dist = temp;
559         }
560 }
561 static void findnearestface__doClosest(void *userData, EditFace *efa, int x, int y, int index)
562 {
563         struct { int mval[2]; short pass; int dist, lastIndex, closestIndex; EditFace *closest; } *data = userData;
564
565         if (data->pass==0) {
566                 if (index<=data->lastIndex)
567                         return;
568         } else {
569                 if (index>data->lastIndex)
570                         return;
571         }
572
573         if (data->dist>3) {
574                 int temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
575
576                 if (temp<data->dist) {
577                         data->dist = temp;
578                         data->closest = efa;
579                         data->closestIndex = index;
580                 }
581         }
582 }
583 static EditFace *findnearestface(ViewContext *vc, int *dist)
584 {
585
586         if(vc->v3d->drawtype>OB_WIRE && (vc->v3d->flag & V3D_ZBUF_SELECT)) {
587                 unsigned int index = view3d_sample_backbuf(vc, vc->mval[0], vc->mval[1]);
588                 EditFace *efa = BLI_findlink(&vc->em->faces, index-1);
589
590                 if (efa) {
591                         struct { int mval[2]; int dist; EditFace *toFace; } data;
592
593                         data.mval[0] = vc->mval[0];
594                         data.mval[1] = vc->mval[1];
595                         data.dist = 0x7FFF;             /* largest short */
596                         data.toFace = efa;
597
598                         ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
599                         mesh_foreachScreenFace(vc, findnearestface__getDistance, &data);
600
601                         if(vc->em->selectmode == SCE_SELECT_FACE || data.dist<*dist) {  /* only faces, no dist check */
602                                 *dist= data.dist;
603                                 return efa;
604                         }
605                 }
606                 
607                 return NULL;
608         }
609         else {
610                 struct { int mval[2]; short pass; int dist, lastIndex, closestIndex; EditFace *closest; } data;
611                 static int lastSelectedIndex=0;
612                 static EditFace *lastSelected=NULL;
613
614                 if (lastSelected && BLI_findlink(&vc->em->faces, lastSelectedIndex)!=lastSelected) {
615                         lastSelectedIndex = 0;
616                         lastSelected = NULL;
617                 }
618
619                 data.lastIndex = lastSelectedIndex;
620                 data.mval[0] = vc->mval[0];
621                 data.mval[1] = vc->mval[1];
622                 data.dist = *dist;
623                 data.closest = NULL;
624                 data.closestIndex = 0;
625
626                 data.pass = 0;
627
628                 ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
629                 mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
630
631                 if (data.dist>3) {
632                         data.pass = 1;
633                         mesh_foreachScreenFace(vc, findnearestface__doClosest, &data);
634                 }
635
636                 *dist = data.dist;
637                 lastSelected = data.closest;
638                 lastSelectedIndex = data.closestIndex;
639
640                 return data.closest;
641         }
642 }
643
644 /* best distance based on screen coords. 
645    use em->selectmode to define how to use 
646    selected vertices and edges get disadvantage
647    return 1 if found one
648 */
649 static int unified_findnearest(ViewContext *vc, EditVert **eve, EditEdge **eed, EditFace **efa) 
650 {
651         EditMesh *em= vc->em;
652         int dist= 75;
653         
654         *eve= NULL;
655         *eed= NULL;
656         *efa= NULL;
657         
658         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
659         view3d_validate_backbuf(vc);
660         
661         if(em->selectmode & SCE_SELECT_VERTEX)
662                 *eve= findnearestvert(vc, &dist, SELECT, 0);
663         if(em->selectmode & SCE_SELECT_FACE)
664                 *efa= findnearestface(vc, &dist);
665
666         dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
667         if(em->selectmode & SCE_SELECT_EDGE)
668                 *eed= findnearestedge(vc, &dist);
669
670         /* return only one of 3 pointers, for frontbuffer redraws */
671         if(*eed) {
672                 *efa= NULL; *eve= NULL;
673         }
674         else if(*efa) {
675                 *eve= NULL;
676         }
677         
678         return (*eve || *eed || *efa);
679 }
680
681
682 /* ****************  SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
683
684 /* selects new faces/edges/verts based on the existing selection */
685
686 /* VERT GROUP */
687
688 #define SIMVERT_NORMAL  0
689 #define SIMVERT_FACE    1
690 #define SIMVERT_VGROUP  2
691 #define SIMVERT_TOT             3
692
693 /* EDGE GROUP */
694
695 #define SIMEDGE_LENGTH          101
696 #define SIMEDGE_DIR                     102
697 #define SIMEDGE_FACE            103
698 #define SIMEDGE_FACE_ANGLE      104
699 #define SIMEDGE_CREASE          105
700 #define SIMEDGE_SEAM            106
701 #define SIMEDGE_SHARP           107
702 #define SIMEDGE_TOT                     108
703
704 /* FACE GROUP */
705
706 #define SIMFACE_MATERIAL        201
707 #define SIMFACE_IMAGE           202
708 #define SIMFACE_AREA            203
709 #define SIMFACE_PERIMETER       204
710 #define SIMFACE_NORMAL          205
711 #define SIMFACE_COPLANAR        206
712 #define SIMFACE_TOT                     207
713
714 static EnumPropertyItem prop_similar_types[] = {
715         {SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
716         {SIMVERT_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
717         {SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
718         {SIMEDGE_LENGTH, "LENGTH", 0, "Length", ""},
719         {SIMEDGE_DIR, "DIR", 0, "Direction", ""},
720         {SIMEDGE_FACE, "FACE", 0, "Amount of Vertices in Face", ""},
721         {SIMEDGE_FACE_ANGLE, "FACE_ANGLE", 0, "Face Angles", ""},
722         {SIMEDGE_CREASE, "CREASE", 0, "Crease", ""},
723         {SIMEDGE_SEAM, "SEAM", 0, "Seam", ""},
724         {SIMEDGE_SHARP, "SHARP", 0, "Sharpness", ""},
725         {SIMFACE_MATERIAL, "MATERIAL", 0, "Material", ""},
726         {SIMFACE_IMAGE, "IMAGE", 0, "Image", ""},
727         {SIMFACE_AREA, "AREA", 0, "Area", ""},
728         {SIMFACE_PERIMETER, "PERIMETER", 0, "Perimeter", ""},
729         {SIMFACE_NORMAL, "NORMAL", 0, "Normal", ""},
730         {SIMFACE_COPLANAR, "COPLANAR", 0, "Co-planar", ""},
731         {0, NULL, 0, NULL, NULL}
732 };
733
734
735 /* this as a way to compare the ares, perim  of 2 faces thay will scale to different sizes
736 *0.5 so smaller faces arnt ALWAYS selected with a thresh of 1.0 */
737 #define SCALE_CMP(a,b) ((a+a*thresh >= b) && (a-(a*thresh*0.5f) <= b))
738
739 static int similar_face_select__internal(EditMesh *em, int mode, float thresh)
740 {
741         EditFace *efa, *base_efa=NULL;
742         unsigned int selcount=0; /*count how many new faces we select*/
743         
744         /*deselcount, count how many deselected faces are left, so we can bail out early
745         also means that if there are no deselected faces, we can avoid a lot of looping */
746         unsigned int deselcount=0; 
747         short ok=0;
748         
749         for(efa= em->faces.first; efa; efa= efa->next) {
750                 if (!efa->h) {
751                         if (efa->f & SELECT) {
752                                 efa->f1=1;
753                                 ok=1;
754                         } else {
755                                 efa->f1=0;
756                                 deselcount++; /* a deselected face we may select later */
757                         }
758                 }
759         }
760         
761         if (!ok || !deselcount) /* no data selected OR no more data to select */
762                 return 0;
763         
764         if (mode==SIMFACE_AREA) {
765                 for(efa= em->faces.first; efa; efa= efa->next) {
766                         efa->tmp.fp= EM_face_area(efa);
767                 }
768         } else if (mode==SIMFACE_PERIMETER) {
769                 for(efa= em->faces.first; efa; efa= efa->next) {
770                         efa->tmp.fp= EM_face_perimeter(efa);
771                 }
772         }
773         
774         for(base_efa= em->faces.first; base_efa; base_efa= base_efa->next) {
775                 if (base_efa->f1) { /* This was one of the faces originaly selected */
776                         if (mode==SIMFACE_MATERIAL) { /* same material */
777                                 for(efa= em->faces.first; efa; efa= efa->next) {
778                                         if (
779                                                 !(efa->f & SELECT) &&
780                                                 !efa->h &&
781                                                 base_efa->mat_nr == efa->mat_nr
782                                         ) {
783                                                 EM_select_face(efa, 1);
784                                                 selcount++;
785                                                 deselcount--;
786                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
787                                                         return selcount;
788                                         }
789                                 }
790                         } else if (mode==SIMFACE_IMAGE) { /* same image */
791                                 MTFace *tf, *base_tf;
792
793                                 base_tf = (MTFace*)CustomData_em_get(&em->fdata, base_efa->data,
794                                                                                                          CD_MTFACE);
795
796                                 if(!base_tf)
797                                         return selcount;
798
799                                 for(efa= em->faces.first; efa; efa= efa->next) {
800                                         if (!(efa->f & SELECT) && !efa->h) {
801                                                 tf = (MTFace*)CustomData_em_get(&em->fdata, efa->data,
802                                                                                                                 CD_MTFACE);
803
804                                                 if(base_tf->tpage == tf->tpage) {
805                                                         EM_select_face(efa, 1);
806                                                         selcount++;
807                                                         deselcount--;
808                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
809                                                                 return selcount;
810                                                 }
811                                         }
812                                 }
813                         } else if (mode==SIMFACE_AREA || mode==SIMFACE_PERIMETER) { /* same area OR same perimeter, both use the same temp var */
814                                 for(efa= em->faces.first; efa; efa= efa->next) {
815                                         if (
816                                                 (!(efa->f & SELECT) && !efa->h) &&
817                                                 SCALE_CMP(base_efa->tmp.fp, efa->tmp.fp)
818                                         ) {
819                                                 EM_select_face(efa, 1);
820                                                 selcount++;
821                                                 deselcount--;
822                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
823                                                         return selcount;
824                                         }
825                                 }
826                         } else if (mode==SIMFACE_NORMAL) {
827                                 float angle;
828                                 for(efa= em->faces.first; efa; efa= efa->next) {
829                                         if (!(efa->f & SELECT) && !efa->h) {
830                                                 angle= RAD2DEGF(angle_v3v3(base_efa->n, efa->n));
831                                                 if (angle/180.0f<=thresh) {
832                                                         EM_select_face(efa, 1);
833                                                         selcount++;
834                                                         deselcount--;
835                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
836                                                                 return selcount;
837                                                 }
838                                         }
839                                 }
840                         } else if (mode==SIMFACE_COPLANAR) { /* same planer */
841                                 float angle, base_dot, dot;
842                                 base_dot= dot_v3v3(base_efa->cent, base_efa->n);
843                                 for(efa= em->faces.first; efa; efa= efa->next) {
844                                         if (!(efa->f & SELECT) && !efa->h) {
845                                                 angle= RAD2DEGF(angle_v3v3(base_efa->n, efa->n));
846                                                 if (angle/180.0f<=thresh) {
847                                                         dot=dot_v3v3(efa->cent, base_efa->n);
848                                                         if (fabsf(base_dot-dot) <= thresh) {
849                                                                 EM_select_face(efa, 1);
850                                                                 selcount++;
851                                                                 deselcount--;
852                                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
853                                                                         return selcount;
854                                                         }
855                                                 }
856                                         }
857                                 }
858                         }
859                 }
860         } /* end base_efa loop */
861         return selcount;
862 }
863
864 static int similar_face_select_exec(bContext *C, wmOperator *op)
865 {
866         Object *obedit= CTX_data_edit_object(C);
867         Mesh *me= obedit->data;
868         EditMesh *em= BKE_mesh_get_editmesh(me); 
869
870         int selcount = similar_face_select__internal(em, RNA_enum_get(op->ptr, "type"), RNA_float_get(op->ptr, "threshold"));
871         
872         if (selcount) {
873                 /* here was an edge-mode only select flush case, has to be generalized */
874                 EM_selectmode_flush(em);
875                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
876         }
877         
878         BKE_mesh_end_editmesh(me, em);
879         return OPERATOR_FINISHED;
880 }       
881
882 /* ***************************************************** */
883
884 static int similar_edge_select__internal(EditMesh *em, int mode, float thresh)
885 {
886         EditEdge *eed, *base_eed=NULL;
887         unsigned int selcount=0; /* count how many new edges we select*/
888         
889         /*count how many visible selected edges there are,
890         so we can return when there are none left */
891         unsigned int deselcount=0;
892         
893         short ok=0;
894         
895         for(eed= em->edges.first; eed; eed= eed->next) {
896                 if (!eed->h) {
897                         if (eed->f & SELECT) {
898                                 eed->f1=1;
899                                 ok=1;
900                         } else {
901                                 eed->f1=0;
902                                 deselcount++;
903                         }
904                         /* set all eed->tmp.l to 0 we use it later.
905                         for counting face users*/
906                         eed->tmp.l=0;
907                         eed->f2=0; /* only for mode SIMEDGE_FACE_ANGLE, edge animations */
908                 }
909         }
910         
911         if (!ok || !deselcount) /* no data selected OR no more data to select*/
912                 return 0;
913         
914         if (mode==SIMEDGE_LENGTH) { /*store length*/
915                 for(eed= em->edges.first; eed; eed= eed->next) {
916                         if (!eed->h) /* dont calc data for hidden edges*/
917                                 eed->tmp.fp= len_v3v3(eed->v1->co, eed->v2->co);
918                 }
919         } else if (mode==SIMEDGE_FACE) { /*store face users*/
920                 EditFace *efa;
921                 /* cound how many faces each edge uses use tmp->l */
922                 for(efa= em->faces.first; efa; efa= efa->next) {
923                         efa->e1->tmp.l++;
924                         efa->e2->tmp.l++;
925                         efa->e3->tmp.l++;
926                         if (efa->e4) efa->e4->tmp.l++;
927                 }
928         } else if (mode==SIMEDGE_FACE_ANGLE) { /*store edge angles */
929                 EditFace *efa;
930                 int j;
931                 /* cound how many faces each edge uses use tmp.l */
932                 for(efa= em->faces.first; efa; efa= efa->next) {
933                         /* here we use the edges temp data to assign a face
934                         if a face has already been assigned (eed->f2==1)
935                         we calculate the angle between the current face and
936                         the edges previously found face.
937                         store the angle in eed->tmp.fp (loosing the face eed->tmp.f)
938                         but tagging eed->f2==2, so we know not to look at it again.
939                         This only works for edges that connect to 2 faces. but its good enough
940                         */
941                         
942                         /* se we can loop through face edges*/
943                         j=0;
944                         eed= efa->e1;
945                         while (j<4) {
946                                 if (j==1) eed= efa->e2;
947                                 else if (j==2) eed= efa->e3;
948                                 else if (j==3) {
949                                         eed= efa->e4;
950                                         if (!eed)
951                                                 break;
952                                 } /* done looping */
953                                 
954                                 if (!eed->h) { /* dont calc data for hidden edges*/
955                                         if (eed->f2==2)
956                                                 break;
957                                         else if (eed->f2==0) /* first access, assign the face */
958                                                 eed->tmp.f= efa;
959                                         else if (eed->f2==1) /* second, we assign the angle*/
960                                                 eed->tmp.fp= RAD2DEGF(angle_v3v3(eed->tmp.f->n, efa->n))/180;
961                                         eed->f2++; /* f2==0 no face assigned. f2==1 one face found. f2==2 angle calculated.*/
962                                 }
963                                 j++;
964                         }
965                 }
966         }
967         
968         for(base_eed= em->edges.first; base_eed; base_eed= base_eed->next) {
969                 if (base_eed->f1) {
970                         if (mode==SIMEDGE_LENGTH) { /* same length */
971                                 for(eed= em->edges.first; eed; eed= eed->next) {
972                                         if (
973                                                 !(eed->f & SELECT) &&
974                                                 !eed->h &&
975                                                 SCALE_CMP(base_eed->tmp.fp, eed->tmp.fp)
976                                         ) {
977                                                 EM_select_edge(eed, 1);
978                                                 selcount++;
979                                                 deselcount--;
980                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
981                                                         return selcount;
982                                         }
983                                 }
984                         } else if (mode==SIMEDGE_DIR) { /* same direction */
985                                 float base_dir[3], dir[3], angle;
986                                 sub_v3_v3v3(base_dir, base_eed->v1->co, base_eed->v2->co);
987                                 for(eed= em->edges.first; eed; eed= eed->next) {
988                                         if (!(eed->f & SELECT) && !eed->h) {
989                                                 sub_v3_v3v3(dir, eed->v1->co, eed->v2->co);
990                                                 angle= RAD2DEGF(angle_v3v3(base_dir, dir));
991                                                 
992                                                 if (angle>90.0f) /* use the smallest angle between the edges */
993                                                         angle= fabsf(angle-180.0f);
994                                                 
995                                                 if (angle / 90.0f<=thresh) {
996                                                         EM_select_edge(eed, 1);
997                                                         selcount++;
998                                                         deselcount--;
999                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
1000                                                                 return selcount;
1001                                                 }
1002                                         }
1003                                 }
1004                         } else if (mode==SIMEDGE_FACE) { /* face users */                               
1005                                 for(eed= em->edges.first; eed; eed= eed->next) {
1006                                         if (
1007                                                 !(eed->f & SELECT) &&
1008                                                 !eed->h &&
1009                                                 base_eed->tmp.l==eed->tmp.l
1010                                         ) {
1011                                                 EM_select_edge(eed, 1);
1012                                                 selcount++;
1013                                                 deselcount--;
1014                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1015                                                         return selcount;
1016                                         }
1017                                 }
1018                         } else if (mode==SIMEDGE_FACE_ANGLE && base_eed->f2==2) { /* edge angles, f2==2 means the edge has an angle. */                         
1019                                 for(eed= em->edges.first; eed; eed= eed->next) {
1020                                         if (
1021                                                 !(eed->f & SELECT) &&
1022                                                 !eed->h &&
1023                                                 eed->f2==2 &&
1024                                                 (fabsf(base_eed->tmp.fp-eed->tmp.fp)<=thresh)
1025                                         ) {
1026                                                 EM_select_edge(eed, 1);
1027                                                 selcount++;
1028                                                 deselcount--;
1029                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1030                                                         return selcount;
1031                                         }
1032                                 }
1033                         } else if (mode==SIMEDGE_CREASE) { /* edge crease */
1034                                 for(eed= em->edges.first; eed; eed= eed->next) {
1035                                         if (
1036                                                 !(eed->f & SELECT) &&
1037                                                 !eed->h &&
1038                                                 (fabsf(base_eed->crease-eed->crease) <= thresh)
1039                                         ) {
1040                                                 EM_select_edge(eed, 1);
1041                                                 selcount++;
1042                                                 deselcount--;
1043                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1044                                                         return selcount;
1045                                         }
1046                                 }
1047                         } else if (mode==SIMEDGE_SEAM) { /* edge seam */
1048                                 for(eed= em->edges.first; eed; eed= eed->next) {
1049                                         if (
1050                                                 !(eed->f & SELECT) &&
1051                                                 !eed->h &&
1052                                                 (eed->seam == base_eed->seam)
1053                                         ) {
1054                                                 EM_select_edge(eed, 1);
1055                                                 selcount++;
1056                                                 deselcount--;
1057                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1058                                                         return selcount;
1059                                         }
1060                                 }
1061                         } else if (mode==SIMEDGE_SHARP) { /* edge sharp */
1062                                 for(eed= em->edges.first; eed; eed= eed->next) {
1063                                         if (
1064                                                 !(eed->f & SELECT) &&
1065                                                 !eed->h &&
1066                                                 (eed->sharp == base_eed->sharp)
1067                                         ) {
1068                                                 EM_select_edge(eed, 1);
1069                                                 selcount++;
1070                                                 deselcount--;
1071                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1072                                                         return selcount;
1073                                         }
1074                                 }
1075                         }
1076                 }
1077         }       
1078         return selcount;
1079 }
1080 /* wrap the above function but do selection flushing edge to face */
1081 static int similar_edge_select_exec(bContext *C, wmOperator *op)
1082 {
1083         Object *obedit= CTX_data_edit_object(C);
1084         Mesh *me= obedit->data;
1085         EditMesh *em= BKE_mesh_get_editmesh(me); 
1086
1087         int selcount = similar_edge_select__internal(em, RNA_enum_get(op->ptr, "type"), RNA_float_get(op->ptr, "threshold"));
1088         
1089         if (selcount) {
1090                 /* here was an edge-mode only select flush case, has to be generalized */
1091                 EM_selectmode_flush(em);
1092                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
1093         }
1094
1095         BKE_mesh_end_editmesh(me, em);
1096         return OPERATOR_FINISHED;
1097 }
1098
1099 /* ********************************* */
1100
1101 static int similar_vert_select_exec(bContext *C, wmOperator *op)
1102 {
1103         Object *obedit= CTX_data_edit_object(C);
1104         Mesh *me= obedit->data;
1105         EditMesh *em= BKE_mesh_get_editmesh(me); 
1106         EditVert *eve, *base_eve=NULL;
1107         unsigned int selcount=0; /* count how many new edges we select*/
1108         
1109         /*count how many visible selected edges there are,
1110         so we can return when there are none left */
1111         unsigned int deselcount=0;
1112         int mode= RNA_enum_get(op->ptr, "type");
1113         float thresh = RNA_float_get(op->ptr, "threshold");
1114         
1115         short ok=0;
1116         
1117         for(eve= em->verts.first; eve; eve= eve->next) {
1118                 if (!eve->h) {
1119                         if (eve->f & SELECT) {
1120                                 eve->f1=1;
1121                                 ok=1;
1122                         } else {
1123                                 eve->f1=0;
1124                                 deselcount++;
1125                         }
1126                         /* set all eve->tmp.l to 0 we use them later.*/
1127                         eve->tmp.l=0;
1128                 }
1129                 
1130         }
1131         
1132         if (!ok || !deselcount) { /* no data selected OR no more data to select*/
1133                 BKE_mesh_end_editmesh(me, em);
1134                 return OPERATOR_CANCELLED;
1135         }
1136         
1137         if(mode == SIMVERT_FACE) {
1138                 /* store face users */
1139                 EditFace *efa;
1140                 
1141                 /* count how many faces each edge uses use tmp->l */
1142                 for(efa= em->faces.first; efa; efa= efa->next) {
1143                         efa->v1->tmp.l++;
1144                         efa->v2->tmp.l++;
1145                         efa->v3->tmp.l++;
1146                         if (efa->v4) efa->v4->tmp.l++;
1147                 }
1148         }
1149         
1150         
1151         for(base_eve= em->verts.first; base_eve; base_eve= base_eve->next) {
1152                 if (base_eve->f1) {
1153                                 
1154                         if(mode == SIMVERT_NORMAL) {
1155                                 float angle;
1156                                 for(eve= em->verts.first; eve; eve= eve->next) {
1157                                         if (!(eve->f & SELECT) && !eve->h) {
1158                                                 angle= RAD2DEGF(angle_v3v3(base_eve->no, eve->no));
1159                                                 if (angle/180.0f<=thresh) {
1160                                                         eve->f |= SELECT;
1161                                                         selcount++;
1162                                                         deselcount--;
1163                                                         if (!deselcount) {/*have we selected all posible faces?, if so return*/
1164                                                                 BKE_mesh_end_editmesh(me, em);
1165                                                                 return OPERATOR_FINISHED;
1166                                                         }
1167                                                 }
1168                                         }
1169                                 }
1170                         }
1171                         else if(mode == SIMVERT_FACE) {
1172                                 for(eve= em->verts.first; eve; eve= eve->next) {
1173                                         if (
1174                                                 !(eve->f & SELECT) &&
1175                                                 !eve->h &&
1176                                                 base_eve->tmp.l==eve->tmp.l
1177                                         ) {
1178                                                 eve->f |= SELECT;
1179                                                 selcount++;
1180                                                 deselcount--;
1181                                                 if (!deselcount) {/*have we selected all posible faces?, if so return*/
1182                                                         BKE_mesh_end_editmesh(me, em);
1183                                                         return OPERATOR_FINISHED;
1184                                                 }
1185                                         }
1186                                 }
1187                         } 
1188                         else if(mode == SIMVERT_VGROUP) {
1189                                 MDeformVert *dvert, *base_dvert;
1190                                 short i, j; /* weight index */
1191
1192                                 base_dvert= CustomData_em_get(&em->vdata, base_eve->data,
1193                                         CD_MDEFORMVERT);
1194
1195                                 if (!base_dvert || base_dvert->totweight == 0) {
1196                                         BKE_mesh_end_editmesh(me, em);
1197                                         return OPERATOR_FINISHED;
1198                                 }
1199                                 
1200                                 for(eve= em->verts.first; eve; eve= eve->next) {
1201                                         dvert= CustomData_em_get(&em->vdata, eve->data,
1202                                                 CD_MDEFORMVERT);
1203
1204                                         if (dvert && !(eve->f & SELECT) && !eve->h && dvert->totweight) {
1205                                                 /* do the extra check for selection in the following if, so were not
1206                                                 checking verts that may be already selected */
1207                                                 for (i=0; base_dvert->totweight >i && !(eve->f & SELECT); i++) { 
1208                                                         for (j=0; dvert->totweight >j; j++) {
1209                                                                 if (base_dvert->dw[i].def_nr==dvert->dw[j].def_nr) {
1210                                                                         eve->f |= SELECT;
1211                                                                         selcount++;
1212                                                                         deselcount--;
1213                                                                         if (!deselcount) { /*have we selected all posible faces?, if so return*/
1214                                                                                 BKE_mesh_end_editmesh(me, em);
1215                                                                                 return OPERATOR_FINISHED;
1216                                                                         }
1217                                                                         break;
1218                                                                 }
1219                                                         }
1220                                                 }
1221                                         }
1222                                 }
1223                         }
1224                 }
1225         } /* end basevert loop */
1226
1227         if(selcount) {
1228                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
1229         }
1230
1231         BKE_mesh_end_editmesh(me, em);
1232         return OPERATOR_FINISHED;
1233 }
1234
1235 static int select_similar_exec(bContext *C, wmOperator *op)
1236 {
1237         int type= RNA_enum_get(op->ptr, "type");
1238
1239         if(type < 100)
1240                 return similar_vert_select_exec(C, op);
1241         else if(type < 200)
1242                 return similar_edge_select_exec(C, op);
1243         else
1244                 return similar_face_select_exec(C, op);
1245 }
1246
1247 static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1248 {
1249         Object *obedit= CTX_data_edit_object(C);
1250         EnumPropertyItem *item= NULL;
1251         int a, totitem= 0;
1252
1253         if (C == NULL) {
1254                 return prop_similar_types;
1255         }
1256                 
1257         if(obedit && obedit->type == OB_MESH) {
1258                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data); 
1259
1260                 if(em->selectmode & SCE_SELECT_VERTEX) {
1261                         for(a=SIMVERT_NORMAL; a<=SIMVERT_TOT; a++)
1262                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1263                 }
1264                 else if(em->selectmode & SCE_SELECT_EDGE) {
1265                         for(a=SIMEDGE_LENGTH; a<=SIMEDGE_TOT; a++)
1266                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1267                 }
1268                 else if(em->selectmode & SCE_SELECT_FACE) {
1269                         for(a=SIMFACE_MATERIAL; a<=SIMFACE_TOT; a++)
1270                                 RNA_enum_items_add_value(&item, &totitem, prop_similar_types, a);
1271                 }
1272         }
1273
1274         RNA_enum_item_end(&item, &totitem);
1275         *free= 1;
1276
1277         return item;
1278 }
1279
1280 void MESH_OT_select_similar(wmOperatorType *ot)
1281 {
1282         PropertyRNA *prop;
1283
1284         /* identifiers */
1285         ot->name= "Select Similar";
1286         ot->description= "Select similar vertices, edges or faces by property types";
1287         ot->idname= "MESH_OT_select_similar";
1288         
1289         /* api callbacks */
1290         ot->invoke= WM_menu_invoke;
1291         ot->exec= select_similar_exec;
1292         ot->poll= ED_operator_editmesh;
1293         
1294         /* flags */
1295         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1296         
1297         /* properties */
1298         prop= RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
1299         RNA_def_enum_funcs(prop, select_similar_type_itemf);
1300         ot->prop= prop;
1301         RNA_def_float(ot->srna, "threshold", 0.01f, 0.0f, FLT_MAX, "Threshold", "", 0.0f, 100.f);
1302 }
1303
1304 /* ******************************************* */
1305
1306
1307 int mesh_layers_menu_charlen(CustomData *data, int type)
1308 {
1309         int i, len = 0;
1310         /* see if there is a duplicate */
1311         for(i=0; i<data->totlayer; i++) {
1312                 if((&data->layers[i])->type == type) {
1313                         /* we could count the chars here but we'll just assumeme each
1314                          * is 32 chars with some room for the menu text - 40 should be fine */
1315                         len+=40; 
1316                 }
1317         }
1318         return len;
1319 }
1320
1321 /* this function adds menu text into an existing string.
1322  * this string's size should be allocated with mesh_layers_menu_charlen */
1323 void mesh_layers_menu_concat(CustomData *data, int type, char *str) 
1324 {
1325         int i, count = 0;
1326         char *str_pt = str;
1327         CustomDataLayer *layer;
1328         
1329         /* see if there is a duplicate */
1330         for(i=0; i<data->totlayer; i++) {
1331                 layer = &data->layers[i];
1332                 if(layer->type == type) {
1333                         str_pt += sprintf(str_pt, "%s%%x%d|", layer->name, count);
1334                         count++;
1335                 }
1336         }
1337 }
1338
1339 int mesh_layers_menu(CustomData *data, int type)
1340 {
1341         int ret;
1342         char *str_pt, *str;
1343         
1344         str_pt = str = MEM_mallocN(mesh_layers_menu_charlen(data, type) + 18, "layer menu");
1345         str[0] = '\0';
1346         
1347         str_pt += sprintf(str_pt, "Layers%%t|");
1348         
1349         mesh_layers_menu_concat(data, type, str_pt);
1350         
1351         ret = pupmenu(str);
1352         MEM_freeN(str);
1353         return ret;
1354 }
1355
1356 static void EM_mesh_copy_edge(EditMesh *em, short type) 
1357 {
1358         EditSelection *ese;
1359         short change=0;
1360         
1361         EditEdge *eed, *eed_act;
1362         float vec[3], vec_mid[3], eed_len, eed_len_act;
1363         
1364         if (!em) return;
1365         
1366         ese = em->selected.last;
1367         if (!ese) return;
1368         
1369         eed_act = (EditEdge*)ese->data;
1370         
1371         switch (type) {
1372         case 1: /* copy crease */
1373                 for(eed=em->edges.first; eed; eed=eed->next) {
1374                         if (eed->f & SELECT && eed != eed_act && eed->crease != eed_act->crease) {
1375                                 eed->crease = eed_act->crease;
1376                                 change = 1;
1377                         }
1378                 }
1379                 break;
1380         case 2: /* copy bevel weight */
1381                 for(eed=em->edges.first; eed; eed=eed->next) {
1382                         if (eed->f & SELECT && eed != eed_act && eed->bweight != eed_act->bweight) {
1383                                 eed->bweight = eed_act->bweight;
1384                                 change = 1;
1385                         }
1386                 }
1387                 break;
1388
1389         case 3: /* copy length */
1390                 eed_len_act = len_v3v3(eed_act->v1->co, eed_act->v2->co);
1391                 for(eed=em->edges.first; eed; eed=eed->next) {
1392                         if (eed->f & SELECT && eed != eed_act) {
1393
1394                                 eed_len = len_v3v3(eed->v1->co, eed->v2->co);
1395
1396                                 if (eed_len == eed_len_act) continue;
1397                                 /* if this edge is zero length we cont do anything with it*/
1398                                 if (eed_len == 0.0f) continue;
1399                                 if (eed_len_act == 0.0f) {
1400                                         add_v3_v3v3(vec_mid, eed->v1->co, eed->v2->co);
1401                                         mul_v3_fl(vec_mid, 0.5);
1402                                         VECCOPY(eed->v1->co, vec_mid);
1403                                         VECCOPY(eed->v2->co, vec_mid);
1404                                 } else {
1405                                         /* copy the edge length */
1406                                         add_v3_v3v3(vec_mid, eed->v1->co, eed->v2->co);
1407                                         mul_v3_fl(vec_mid, 0.5);
1408
1409                                         /* SCALE 1 */
1410                                         sub_v3_v3v3(vec, eed->v1->co, vec_mid);
1411                                         mul_v3_fl(vec, eed_len_act/eed_len);
1412                                         add_v3_v3v3(eed->v1->co, vec, vec_mid);
1413
1414                                         /* SCALE 2 */
1415                                         sub_v3_v3v3(vec, eed->v2->co, vec_mid);
1416                                         mul_v3_fl(vec, eed_len_act/eed_len);
1417                                         add_v3_v3v3(eed->v2->co, vec, vec_mid);
1418                                 }
1419                                 change = 1;
1420                         }
1421                 }
1422
1423                 if (change)
1424                         recalc_editnormals(em);
1425
1426                 break;
1427         }
1428         
1429         if (change) {
1430 //              DAG_id_tag_update(obedit->data, 0);
1431                 
1432         }
1433 }
1434
1435 static void EM_mesh_copy_face(EditMesh *em, wmOperator *op, short type)
1436 {
1437         short change=0;
1438         
1439         EditFace *efa, *efa_act;
1440         MTFace *tf, *tf_act = NULL;
1441         MCol *mcol, *mcol_act = NULL;
1442         if (!em) return;
1443         efa_act = EM_get_actFace(em, 0);
1444         
1445         if (!efa_act) return;
1446         
1447         tf_act =        CustomData_em_get(&em->fdata, efa_act->data, CD_MTFACE);
1448         mcol_act =      CustomData_em_get(&em->fdata, efa_act->data, CD_MCOL);
1449         
1450         switch (type) {
1451         case 1: /* copy material */
1452                 for(efa=em->faces.first; efa; efa=efa->next) {
1453                         if (efa->f & SELECT && efa->mat_nr != efa_act->mat_nr) {
1454                                 efa->mat_nr = efa_act->mat_nr;
1455                                 change = 1;
1456                         }
1457                 }
1458                 break;
1459         case 2: /* copy image */
1460                 if (!tf_act) {
1461                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1462                         return;
1463                 }
1464                 for(efa=em->faces.first; efa; efa=efa->next) {
1465                         if (efa->f & SELECT && efa != efa_act) {
1466                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1467                                 if (tf_act->tpage) {
1468                                         tf->tpage = tf_act->tpage;
1469                                 } else {
1470                                         tf->tpage = NULL;
1471                                 }
1472                                 tf->tile= tf_act->tile;
1473                                 change = 1;
1474                         }
1475                 }
1476                 break;
1477
1478         case 3: /* copy UV's */
1479                 if (!tf_act) {
1480                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1481                         return;
1482                 }
1483                 for(efa=em->faces.first; efa; efa=efa->next) {
1484                         if (efa->f & SELECT && efa != efa_act) {
1485                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1486                                 memcpy(tf->uv, tf_act->uv, sizeof(tf->uv));
1487                                 change = 1;
1488                         }
1489                 }
1490                 break;
1491         case 4: /* mode's */
1492                 if (!tf_act) {
1493                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1494                         return;
1495                 }
1496                 for(efa=em->faces.first; efa; efa=efa->next) {
1497                         if (efa->f & SELECT && efa != efa_act) {
1498                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1499                                 tf->mode= tf_act->mode;
1500                                 change = 1;
1501                         }
1502                 }
1503                 break;
1504         case 5: /* copy transp's */
1505                 if (!tf_act) {
1506                         BKE_report(op->reports, RPT_WARNING, "Mesh has no uv/image layers");
1507                         return;
1508                 }
1509                 for(efa=em->faces.first; efa; efa=efa->next) {
1510                         if (efa->f & SELECT && efa != efa_act) {
1511                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1512                                 tf->transp= tf_act->transp;
1513                                 change = 1;
1514                         }
1515                 }
1516                 break;
1517
1518         case 6: /* copy vcols's */
1519                 if (!mcol_act) {
1520                         BKE_report(op->reports, RPT_WARNING, "Mesh has no color layers");
1521                         return;
1522                 } else {
1523                         /* guess the 4th color if needs be */
1524                         float val =- 1;
1525
1526                         if (!efa_act->v4) {
1527                                 /* guess the othe vale, we may need to use it
1528                                  * 
1529                                  * Modifying the 4th value of the mcol is ok here since its not seen
1530                                  * on a triangle
1531                                  * */
1532                                 val = ((float)(mcol_act->r +  (mcol_act+1)->r + (mcol_act+2)->r)) / 3; CLAMP(val, 0, 255);
1533                                 (mcol_act+3)->r = (char)val;
1534
1535                                 val = ((float)(mcol_act->g +  (mcol_act+1)->g + (mcol_act+2)->g)) / 3; CLAMP(val, 0, 255);
1536                                 (mcol_act+3)->g = (char)val;
1537
1538                                 val = ((float)(mcol_act->b +  (mcol_act+1)->b + (mcol_act+2)->b)) / 3; CLAMP(val, 0, 255);
1539                                 (mcol_act+3)->b = (char)val;
1540                         } 
1541
1542
1543                         for(efa=em->faces.first; efa; efa=efa->next) {
1544                                 if (efa->f & SELECT && efa != efa_act) {
1545                                         /* TODO - make copy from tri to quad guess the 4th vert */
1546                                         mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1547                                         memcpy(mcol, mcol_act, sizeof(MCol)*4); 
1548                                         change = 1;
1549                                 }
1550                         }
1551                 }
1552                 break;
1553         }
1554         
1555         if (change) {
1556 //              DAG_id_tag_update(obedit->data, 0);
1557                 
1558         }
1559 }
1560
1561
1562 void EM_mesh_copy_face_layer(EditMesh *em, wmOperator *op, short type) 
1563 {
1564         short change=0;
1565         
1566         EditFace *efa;
1567         MTFace *tf, *tf_from;
1568         MCol *mcol, *mcol_from;
1569         
1570         if (!em) return;
1571         
1572         switch(type) {
1573         case 7:
1574         case 8:
1575         case 9:
1576                 if (CustomData_number_of_layers(&em->fdata, CD_MTFACE)<2) {
1577                         BKE_report(op->reports, RPT_WARNING, "mesh does not have multiple uv/image layers");
1578                         return;
1579                 } else {
1580                         int layer_orig_idx, layer_idx;
1581
1582                         layer_idx = mesh_layers_menu(&em->fdata, CD_MTFACE);
1583                         if (layer_idx<0) return;
1584
1585                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1586                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MTFACE);
1587                         if (layer_idx==layer_orig_idx)
1588                                 return;
1589
1590                         /* get the tfaces */
1591                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, (int)layer_idx);
1592                         /* store the tfaces in our temp */
1593                         for(efa=em->faces.first; efa; efa=efa->next) {
1594                                 if (efa->f & SELECT) {
1595                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1596                                 }       
1597                         }
1598                         CustomData_set_layer_active(&em->fdata, CD_MTFACE, layer_orig_idx);
1599                 }
1600                 break;
1601
1602         case 10: /* select vcol layers - make sure this stays in sync with above code */
1603                 if (CustomData_number_of_layers(&em->fdata, CD_MCOL)<2) {
1604                         BKE_report(op->reports, RPT_WARNING, "mesh does not have multiple color layers");
1605                         return;
1606                 } else {
1607                         int layer_orig_idx, layer_idx;
1608
1609                         layer_idx = mesh_layers_menu(&em->fdata, CD_MCOL);
1610                         if (layer_idx<0) return;
1611
1612                         /* warning, have not updated mesh pointers however this is not needed since we swicth back */
1613                         layer_orig_idx = CustomData_get_active_layer(&em->fdata, CD_MCOL);
1614                         if (layer_idx==layer_orig_idx)
1615                                 return;
1616
1617                         /* get the tfaces */
1618                         CustomData_set_layer_active(&em->fdata, CD_MCOL, (int)layer_idx);
1619                         /* store the tfaces in our temp */
1620                         for(efa=em->faces.first; efa; efa=efa->next) {
1621                                 if (efa->f & SELECT) {
1622                                         efa->tmp.p = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1623                                 }       
1624                         }
1625                         CustomData_set_layer_active(&em->fdata, CD_MCOL, layer_orig_idx);
1626
1627                 }
1628                 break;
1629         }
1630
1631         /* layer copy only - sanity checks done above */
1632         switch (type) {
1633         case 7: /* copy UV's only */
1634                 for(efa=em->faces.first; efa; efa=efa->next) {
1635                         if (efa->f & SELECT) {
1636                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1637                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1638                                 memcpy(tf->uv, tf_from->uv, sizeof(tf->uv));
1639                                 change = 1;
1640                         }
1641                 }
1642                 break;
1643         case 8: /* copy image settings only */
1644                 for(efa=em->faces.first; efa; efa=efa->next) {
1645                         if (efa->f & SELECT) {
1646                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1647                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1648                                 if (tf_from->tpage) {
1649                                         tf->tpage = tf_from->tpage;
1650                                 } else {
1651                                         tf->tpage = NULL;
1652                                 }
1653                                 tf->tile= tf_from->tile;
1654                                 change = 1;
1655                         }
1656                 }
1657                 break;
1658         case 9: /* copy all tface info */
1659                 for(efa=em->faces.first; efa; efa=efa->next) {
1660                         if (efa->f & SELECT) {
1661                                 tf_from = (MTFace *)efa->tmp.p; /* not active but easier to use this way */
1662                                 tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
1663                                 memcpy(tf->uv, ((MTFace *)efa->tmp.p)->uv, sizeof(tf->uv));
1664                                 tf->tpage = tf_from->tpage;
1665                                 tf->mode = tf_from->mode;
1666                                 tf->transp = tf_from->transp;
1667                                 change = 1;
1668                         }
1669                 }
1670                 break;
1671         case 10:
1672                 for(efa=em->faces.first; efa; efa=efa->next) {
1673                         if (efa->f & SELECT) {
1674                                 mcol_from = (MCol *)efa->tmp.p; 
1675                                 mcol = CustomData_em_get(&em->fdata, efa->data, CD_MCOL);
1676                                 memcpy(mcol, mcol_from, sizeof(MCol)*4);        
1677                                 change = 1;
1678                         }
1679                 }
1680                 break;
1681         }
1682
1683         if (change) {
1684 //              DAG_id_tag_update(obedit->data, 0);
1685                 
1686         }
1687 }
1688
1689
1690 /* ctrl+c in mesh editmode */
1691 static void UNUSED_FUNCTION(mesh_copy_menu)(EditMesh *em, wmOperator *op)
1692 {
1693         EditSelection *ese;
1694         int ret;
1695         if (!em) return;
1696         
1697         ese = em->selected.last;
1698         
1699         /* Faces can have a NULL ese, so dont return on a NULL ese here */
1700         
1701         if(ese && ese->type == EDITVERT) {
1702                 /* EditVert *ev, *ev_act = (EditVert*)ese->data;
1703                 ret= pupmenu(""); */
1704         } else if(ese && ese->type == EDITEDGE) {
1705                 ret= pupmenu("Copy Active Edge to Selected%t|Crease%x1|Bevel Weight%x2|Length%x3");
1706                 if (ret<1) return;
1707                 
1708                 EM_mesh_copy_edge(em, ret);
1709                 
1710         } else if(ese==NULL || ese->type == EDITFACE) {
1711                 ret= pupmenu(
1712                         "Copy Face Selected%t|"
1713                         "Active Material%x1|Active Image%x2|Active UV Coords%x3|"
1714                         "Active Mode%x4|Active Transp%x5|Active Vertex Colors%x6|%l|"
1715
1716                         "TexFace UVs from layer%x7|"
1717                         "TexFace Images from layer%x8|"
1718                         "TexFace All from layer%x9|"
1719                         "Vertex Colors from layer%x10");
1720                 if (ret<1) return;
1721                 
1722                 if (ret<=6) {
1723                         EM_mesh_copy_face(em, op, ret);
1724                 } else {
1725                         EM_mesh_copy_face_layer(em, op, ret);
1726                 }
1727         }
1728 }
1729
1730 /* ****************  LOOP SELECTS *************** */
1731
1732 /* selects quads in loop direction of indicated edge */
1733 /* only flush over edges with valence <= 2 */
1734 void faceloop_select(EditMesh *em, EditEdge *startedge, int select)
1735 {
1736         EditEdge *eed;
1737         EditFace *efa;
1738         int looking= 1;
1739         
1740         /* in eed->f1 we put the valence (amount of faces in edge) */
1741         /* in eed->f2 we put tagged flag as correct loop */
1742         /* in efa->f1 we put tagged flag as correct to select */
1743
1744         for(eed= em->edges.first; eed; eed= eed->next) {
1745                 eed->f1= 0;
1746                 eed->f2= 0;
1747         }
1748         for(efa= em->faces.first; efa; efa= efa->next) {
1749                 efa->f1= 0;
1750                 if(efa->h==0) {
1751                         efa->e1->f1++;
1752                         efa->e2->f1++;
1753                         efa->e3->f1++;
1754                         if(efa->e4) efa->e4->f1++;
1755                 }
1756         }
1757         
1758         /* tag startedge OK*/
1759         startedge->f2= 1;
1760         
1761         while(looking) {
1762                 looking= 0;
1763                 
1764                 for(efa= em->faces.first; efa; efa= efa->next) {
1765                         if(efa->h==0 && efa->e4 && efa->f1==0) {        /* not done quad */
1766                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1767
1768                                         /* if edge tagged, select opposing edge and mark face ok */
1769                                         if(efa->e1->f2) {
1770                                                 efa->e3->f2= 1;
1771                                                 efa->f1= 1;
1772                                                 looking= 1;
1773                                         }
1774                                         else if(efa->e2->f2) {
1775                                                 efa->e4->f2= 1;
1776                                                 efa->f1= 1;
1777                                                 looking= 1;
1778                                         }
1779                                         if(efa->e3->f2) {
1780                                                 efa->e1->f2= 1;
1781                                                 efa->f1= 1;
1782                                                 looking= 1;
1783                                         }
1784                                         if(efa->e4->f2) {
1785                                                 efa->e2->f2= 1;
1786                                                 efa->f1= 1;
1787                                                 looking= 1;
1788                                         }
1789                                 }
1790                         }
1791                 }
1792         }
1793         
1794         /* (de)select the faces */
1795         if(select!=2) {
1796                 for(efa= em->faces.first; efa; efa= efa->next) {
1797                         if(efa->f1) EM_select_face(efa, select);
1798                 }
1799         }
1800 }
1801
1802
1803 /* helper for edgeloop_select, checks for eed->f2 tag in faces */
1804 static int edge_not_in_tagged_face(EditMesh *em, EditEdge *eed)
1805 {
1806         EditFace *efa;
1807         
1808         for(efa= em->faces.first; efa; efa= efa->next) {
1809                 if(efa->h==0) {
1810                         if(efa->e1==eed || efa->e2==eed || efa->e3==eed || efa->e4==eed) {      /* edge is in face */
1811                                 if(efa->e1->f2 || efa->e2->f2 || efa->e3->f2 || (efa->e4 && efa->e4->f2)) {     /* face is tagged */
1812                                         return 0;
1813                                 }
1814                         }
1815                 }
1816         }
1817         return 1;
1818 }
1819
1820 static void ensure_ed_vert_sel(EditMesh *em)
1821 {
1822         EditEdge *eed;
1823
1824         /* EM_selectmode_flush() doesnt take into account that deselected edges
1825          * may be still connected to selected edges [#26885] */
1826         for(eed= em->edges.first; eed; eed= eed->next) {
1827                 if(eed->f & SELECT) {
1828                         eed->v1->f |= SELECT;
1829                         eed->v2->f |= SELECT;
1830                 }
1831         }
1832 }
1833
1834 /* selects or deselects edges that:
1835 - if edges has 2 faces:
1836         - has vertices with valence of 4
1837         - not shares face with previous edge
1838 - if edge has 1 face:
1839         - has vertices with valence 4
1840         - not shares face with previous edge
1841         - but also only 1 face
1842 - if edge no face:
1843         - has vertices with valence 2
1844 */
1845 static void edgeloop_select(EditMesh *em, EditEdge *starteed, int select)
1846 {
1847         EditVert *eve;
1848         EditEdge *eed;
1849         EditFace *efa;
1850         int looking= 1;
1851         
1852         /* in f1 we put the valence (amount of edges in a vertex, or faces in edge) */
1853         /* in eed->f2 and efa->f1 we put tagged flag as correct loop */
1854         for(eve= em->verts.first; eve; eve= eve->next) {
1855                 eve->f1= 0;
1856                 eve->f2= 0;
1857         }
1858         for(eed= em->edges.first; eed; eed= eed->next) {
1859                 eed->f1= 0;
1860                 eed->f2= 0;
1861                 if((eed->h & 1)==0) {   /* fgon edges add to valence too */
1862                         eed->v1->f1++; eed->v2->f1++;
1863                 }
1864         }
1865         for(efa= em->faces.first; efa; efa= efa->next) {
1866                 efa->f1= 0;
1867                 if(efa->h==0) {
1868                         efa->e1->f1++;
1869                         efa->e2->f1++;
1870                         efa->e3->f1++;
1871                         if(efa->e4) efa->e4->f1++;
1872                 }
1873         }
1874         
1875         /* looped edges & vertices get tagged f2 */
1876         starteed->f2= 1;
1877         if(starteed->v1->f1<5) starteed->v1->f2= 1;
1878         if(starteed->v2->f1<5) starteed->v2->f2= 1;
1879         /* sorry, first edge isnt even ok */
1880         if(starteed->v1->f2==0 && starteed->v2->f2==0) looking= 0;
1881         
1882         while(looking) {
1883                 looking= 0;
1884                 
1885                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
1886                 for(eed= em->edges.first; eed; eed= eed->next) {
1887                         if(eed->h==0 && eed->f2==0) { /* edge not hidden, not tagged */
1888                                 if( (eed->v1->f1<5 && eed->v1->f2) || (eed->v2->f1<5 && eed->v2->f2)) { /* valence of vertex OK, and is tagged */
1889                                         /* new edge is not allowed to be in face with tagged edge */
1890                                         if(edge_not_in_tagged_face(em, eed)) {
1891                                                 if(eed->f1==starteed->f1) {     /* same amount of faces */
1892                                                         looking= 1;
1893                                                         eed->f2= 1;
1894                                                         if(eed->v2->f1<5) eed->v2->f2= 1;
1895                                                         if(eed->v1->f1<5) eed->v1->f2= 1;
1896                                                 }
1897                                         }
1898                                 }
1899                         }
1900                 }
1901         }
1902         /* and we do the select */
1903         for(eed= em->edges.first; eed; eed= eed->next) {
1904                 if(eed->f2) EM_select_edge(eed, select);
1905         }
1906
1907         if(select == FALSE && !(em->selectmode & SCE_SELECT_VERTEX)) { /* only when not in vert sel [#26931] */
1908                 ensure_ed_vert_sel(em);
1909         }
1910 }
1911
1912 /* 
1913    Almostly exactly the same code as faceloop select
1914 */
1915 static void edgering_select(EditMesh *em, EditEdge *startedge, int select)
1916 {
1917         EditEdge *eed;
1918         EditFace *efa;
1919         int looking= 1;
1920         
1921         /* in eed->f1 we put the valence (amount of faces in edge) */
1922         /* in eed->f2 we put tagged flag as correct loop */
1923         /* in efa->f1 we put tagged flag as correct to select */
1924
1925         for(eed= em->edges.first; eed; eed= eed->next) {
1926                 eed->f1= 0;
1927                 eed->f2= 0;
1928         }
1929         for(efa= em->faces.first; efa; efa= efa->next) {
1930                 efa->f1= 0;
1931                 if(efa->h==0) {
1932                         efa->e1->f1++;
1933                         efa->e2->f1++;
1934                         efa->e3->f1++;
1935                         if(efa->e4) efa->e4->f1++;
1936                 }
1937         }
1938         
1939         /* tag startedge OK */
1940         startedge->f2= 1;
1941         
1942         while(looking) {
1943                 looking= 0;
1944                 
1945                 for(efa= em->faces.first; efa; efa= efa->next) {
1946                         if(efa->e4 && efa->f1==0 && !efa->h) {  /* not done quad */
1947                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1948
1949                                         /* if edge tagged, select opposing edge and mark face ok */
1950                                         if(efa->e1->f2) {
1951                                                 efa->e3->f2= 1;
1952                                                 efa->f1= 1;
1953                                                 looking= 1;
1954                                         }
1955                                         else if(efa->e2->f2) {
1956                                                 efa->e4->f2= 1;
1957                                                 efa->f1= 1;
1958                                                 looking= 1;
1959                                         }
1960                                         if(efa->e3->f2) {
1961                                                 efa->e1->f2= 1;
1962                                                 efa->f1= 1;
1963                                                 looking= 1;
1964                                         }
1965                                         if(efa->e4->f2) {
1966                                                 efa->e2->f2= 1;
1967                                                 efa->f1= 1;
1968                                                 looking= 1;
1969                                         }
1970                                 }
1971                         }
1972                 }
1973         }
1974         
1975         /* (de)select the edges */
1976         for(eed= em->edges.first; eed; eed= eed->next) {
1977                         if(eed->f2) EM_select_edge(eed, select);
1978         }
1979
1980         if(select == FALSE && !(em->selectmode & SCE_SELECT_VERTEX)) { /* only when not in vert sel [#26931] */
1981                 ensure_ed_vert_sel(em);
1982         }
1983 }
1984
1985 static int loop_multiselect(bContext *C, wmOperator *op)
1986 {
1987         Object *obedit= CTX_data_edit_object(C);
1988         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
1989         EditEdge *eed;
1990         EditEdge **edarray;
1991         int edindex, edfirstcount;
1992         int looptype= RNA_boolean_get(op->ptr, "ring");
1993         
1994         /* sets em->totedgesel */
1995         EM_nedges_selected(em);
1996         
1997         edarray = MEM_mallocN(sizeof(EditEdge*)*em->totedgesel,"edge array");
1998         edindex = 0;
1999         edfirstcount = em->totedgesel;
2000         
2001         for(eed=em->edges.first; eed; eed=eed->next){
2002                 if(eed->f&SELECT){
2003                         edarray[edindex] = eed;
2004                         edindex += 1;
2005                 }
2006         }
2007         
2008         if(looptype){
2009                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
2010                         eed = edarray[edindex];
2011                         edgering_select(em, eed,SELECT);
2012                 }
2013                 EM_selectmode_flush(em);
2014         }
2015         else{
2016                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
2017                         eed = edarray[edindex];
2018                         edgeloop_select(em, eed,SELECT);
2019                 }
2020                 EM_selectmode_flush(em);
2021         }
2022         MEM_freeN(edarray);
2023 //      if (EM_texFaceCheck())
2024         
2025         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2026
2027         BKE_mesh_end_editmesh(obedit->data, em);
2028         return OPERATOR_FINISHED;       
2029 }
2030
2031 void MESH_OT_loop_multi_select(wmOperatorType *ot)
2032 {
2033         /* identifiers */
2034         ot->name= "Multi Select Loops";
2035         ot->description= "Select a loop of connected edges by connection type";
2036         ot->idname= "MESH_OT_loop_multi_select";
2037         
2038         /* api callbacks */
2039         ot->exec= loop_multiselect;
2040         ot->poll= ED_operator_editmesh;
2041         
2042         /* flags */
2043         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2044         
2045         /* properties */
2046         RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
2047 }
2048
2049                 
2050 /* ***************** MAIN MOUSE SELECTION ************** */
2051
2052
2053 /* ***************** loop select (non modal) ************** */
2054
2055 static void mouse_mesh_loop(bContext *C, const int mval[2], short extend, short ring)
2056 {
2057         ViewContext vc;
2058         EditMesh *em;
2059         EditEdge *eed;
2060         int select= 1;
2061         int dist= 50;
2062         
2063         em_setup_viewcontext(C, &vc);
2064         vc.mval[0]= mval[0];
2065         vc.mval[1]= mval[1];
2066         em= vc.em;
2067
2068         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
2069         view3d_validate_backbuf(&vc);
2070         
2071         eed= findnearestedge(&vc, &dist);
2072         if(eed) {
2073                 if(extend==0) EM_clear_flag_all(em, SELECT);
2074         
2075                 if((eed->f & SELECT)==0) select=1;
2076                 else if(extend) select=0;
2077
2078                 if(em->selectmode & SCE_SELECT_FACE) {
2079                         faceloop_select(em, eed, select);
2080                 }
2081                 else if(em->selectmode & SCE_SELECT_EDGE) {
2082                         if(ring)
2083                                 edgering_select(em, eed, select);
2084                         else
2085                                 edgeloop_select(em, eed, select);
2086                 }
2087                 else if(em->selectmode & SCE_SELECT_VERTEX) {
2088                         if(ring)
2089                                 edgering_select(em, eed, select);
2090                         else 
2091                                 edgeloop_select(em, eed, select);
2092                 }
2093
2094                 EM_selectmode_flush(em);
2095 //                      if (EM_texFaceCheck())
2096                 
2097                 /* sets as active, useful for other tools */
2098                 if(select) {
2099                         if(em->selectmode & SCE_SELECT_VERTEX)
2100                                 EM_store_selection(em, eed->v1, EDITVERT);
2101                         if(em->selectmode & SCE_SELECT_EDGE)
2102                                 EM_store_selection(em, eed, EDITEDGE);
2103                 }
2104
2105                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2106         }
2107 }
2108
2109 static int mesh_select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event)
2110 {
2111         
2112         view3d_operator_needs_opengl(C);
2113         
2114         mouse_mesh_loop(C, event->mval, RNA_boolean_get(op->ptr, "extend"),
2115                                         RNA_boolean_get(op->ptr, "ring"));
2116         
2117         /* cannot do tweaks for as long this keymap is after transform map */
2118         return OPERATOR_FINISHED;
2119 }
2120
2121 void MESH_OT_loop_select(wmOperatorType *ot)
2122 {
2123         /* identifiers */
2124         ot->name= "Loop Select";
2125         ot->description= "Select a loop of connected edges";
2126         ot->idname= "MESH_OT_loop_select";
2127         
2128         /* api callbacks */
2129         ot->invoke= mesh_select_loop_invoke;
2130         ot->poll= ED_operator_editmesh_region_view3d;
2131         
2132         /* flags */
2133         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2134         
2135         /* properties */
2136         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2137         RNA_def_boolean(ot->srna, "ring", 0, "Select Ring", "");
2138 }
2139
2140 /* ******************* mesh shortest path select, uses prev-selected edge ****************** */
2141
2142 /* since you want to create paths with multiple selects, it doesn't have extend option */
2143 static void mouse_mesh_shortest_path(bContext *C, const int mval[2])
2144 {
2145         ViewContext vc;
2146         EditMesh *em;
2147         EditEdge *eed, *eed_act= NULL;
2148         int dist= 50;
2149         
2150         em_setup_viewcontext(C, &vc);
2151         vc.mval[0]= mval[0];
2152         vc.mval[1]= mval[1];
2153         em= vc.em;
2154         
2155         /* no afterqueue (yet), so we check it now, otherwise the em_xxxofs indices are bad */
2156         view3d_validate_backbuf(&vc);
2157         
2158         eed= findnearestedge(&vc, &dist);
2159         if(eed) {
2160                 Mesh *me= vc.obedit->data;
2161                 int path = 0;
2162                 
2163                 if (em->selected.last) {
2164                         EditSelection *ese = em->selected.last;
2165                         
2166                         if(ese && ese->type == EDITEDGE) {
2167                                 eed_act = (EditEdge*)ese->data;
2168                                 if (eed_act != eed) {
2169                                         if (edgetag_shortest_path(vc.scene, em, eed_act, eed)) { /* <- this is where the magic happens */
2170                                                 EM_remove_selection(em, eed_act, EDITEDGE);
2171                                                 path = 1;
2172                                         }
2173                                 }
2174                         }
2175                 }
2176                 if (path==0) {
2177                         int act = (edgetag_context_check(vc.scene, eed)==0);
2178                         edgetag_context_set(vc.scene, eed, act); /* switch the edge option */
2179                 }
2180
2181                 /* even if this is selected it may not be in the selection list */
2182                 if(edgetag_context_check(vc.scene, eed)==0) {
2183                         EM_remove_selection(em, eed, EDITEDGE);
2184                 }
2185                 else {
2186                         /* other modes need to keep the last edge tagged */
2187                         if(eed_act) {
2188                                 if(vc.scene->toolsettings->edge_mode!=EDGE_MODE_SELECT) {
2189                                         /* for non-select modes, always de-select the previous active edge */
2190                                         EM_select_edge(eed_act, 0);
2191                                 }
2192                         }
2193
2194                         /* set the new edge active */
2195                         EM_select_edge(eed, 1);
2196                         EM_store_selection(em, eed, EDITEDGE);
2197                 }
2198
2199                 EM_selectmode_flush(em);
2200         
2201                 /* force drawmode for mesh */
2202                 switch (vc.scene->toolsettings->edge_mode) {
2203                         
2204                         case EDGE_MODE_TAG_SEAM:
2205                                 me->drawflag |= ME_DRAWSEAMS;
2206                                 break;
2207                         case EDGE_MODE_TAG_SHARP:
2208                                 me->drawflag |= ME_DRAWSHARP;
2209                                 break;
2210                         case EDGE_MODE_TAG_CREASE:      
2211                                 me->drawflag |= ME_DRAWCREASES;
2212                                 break;
2213                         case EDGE_MODE_TAG_BEVEL:
2214                                 me->drawflag |= ME_DRAWBWEIGHTS;
2215                                 break;
2216                 }
2217
2218                 /* live unwrap while tagging */
2219                 if(     (vc.scene->toolsettings->edge_mode_live_unwrap) &&
2220                         (vc.scene->toolsettings->edge_mode == EDGE_MODE_TAG_SEAM) &&
2221                         (CustomData_has_layer(&em->fdata, CD_MTFACE))
2222                 ) {
2223                         ED_unwrap_lscm(vc.scene, vc.obedit, FALSE); /* unwrap all not just sel */
2224                 }
2225
2226                 DAG_id_tag_update(vc.obedit->data, 0);
2227                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2228         }
2229 }
2230
2231
2232 static int mesh_shortest_path_select_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
2233 {
2234         
2235         view3d_operator_needs_opengl(C);
2236
2237         mouse_mesh_shortest_path(C, event->mval);
2238         
2239         return OPERATOR_FINISHED;
2240 }
2241
2242 static int mesh_shortest_path_select_poll(bContext *C)
2243 {
2244         if(ED_operator_editmesh_region_view3d(C)) {
2245                 Object *obedit= CTX_data_edit_object(C);
2246                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2247                 return (em->selectmode & SCE_SELECT_EDGE);
2248         }
2249         return 0;
2250 }
2251         
2252 void MESH_OT_select_shortest_path(wmOperatorType *ot)
2253 {
2254         /* identifiers */
2255         ot->name= "Shortest Path Select";
2256         ot->description= "Select shortest path between two selections";
2257         ot->idname= "MESH_OT_select_shortest_path";
2258         
2259         /* api callbacks */
2260         ot->invoke= mesh_shortest_path_select_invoke;
2261         ot->poll= mesh_shortest_path_select_poll;
2262         
2263         /* flags */
2264         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2265         
2266         /* properties */
2267         RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "");
2268 }
2269
2270
2271 /* ************************************************** */
2272
2273
2274 /* here actual select happens */
2275 /* gets called via generic mouse select operator */
2276 int mouse_mesh(bContext *C, const int mval[2], short extend)
2277 {
2278         ViewContext vc;
2279         EditVert *eve;
2280         EditEdge *eed;
2281         EditFace *efa;
2282         
2283         /* setup view context for argument to callbacks */
2284         em_setup_viewcontext(C, &vc);
2285         vc.mval[0]= mval[0];
2286         vc.mval[1]= mval[1];
2287         
2288         if(unified_findnearest(&vc, &eve, &eed, &efa)) {
2289                 
2290                 if(extend==0) EM_clear_flag_all(vc.em, SELECT);
2291                 
2292                 if(efa) {
2293                         /* set the last selected face */
2294                         EM_set_actFace(vc.em, efa);
2295                         
2296                         if( (efa->f & SELECT)==0 ) {
2297                                 EM_store_selection(vc.em, efa, EDITFACE);
2298                                 EM_select_face_fgon(vc.em, efa, 1);
2299                         }
2300                         else if(extend) {
2301                                 EM_remove_selection(vc.em, efa, EDITFACE);
2302                                 EM_select_face_fgon(vc.em, efa, 0);
2303                         }
2304                 }
2305                 else if(eed) {
2306                         if((eed->f & SELECT)==0) {
2307                                 EM_store_selection(vc.em, eed, EDITEDGE);
2308                                 EM_select_edge(eed, 1);
2309                         }
2310                         else if(extend) {
2311                                 EM_remove_selection(vc.em, eed, EDITEDGE);
2312                                 EM_select_edge(eed, 0);
2313                         }
2314                 }
2315                 else if(eve) {
2316                         if((eve->f & SELECT)==0) {
2317                                 eve->f |= SELECT;
2318                                 EM_store_selection(vc.em, eve, EDITVERT);
2319                         }
2320                         else if(extend){ 
2321                                 EM_remove_selection(vc.em, eve, EDITVERT);
2322                                 eve->f &= ~SELECT;
2323                         }
2324                 }
2325                 
2326                 EM_selectmode_flush(vc.em);
2327                   
2328 //              if (EM_texFaceCheck()) {
2329
2330                 if (efa && efa->mat_nr != vc.obedit->actcol-1) {
2331                         vc.obedit->actcol= efa->mat_nr+1;
2332                         vc.em->mat_nr= efa->mat_nr;
2333                         WM_event_add_notifier(C, NC_MATERIAL|ND_SHADING, NULL);
2334                 }
2335
2336                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, vc.obedit->data);
2337
2338                 return 1;
2339         }
2340         
2341         return 0;
2342 }
2343
2344 /* *********** select linked ************* */
2345
2346 /* for use with selectconnected_delimit_mesh only! */
2347 #define is_edge_delimit_ok(eed) ((eed->tmp.l == 1) && (eed->seam==0))
2348 #define is_face_tag(efa) is_edge_delimit_ok(efa->e1) || is_edge_delimit_ok(efa->e2) || is_edge_delimit_ok(efa->e3) || (efa->v4 && is_edge_delimit_ok(efa->e4))
2349
2350 #define face_tag(efa)\
2351 if(efa->v4)     efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= efa->e4->tmp.l= 1;\
2352 else            efa->tmp.l=             efa->e1->tmp.l= efa->e2->tmp.l= efa->e3->tmp.l= 1;
2353
2354 /* all - 1) use all faces for extending the selection  2) only use the mouse face
2355 * sel - 1) select  0) deselect 
2356 * */
2357
2358 /* legacy warning, this function combines too much :) */
2359 static int select_linked_limited_invoke(ViewContext *vc, short all, short sel)
2360 {
2361         EditMesh *em= vc->em;
2362         EditFace *efa;
2363         EditEdge *eed;
2364         EditVert *eve;
2365         short done=1, change=0;
2366         
2367         if(em->faces.first==0) return OPERATOR_CANCELLED;
2368         
2369         /* flag all edges+faces as off*/
2370         for(eed= em->edges.first; eed; eed= eed->next)
2371                 eed->tmp.l=0;
2372         
2373         for(efa= em->faces.first; efa; efa= efa->next) {
2374                 efa->tmp.l = 0;
2375         }
2376         
2377         if (all) {
2378                 // XXX verts?
2379                 for(eed= em->edges.first; eed; eed= eed->next) {
2380                         if(eed->f & SELECT)
2381                                 eed->tmp.l= 1;
2382                 }
2383                 for(efa= em->faces.first; efa; efa= efa->next) {
2384                         
2385                         if (efa->f & SELECT) {
2386                                 face_tag(efa);
2387                         } else {
2388                                 efa->tmp.l = 0;
2389                         }
2390                 }
2391         } 
2392         else {
2393                 if( unified_findnearest(vc, &eve, &eed, &efa) ) {
2394                         
2395                         if(efa) {
2396                                 efa->tmp.l = 1;
2397                                 face_tag(efa);
2398                         }
2399                         else if(eed)
2400                                 eed->tmp.l= 1;
2401                         else {
2402                                 for(eed= em->edges.first; eed; eed= eed->next)
2403                                         if(eed->v1==eve || eed->v2==eve)
2404                                                 break;
2405                                 eed->tmp.l= 1;
2406                         }
2407                 }
2408                 else
2409                         return OPERATOR_FINISHED;
2410         }
2411         
2412         while(done==1) {
2413                 done= 0;
2414                 /* simple algo - select all faces that have a selected edge
2415                 * this intern selects the edge, repeat until nothing is left to do */
2416                 for(efa= em->faces.first; efa; efa= efa->next) {
2417                         if ((efa->tmp.l == 0) && (!efa->h)) {
2418                                 if (is_face_tag(efa)) {
2419                                         face_tag(efa);
2420                                         done= 1;
2421                                 }
2422                         }
2423                 }
2424         }
2425         
2426         for(efa= em->faces.first; efa; efa= efa->next) {
2427                 if (efa->tmp.l) {
2428                         if (sel) {
2429                                 if (!(efa->f & SELECT)) {
2430                                         EM_select_face(efa, 1);
2431                                         change = 1;
2432                                 }
2433                         } else {
2434                                 if (efa->f & SELECT) {
2435                                         EM_select_face(efa, 0);
2436                                         change = 1;
2437                                 }
2438                         }
2439                 }
2440         }
2441         
2442         if (!change)
2443                 return OPERATOR_CANCELLED;
2444         
2445         if (!sel) /* make sure de-selecting faces didnt de-select the verts/edges connected to selected faces, this is common with boundaries */
2446                 for(efa= em->faces.first; efa; efa= efa->next)
2447                         if (efa->f & SELECT)
2448                                 EM_select_face(efa, 1);
2449         
2450         //      if (EM_texFaceCheck())
2451         
2452         return OPERATOR_FINISHED;
2453 }
2454
2455 #undef is_edge_delimit_ok
2456 #undef is_face_tag
2457 #undef face_tag
2458
2459 static void linked_limit_default(bContext *C, wmOperator *op)
2460 {
2461         if(!RNA_struct_property_is_set(op->ptr, "limit")) {
2462                 Object *obedit= CTX_data_edit_object(C);
2463                 EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2464                 if(em->selectmode == SCE_SELECT_FACE)
2465                         RNA_boolean_set(op->ptr, "limit", TRUE);
2466         }
2467 }
2468
2469 static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event)
2470 {
2471         Object *obedit= CTX_data_edit_object(C);
2472         ViewContext vc;
2473         EditVert *eve, *v1, *v2;
2474         EditEdge *eed;
2475         EditFace *efa;
2476         short done=1, toggle=0;
2477         int sel= !RNA_boolean_get(op->ptr, "deselect");
2478         int limit;
2479         
2480         linked_limit_default(C, op);
2481
2482         limit = RNA_boolean_get(op->ptr, "limit");
2483
2484         /* unified_finednearest needs ogl */
2485         view3d_operator_needs_opengl(C);
2486         
2487         /* setup view context for argument to callbacks */
2488         em_setup_viewcontext(C, &vc);
2489         
2490         if(vc.em->edges.first==0) return OPERATOR_CANCELLED;
2491         
2492         vc.mval[0]= event->mval[0];
2493         vc.mval[1]= event->mval[1];
2494         
2495         /* return warning! */
2496         if(limit) {
2497                 int retval= select_linked_limited_invoke(&vc, 0, sel);
2498                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2499                 return retval;
2500         }
2501         
2502         if( unified_findnearest(&vc, &eve, &eed, &efa)==0 ) {
2503                 WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2504         
2505                 return OPERATOR_CANCELLED;
2506         }
2507
2508         /* clear test flags */
2509         for(v1= vc.em->verts.first; v1; v1= v1->next) v1->f1= 0;
2510         
2511         /* start vertex/face/edge */
2512         if(eve) eve->f1= 1;
2513         else if(eed) eed->v1->f1= eed->v2->f1= 1;
2514         else efa->v1->f1= efa->v2->f1= efa->v3->f1= 1;
2515         
2516         /* set flag f1 if affected */
2517         while(done==1) {
2518                 done= 0;
2519                 toggle++;
2520                 
2521                 if(toggle & 1) eed= vc.em->edges.first;
2522                 else eed= vc.em->edges.last;
2523                 
2524                 while(eed) {
2525                         v1= eed->v1;
2526                         v2= eed->v2;
2527                         
2528                         if(eed->h==0) {
2529                                 if(v1->f1 && v2->f1==0) {
2530                                         v2->f1= 1;
2531                                         done= 1;
2532                                 }
2533                                 else if(v1->f1==0 && v2->f1) {
2534                                         v1->f1= 1;
2535                                         done= 1;
2536                                 }
2537                         }
2538                         
2539                         if(toggle & 1) eed= eed->next;
2540                         else eed= eed->prev;
2541                 }
2542         }
2543         
2544         /* now use vertex f1 flag to select/deselect */
2545         for(eed= vc.em->edges.first; eed; eed= eed->next) {
2546                 if(eed->v1->f1 && eed->v2->f1) 
2547                         EM_select_edge(eed, sel);
2548         }
2549         for(efa= vc.em->faces.first; efa; efa= efa->next) {
2550                 if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
2551                         EM_select_face(efa, sel);
2552         }
2553         /* no flush needed, connected geometry is done */
2554         
2555 //      if (EM_texFaceCheck())
2556         
2557         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2558         return OPERATOR_FINISHED;       
2559 }
2560
2561 void MESH_OT_select_linked_pick(wmOperatorType *ot)
2562 {
2563         /* identifiers */
2564         ot->name= "Select Linked";
2565         ot->description= "(un)select all vertices linked to the active mesh";
2566         ot->idname= "MESH_OT_select_linked_pick";
2567         
2568         /* api callbacks */
2569         ot->invoke= select_linked_pick_invoke;
2570         ot->poll= ED_operator_editmesh_region_view3d;
2571         
2572         /* flags */
2573         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2574         
2575         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
2576         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "Limit selection by seam boundaries (faces only)");
2577 }
2578
2579
2580 /* ************************* */
2581
2582 void selectconnected_mesh_all(EditMesh *em)
2583 {
2584         EditVert *v1,*v2;
2585         EditEdge *eed;
2586         short done=1, toggle=0;
2587         
2588         if(em->edges.first==0) return;
2589         
2590         while(done==1) {
2591                 done= 0;
2592                 
2593                 toggle++;
2594                 if(toggle & 1) eed= em->edges.first;
2595                 else eed= em->edges.last;
2596                 
2597                 while(eed) {
2598                         v1= eed->v1;
2599                         v2= eed->v2;
2600                         if(eed->h==0) {
2601                                 if(v1->f & SELECT) {
2602                                         if( (v2->f & SELECT)==0 ) {
2603                                                 v2->f |= SELECT;
2604                                                 done= 1;
2605                                         }
2606                                 }
2607                                 else if(v2->f & SELECT) {
2608                                         if( (v1->f & SELECT)==0 ) {
2609                                                 v1->f |= SELECT;
2610                                                 done= 1;
2611                                         }
2612                                 }
2613                         }
2614                         if(toggle & 1) eed= eed->next;
2615                         else eed= eed->prev;
2616                 }
2617         }
2618         
2619         /* now use vertex select flag to select rest */
2620         EM_select_flush(em);
2621         
2622         //      if (EM_texFaceCheck())
2623 }
2624
2625 static int select_linked_exec(bContext *C, wmOperator *op)
2626 {
2627         Object *obedit= CTX_data_edit_object(C);
2628         EditMesh *em= BKE_mesh_get_editmesh(obedit->data);
2629         
2630         if( RNA_boolean_get(op->ptr, "limit") ) {
2631                 ViewContext vc;
2632                 em_setup_viewcontext(C, &vc);
2633                 select_linked_limited_invoke(&vc, 1, 1);
2634         }
2635         else
2636                 selectconnected_mesh_all(em);
2637         
2638         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2639
2640         BKE_mesh_end_editmesh(obedit->data, em);
2641         return OPERATOR_FINISHED;       
2642 }
2643
2644 static int select_linked_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2645 {
2646         linked_limit_default(C, op);
2647         return select_linked_exec(C, op);
2648 }
2649
2650 void MESH_OT_select_linked(wmOperatorType *ot)
2651 {
2652         /* identifiers */
2653         ot->name= "Select Linked All";
2654         ot->description= "Select all vertices linked to the active mesh";
2655         ot->idname= "MESH_OT_select_linked";
2656         
2657         /* api callbacks */
2658         ot->exec= select_linked_exec;
2659         ot->invoke= select_linked_invoke;
2660         ot->poll= ED_operator_editmesh;
2661         
2662         /* flags */
2663         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2664         
2665         RNA_def_boolean(ot->srna, "limit", 0, "Limit by Seams", "Limit selection by seam boundaries (faces only)");
2666 }
2667
2668
2669 /* ************************* */
2670
2671 /* swap is 0 or 1, if 1 it hides not selected */
2672 void EM_hide_mesh(EditMesh *em, int swap)
2673 {
2674         EditVert *eve;
2675         EditEdge *eed;
2676         EditFace *efa;
2677         int a;
2678         
2679         if(em==NULL) return;
2680
2681         /* hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
2682         /*  - vertex hidden, always means edge is hidden too
2683                 - edge hidden, always means face is hidden too
2684                 - face hidden, only set face hide
2685                 - then only flush back down what's absolute hidden
2686         */
2687         if(em->selectmode & SCE_SELECT_VERTEX) {
2688                 for(eve= em->verts.first; eve; eve= eve->next) {
2689                         if((eve->f & SELECT)!=swap) {
2690                                 eve->f &= ~SELECT;
2691                                 eve->h= 1;
2692                         }
2693                 }
2694         
2695                 for(eed= em->edges.first; eed; eed= eed->next) {
2696                         if(eed->v1->h || eed->v2->h) {
2697                                 eed->h |= 1;
2698                                 eed->f &= ~SELECT;
2699                         }
2700                 }
2701         
2702                 for(efa= em->faces.first; efa; efa= efa->next) {
2703                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2704                                 efa->h= 1;
2705                                 efa->f &= ~SELECT;
2706                         }
2707                 }
2708         }
2709         else if(em->selectmode & SCE_SELECT_EDGE) {
2710
2711                 for(eed= em->edges.first; eed; eed= eed->next) {
2712                         if((eed->f & SELECT)!=swap) {
2713                                 eed->h |= 1;
2714                                 EM_select_edge(eed, 0);
2715                         }
2716                 }
2717
2718                 for(efa= em->faces.first; efa; efa= efa->next) {
2719                         if(efa->e1->h & 1 || efa->e2->h & 1 || efa->e3->h & 1 || (efa->e4 && efa->e4->h & 1)) {
2720                                 efa->h= 1;
2721                                 efa->f &= ~SELECT;
2722                         }
2723                 }
2724         }
2725         else {
2726
2727                 for(efa= em->faces.first; efa; efa= efa->next) {
2728                         if((efa->f & SELECT)!=swap) {
2729                                 efa->h= 1;
2730                                 EM_select_face(efa, 0);
2731                         }
2732                 }
2733         }
2734         
2735         /* flush down, only whats 100% hidden */
2736         for(eve= em->verts.first; eve; eve= eve->next) eve->f1= 0;
2737         for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
2738         
2739         if(em->selectmode & SCE_SELECT_FACE) {
2740                 for(efa= em->faces.first; efa; efa= efa->next) {
2741                         if(efa->h) a= 1; else a= 2;
2742                         efa->e1->f1 |= a;
2743                         efa->e2->f1 |= a;
2744                         efa->e3->f1 |= a;
2745                         if(efa->e4) efa->e4->f1 |= a;
2746                         /* When edges are not delt with in their own loop, we need to explicitly re-selct select edges that are joined to unselected faces */
2747                         if (swap && (em->selectmode == SCE_SELECT_FACE) && (efa->f & SELECT)) {
2748                                 EM_select_face(efa, 1);
2749                         }
2750                 }
2751         }
2752         
2753         if(em->selectmode >= SCE_SELECT_EDGE) {
2754                 for(eed= em->edges.first; eed; eed= eed->next) {
2755                         if(eed->f1==1) eed->h |= 1;
2756                         if(eed->h & 1) a= 1; else a= 2;
2757                         eed->v1->f1 |= a;
2758                         eed->v2->f1 |= a;
2759                 }
2760         }
2761
2762         if(em->selectmode >= SCE_SELECT_VERTEX) {
2763                 for(eve= em->verts.first; eve; eve= eve->next) {
2764                         if(eve->f1==1) eve->h= 1;
2765                 }
2766         }
2767         
2768         em->totedgesel= em->totfacesel= em->totvertsel= 0;
2769 //      if(EM_texFaceCheck())
2770
2771         //      DAG_id_tag_update(obedit->data, 0);
2772 }
2773
2774 static int hide_mesh_exec(bContext *C, wmOperator *op)
2775 {
2776         Object *obedit= CTX_data_edit_object(C);
2777         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2778         
2779         EM_hide_mesh(em, RNA_boolean_get(op->ptr, "unselected"));
2780                 
2781         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2782
2783         BKE_mesh_end_editmesh(obedit->data, em);
2784         return OPERATOR_FINISHED;       
2785 }
2786
2787 void MESH_OT_hide(wmOperatorType *ot)
2788 {
2789         /* identifiers */
2790         ot->name= "Hide Selection";
2791         ot->description= "Hide (un)selected vertices, edges or faces";
2792         ot->idname= "MESH_OT_hide";
2793         
2794         /* api callbacks */
2795         ot->exec= hide_mesh_exec;
2796         ot->poll= ED_operator_editmesh;
2797         
2798         /* flags */
2799         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2800         
2801         /* props */
2802         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
2803 }
2804
2805 void EM_reveal_mesh(EditMesh *em)
2806 {
2807         EditVert *eve;
2808         EditEdge *eed;
2809         EditFace *efa;
2810         
2811         if(em==NULL) return;
2812
2813         for(eve= em->verts.first; eve; eve= eve->next) {
2814                 if(eve->h) {
2815                         eve->h= 0;
2816                         eve->f |= SELECT;
2817                 }
2818         }
2819         for(eed= em->edges.first; eed; eed= eed->next) {
2820                 if(eed->h & 1) {
2821                         eed->h &= ~1;
2822                         if(em->selectmode & SCE_SELECT_VERTEX); 
2823                         else EM_select_edge(eed, 1);
2824                 }
2825         }
2826         for(efa= em->faces.first; efa; efa= efa->next) {
2827                 if(efa->h) {
2828                         efa->h= 0;
2829                         if(em->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)); 
2830                         else EM_select_face(efa, 1);
2831                 }
2832         }
2833
2834         EM_fgon_flags(em);      /* redo flags and indices for fgons */
2835         EM_selectmode_flush(em);
2836
2837 //      if (EM_texFaceCheck())
2838 //      DAG_id_tag_update(obedit->data, 0);
2839 }
2840
2841 static int reveal_mesh_exec(bContext *C, wmOperator *UNUSED(op))
2842 {
2843         Object *obedit= CTX_data_edit_object(C);
2844         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2845         
2846         EM_reveal_mesh(em);
2847
2848         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2849
2850         BKE_mesh_end_editmesh(obedit->data, em);
2851         return OPERATOR_FINISHED;       
2852 }
2853
2854 void MESH_OT_reveal(wmOperatorType *ot)
2855 {
2856         /* identifiers */
2857         ot->name= "Reveal Hidden";
2858         ot->description= "Reveal all hidden vertices, edges and faces";
2859         ot->idname= "MESH_OT_reveal";
2860         
2861         /* api callbacks */
2862         ot->exec= reveal_mesh_exec;
2863         ot->poll= ED_operator_editmesh;
2864         
2865         /* flags */
2866         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2867 }
2868
2869 static int select_by_number_vertices_exec(bContext *C, wmOperator *op)
2870 {
2871         Object *obedit= CTX_data_edit_object(C);
2872         EditMesh *em= BKE_mesh_get_editmesh(((Mesh *)obedit->data));
2873         EditFace *efa;
2874         int numverts= RNA_enum_get(op->ptr, "type");
2875
2876         /* Selects trias/qiads or isolated verts, and edges that do not have 2 neighboring
2877          * faces
2878          */
2879
2880         /* for loose vertices/edges, we first select all, loop below will deselect */
2881         if(numverts==5) {
2882                 EM_set_flag_all(em, SELECT);
2883         }
2884         else if(em->selectmode!=SCE_SELECT_FACE) {
2885                 BKE_report(op->reports, RPT_WARNING, "Only works in face selection mode");
2886                 return OPERATOR_CANCELLED;
2887         }
2888         
2889         for(efa= em->faces.first; efa; efa= efa->next) {
2890                 if (efa->e4) {
2891                         EM_select_face(efa, (numverts==4) );
2892                 }
2893                 else {
2894                         EM_select_face(efa, (numverts==3) );
2895                 }
2896         }
2897         
2898         EM_selectmode_flush(em);
2899
2900         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data);
2901         
2902         return OPERATOR_FINISHED;
2903 }
2904
2905 void MESH_OT_select_by_number_vertices(wmOperatorType *ot)
2906 {
2907         static const EnumPropertyItem type_items[]= {
2908                 {3, "TRIANGLES", 0, "Triangles", NULL},
2909                 {4, "QUADS", 0, "Quads", NULL},
2910                 {5, "OTHER", 0, "Other", NULL},
2911                 {0, NULL, 0, NULL, NULL}};
2912
2913         /* identifiers */
2914         ot->name= "Select by Number of Vertices";
2915         ot->description= "Select vertices or faces by vertex count";
2916         ot->idname= "MESH_OT_select_by_number_vertices";
2917         
2918         /* api callbacks */
2919         ot->exec= select_by_number_vertices_exec;
2920         ot->invoke= WM_menu_invoke;
2921         ot->poll= ED_operator_editmesh;