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