Fix for editmehs select grouped.
[blender.git] / source / blender / src / editmesh_mods.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2004 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 /*
34
35 editmesh_mods.c, UI level access, no geometry changes 
36
37 */
38
39 #include <stdlib.h>
40 #include <string.h>
41 #include <math.h>
42
43 #include "MEM_guardedalloc.h"
44
45 #include "MTC_matrixops.h"
46
47 #include "DNA_mesh_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_modifier_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_texture_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_screen_types.h"
55 #include "DNA_view3d_types.h"
56
57 #include "BLI_blenlib.h"
58 #include "BLI_arithb.h"
59 #include "BLI_editVert.h"
60 #include "BLI_rand.h"
61
62 #include "BKE_displist.h"
63 #include "BKE_depsgraph.h"
64 #include "BKE_DerivedMesh.h"
65 #include "BKE_global.h"
66 #include "BKE_mesh.h"
67 #include "BKE_material.h"
68 #include "BKE_texture.h"
69 #include "BKE_utildefines.h"
70
71 #include "BIF_editmesh.h"
72 #include "BIF_resources.h"
73 #include "BIF_gl.h"
74 #include "BIF_glutil.h"
75 #include "BIF_graphics.h"
76 #include "BIF_interface.h"
77 #include "BIF_meshtools.h"
78 #include "BIF_mywindow.h"
79 #include "BIF_resources.h"
80 #include "BIF_screen.h"
81 #include "BIF_space.h"
82 #include "BIF_toolbox.h"
83
84 #include "BDR_drawobject.h"
85 #include "BDR_editobject.h"
86
87 #include "BSE_drawview.h"
88 #include "BSE_edit.h"
89 #include "BSE_view.h"
90
91 #include "IMB_imbuf_types.h"
92 #include "IMB_imbuf.h"
93
94 #include "RE_render_ext.h"  /* externtex */
95
96 #include "mydevice.h"
97 #include "blendef.h"
98
99 #include "editmesh.h"
100
101
102 /* ****************************** MIRROR **************** */
103
104 void EM_select_mirrored(void)
105 {
106         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
107                 EditMesh *em = G.editMesh;
108                 EditVert *eve, *v1;
109                 
110                 for(eve= em->verts.first; eve; eve= eve->next) {
111                         if(eve->f & SELECT) {
112                                 v1= editmesh_get_x_mirror_vert(G.obedit, eve->co);
113                                 if(v1) {
114                                         eve->f &= ~SELECT;
115                                         v1->f |= SELECT;
116                                 }
117                         }
118                 }
119         }
120 }
121
122 /* ****************************** SELECTION ROUTINES **************** */
123
124 unsigned int em_solidoffs=0, em_wireoffs=0, em_vertoffs=0;      /* set in drawobject.c ... for colorindices */
125
126 /* facilities for border select and circle select */
127 static char *selbuf= NULL;
128
129 /* opengl doesn't support concave... */
130 static void draw_triangulated(short mcords[][2], short tot)
131 {
132         ListBase lb={NULL, NULL};
133         DispList *dl;
134         float *fp;
135         int a;
136         
137         /* make displist */
138         dl= MEM_callocN(sizeof(DispList), "poly disp");
139         dl->type= DL_POLY;
140         dl->parts= 1;
141         dl->nr= tot;
142         dl->verts= fp=  MEM_callocN(tot*3*sizeof(float), "poly verts");
143         BLI_addtail(&lb, dl);
144         
145         for(a=0; a<tot; a++, fp+=3) {
146                 fp[0]= (float)mcords[a][0];
147                 fp[1]= (float)mcords[a][1];
148         }
149         
150         /* do the fill */
151         filldisplist(&lb, &lb);
152
153         /* do the draw */
154         dl= lb.first;   /* filldisplist adds in head of list */
155         if(dl->type==DL_INDEX3) {
156                 int *index;
157                 
158                 a= dl->parts;
159                 fp= dl->verts;
160                 index= dl->index;
161                 glBegin(GL_TRIANGLES);
162                 while(a--) {
163                         glVertex3fv(fp+3*index[0]);
164                         glVertex3fv(fp+3*index[1]);
165                         glVertex3fv(fp+3*index[2]);
166                         index+= 3;
167                 }
168                 glEnd();
169         }
170         
171         freedisplist(&lb);
172 }
173
174
175 /* reads rect, and builds selection array for quick lookup */
176 /* returns if all is OK */
177 int EM_init_backbuf_border(short xmin, short ymin, short xmax, short ymax)
178 {
179         struct ImBuf *buf;
180         unsigned int *dr;
181         int a;
182         
183         if(G.obedit==NULL || G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
184         if(em_vertoffs==0) return 0;
185         
186         buf= read_backbuf(xmin, ymin, xmax, ymax);
187         if(buf==NULL) return 0;
188
189         dr = buf->rect;
190         
191         /* build selection lookup */
192         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
193         
194         a= (xmax-xmin+1)*(ymax-ymin+1);
195         while(a--) {
196                 if(*dr>0 && *dr<=em_vertoffs) 
197                         selbuf[*dr]= 1;
198                 dr++;
199         }
200         IMB_freeImBuf(buf);
201         return 1;
202 }
203
204 int EM_check_backbuf(unsigned int index)
205 {
206         if(selbuf==NULL) return 1;
207         if(index>0 && index<=em_vertoffs)
208                 return selbuf[index];
209         return 0;
210 }
211
212 void EM_free_backbuf(void)
213 {
214         if(selbuf) MEM_freeN(selbuf);
215         selbuf= NULL;
216 }
217
218 /* mcords is a polygon mask
219    - grab backbuffer,
220    - draw with black in backbuffer, 
221    - grab again and compare
222    returns 'OK' 
223 */
224 int EM_mask_init_backbuf_border(short mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
225 {
226         unsigned int *dr, *drm;
227         struct ImBuf *buf, *bufmask;
228         int a;
229         
230         /* method in use for face selecting too */
231         if(G.obedit==NULL) {
232                 if(G.f & G_FACESELECT);
233                 else return 0;
234         }
235         else if(G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
236
237         if(em_vertoffs==0) return 0;
238         
239         buf= read_backbuf(xmin, ymin, xmax, ymax);
240         if(buf==NULL) return 0;
241
242         dr = buf->rect;
243
244         /* draw the mask */
245 #ifdef __APPLE__
246         glDrawBuffer(GL_AUX0);
247 #endif
248         glDisable(GL_DEPTH_TEST);
249         
250         persp(PERSP_WIN);
251         glColor3ub(0, 0, 0);
252         
253         /* yah, opengl doesn't do concave... tsk! */
254         draw_triangulated(mcords, tot); 
255         
256         glBegin(GL_LINE_LOOP);  /* for zero sized masks, lines */
257         for(a=0; a<tot; a++) glVertex2s(mcords[a][0], mcords[a][1]);
258         glEnd();
259         
260         persp(PERSP_VIEW);
261         glFinish();     /* to be sure readpixels sees mask */
262         
263         glDrawBuffer(GL_BACK);
264         
265         /* grab mask */
266         bufmask= read_backbuf(xmin, ymin, xmax, ymax);
267         drm = bufmask->rect;
268         if(bufmask==NULL) return 0; /* only when mem alloc fails, go crash somewhere else! */
269         
270         /* build selection lookup */
271         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
272         
273         a= (xmax-xmin+1)*(ymax-ymin+1);
274         while(a--) {
275                 if(*dr>0 && *dr<=em_vertoffs && *drm==0) selbuf[*dr]= 1;
276                 dr++; drm++;
277         }
278         IMB_freeImBuf(buf);
279         IMB_freeImBuf(bufmask);
280         return 1;
281         
282 }
283
284 /* circle shaped sample area */
285 int EM_init_backbuf_circle(short xs, short ys, short rads)
286 {
287         struct ImBuf *buf;
288         unsigned int *dr;
289         short xmin, ymin, xmax, ymax, xc, yc;
290         int radsq;
291         
292         /* method in use for face selecting too */
293         if(G.obedit==NULL) {
294                 if(G.f & G_FACESELECT);
295                 else return 0;
296         }
297         else if(G.vd->drawtype<OB_SOLID || (G.vd->flag & V3D_ZBUF_SELECT)==0) return 0;
298         if(em_vertoffs==0) return 0;
299         
300         xmin= xs-rads; xmax= xs+rads;
301         ymin= ys-rads; ymax= ys+rads;
302         buf= read_backbuf(xmin, ymin, xmax, ymax);
303         if(buf==NULL) return 0;
304
305         dr = buf->rect;
306         
307         /* build selection lookup */
308         selbuf= MEM_callocN(em_vertoffs+1, "selbuf");
309         radsq= rads*rads;
310         for(yc= -rads; yc<=rads; yc++) {
311                 for(xc= -rads; xc<=rads; xc++, dr++) {
312                         if(xc*xc + yc*yc < radsq) {
313                                 if(*dr>0 && *dr<=em_vertoffs) selbuf[*dr]= 1;
314                         }
315                 }
316         }
317
318         IMB_freeImBuf(buf);
319         return 1;
320         
321 }
322
323 static void findnearestvert__doClosest(void *userData, EditVert *eve, int x, int y, int index)
324 {
325         struct { short mval[2], pass, select; int dist, lastIndex, closestIndex; EditVert *closest; } *data = userData;
326
327         if (data->pass==0) {
328                 if (index<=data->lastIndex)
329                         return;
330         } else {
331                 if (index>data->lastIndex)
332                         return;
333         }
334
335         if (data->dist>3) {
336                 int temp = abs(data->mval[0] - x) + abs(data->mval[1]- y);
337                 if ((eve->f&1)==data->select) temp += 5;
338
339                 if (temp<data->dist) {
340                         data->dist = temp;
341                         data->closest = eve;
342                         data->closestIndex = index;
343                 }
344         }
345 }
346 static EditVert *findnearestvert(short *dist, short sel)
347 {
348         short mval[2];
349
350         getmouseco_areawin(mval);
351                 
352         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
353                 short distance;
354                 unsigned int index = sample_backbuf_rect(mval, 50, em_wireoffs, 0xFFFFFF, &distance);
355                 EditVert *eve = BLI_findlink(&G.editMesh->verts, index-1);
356
357                 if (eve && distance < *dist) {
358                         *dist = distance;
359                         return eve;
360                 } else {
361                         return NULL;
362                 }
363         }
364         else {
365                 struct { short mval[2], pass, select; int dist, lastIndex, closestIndex; EditVert *closest; } data;
366                 static int lastSelectedIndex=0;
367                 static EditVert *lastSelected=NULL;
368
369                 if (lastSelected && BLI_findlink(&G.editMesh->verts, lastSelectedIndex)!=lastSelected) {
370                         lastSelectedIndex = 0;
371                         lastSelected = NULL;
372                 }
373
374                 data.lastIndex = lastSelectedIndex;
375                 data.mval[0] = mval[0];
376                 data.mval[1] = mval[1];
377                 data.select = sel;
378                 data.dist = *dist;
379                 data.closest = NULL;
380                 data.closestIndex = 0;
381
382                 data.pass = 0;
383                 mesh_foreachScreenVert(findnearestvert__doClosest, &data, 1);
384
385                 if (data.dist>3) {
386                         data.pass = 1;
387                         mesh_foreachScreenVert(findnearestvert__doClosest, &data, 1);
388                 }
389
390                 *dist = data.dist;
391                 lastSelected = data.closest;
392                 lastSelectedIndex = data.closestIndex;
393
394                 return data.closest;
395         }
396 }
397
398 /* returns labda for closest distance v1 to line-piece v2-v3 */
399 static float labda_PdistVL2Dfl( float *v1, float *v2, float *v3) 
400 {
401         float rc[2], len;
402         
403         rc[0]= v3[0]-v2[0];
404         rc[1]= v3[1]-v2[1];
405         len= rc[0]*rc[0]+ rc[1]*rc[1];
406         if(len==0.0f)
407                 return 0.0f;
408         
409         return ( rc[0]*(v1[0]-v2[0]) + rc[1]*(v1[1]-v2[1]) )/len;
410 }
411
412 /* note; uses G.vd, so needs active 3d window */
413 static void findnearestedge__doClosest(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int index)
414 {
415         struct { float mval[2]; short dist; EditEdge *closest; } *data = userData;
416         float v1[2], v2[2];
417         short distance;
418                 
419         v1[0] = x0;
420         v1[1] = y0;
421         v2[0] = x1;
422         v2[1] = y1;
423                 
424         distance= PdistVL2Dfl(data->mval, v1, v2);
425                 
426         if(eed->f & SELECT) distance+=5;
427         if(distance < data->dist) {
428                 if(G.vd->flag & V3D_CLIPPING) {
429                         float labda= labda_PdistVL2Dfl(data->mval, v1, v2);
430                         float vec[3];
431
432                         vec[0]= eed->v1->co[0] + labda*(eed->v2->co[0] - eed->v1->co[0]);
433                         vec[1]= eed->v1->co[1] + labda*(eed->v2->co[1] - eed->v1->co[1]);
434                         vec[2]= eed->v1->co[2] + labda*(eed->v2->co[2] - eed->v1->co[2]);
435                         Mat4MulVecfl(G.obedit->obmat, vec);
436
437                         if(view3d_test_clipping(G.vd, vec)==0) {
438                                 data->dist = distance;
439                                 data->closest = eed;
440                         }
441                 }
442                 else {
443                         data->dist = distance;
444                         data->closest = eed;
445                 }
446         }
447 }
448 EditEdge *findnearestedge(short *dist)
449 {
450         short mval[2];
451                 
452         getmouseco_areawin(mval);
453
454         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
455                 short distance;
456                 unsigned int index = sample_backbuf_rect(mval, 50, em_solidoffs, em_wireoffs, &distance);
457                 EditEdge *eed = BLI_findlink(&G.editMesh->edges, index-1);
458
459                 if (eed && distance<*dist) {
460                         *dist = distance;
461                         return eed;
462                 } else {
463                         return NULL;
464                 }
465         }
466         else {
467                 struct { float mval[2]; short dist; EditEdge *closest; } data;
468
469                 data.mval[0] = mval[0];
470                 data.mval[1] = mval[1];
471                 data.dist = *dist;
472                 data.closest = NULL;
473
474                 mesh_foreachScreenEdge(findnearestedge__doClosest, &data, 2);
475
476                 *dist = data.dist;
477                 return data.closest;
478         }
479 }
480
481 static void findnearestface__getDistance(void *userData, EditFace *efa, int x, int y, int index)
482 {
483         struct { short mval[2], dist; EditFace *toFace; } *data = userData;
484
485         if (efa==data->toFace) {
486                 short temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
487
488                 if (temp<data->dist)
489                         data->dist = temp;
490         }
491 }
492 static void findnearestface__doClosest(void *userData, EditFace *efa, int x, int y, int index)
493 {
494         struct { short mval[2], pass, dist; int lastIndex, closestIndex; EditFace *closest; } *data = userData;
495
496         if (data->pass==0) {
497                 if (index<=data->lastIndex)
498                         return;
499         } else {
500                 if (index>data->lastIndex)
501                         return;
502         }
503
504         if (data->dist>3) {
505                 short temp = abs(data->mval[0]-x) + abs(data->mval[1]-y);
506
507                 if (temp<data->dist) {
508                         data->dist = temp;
509                         data->closest = efa;
510                         data->closestIndex = index;
511                 }
512         }
513 }
514 static EditFace *findnearestface(short *dist)
515 {
516         short mval[2];
517
518         getmouseco_areawin(mval);
519
520         if(G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT)) {
521                 unsigned int index = sample_backbuf(mval[0], mval[1]);
522                 EditFace *efa = BLI_findlink(&G.editMesh->faces, index-1);
523
524                 if (efa) {
525                         struct { short mval[2], dist; EditFace *toFace; } data;
526
527                         data.mval[0] = mval[0];
528                         data.mval[1] = mval[1];
529                         data.dist = 0x7FFF;             /* largest short */
530                         data.toFace = efa;
531
532                         mesh_foreachScreenFace(findnearestface__getDistance, &data);
533
534                         if(G.scene->selectmode == SCE_SELECT_FACE || data.dist<*dist) { /* only faces, no dist check */
535                                 *dist= data.dist;
536                                 return efa;
537                         }
538                 }
539                 
540                 return NULL;
541         }
542         else {
543                 struct { short mval[2], pass, dist; int lastIndex, closestIndex; EditFace *closest; } data;
544                 static int lastSelectedIndex=0;
545                 static EditFace *lastSelected=NULL;
546
547                 if (lastSelected && BLI_findlink(&G.editMesh->faces, lastSelectedIndex)!=lastSelected) {
548                         lastSelectedIndex = 0;
549                         lastSelected = NULL;
550                 }
551
552                 data.lastIndex = lastSelectedIndex;
553                 data.mval[0] = mval[0];
554                 data.mval[1] = mval[1];
555                 data.dist = *dist;
556                 data.closest = NULL;
557                 data.closestIndex = 0;
558
559                 data.pass = 0;
560                 mesh_foreachScreenFace(findnearestface__doClosest, &data);
561
562                 if (data.dist>3) {
563                         data.pass = 1;
564                         mesh_foreachScreenFace(findnearestface__doClosest, &data);
565                 }
566
567                 *dist = data.dist;
568                 lastSelected = data.closest;
569                 lastSelectedIndex = data.closestIndex;
570
571                 return data.closest;
572         }
573 }
574
575 /* for interactivity, frontbuffer draw in current window */
576 static void draw_dm_mapped_vert__mapFunc(void *theVert, int index, float *co, float *no_f, short *no_s)
577 {
578         if (EM_get_vert_for_index(index)==theVert) {
579                 bglVertex3fv(co);
580         }
581 }
582 static void draw_dm_mapped_vert(DerivedMesh *dm, EditVert *eve)
583 {
584         EM_init_index_arrays(1, 0, 0);
585         bglBegin(GL_POINTS);
586         dm->foreachMappedVert(dm, draw_dm_mapped_vert__mapFunc, eve);
587         bglEnd();
588         EM_free_index_arrays();
589 }
590
591 static int draw_dm_mapped_edge__setDrawOptions(void *theEdge, int index)
592 {
593         return EM_get_edge_for_index(index)==theEdge;
594 }
595 static void draw_dm_mapped_edge(DerivedMesh *dm, EditEdge *eed)
596 {
597         EM_init_index_arrays(0, 1, 0);
598         dm->drawMappedEdges(dm, draw_dm_mapped_edge__setDrawOptions, eed);
599         EM_free_index_arrays();
600 }
601
602 static void draw_dm_mapped_face_center__mapFunc(void *theFace, int index, float *cent, float *no)
603 {
604         if (EM_get_face_for_index(index)==theFace) {
605                 bglVertex3fv(cent);
606         }
607 }
608 static void draw_dm_mapped_face_center(DerivedMesh *dm, EditFace *efa)
609 {
610         EM_init_index_arrays(0, 0, 1);
611         bglBegin(GL_POINTS);
612         dm->foreachMappedFaceCenter(dm, draw_dm_mapped_face_center__mapFunc, efa);
613         bglEnd();
614         EM_free_index_arrays();
615 }
616
617 static void unified_select_draw(EditVert *eve, EditEdge *eed, EditFace *efa)
618 {
619         int dmNeedsFree;
620         DerivedMesh *dm = editmesh_get_derived_cage(&dmNeedsFree);
621
622         glDrawBuffer(GL_FRONT);
623
624         persp(PERSP_VIEW);
625         
626         if(G.vd->flag & V3D_CLIPPING)
627                 view3d_set_clipping(G.vd);
628         
629         glPushMatrix();
630         mymultmatrix(G.obedit->obmat);
631         
632         /* face selected */
633         if(efa) {
634                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
635                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
636                         
637                         if(efa->f & SELECT) BIF_ThemeColor(TH_VERTEX_SELECT);
638                         else BIF_ThemeColor(TH_VERTEX);
639                         
640                         bglBegin(GL_POINTS);
641                         bglVertex3fv(efa->v1->co);
642                         bglVertex3fv(efa->v2->co);
643                         bglVertex3fv(efa->v3->co);
644                         if(efa->v4) bglVertex3fv(efa->v4->co);
645                         bglEnd();
646                 }
647
648                 if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_FACE)) {
649                         if(efa->fgonf==0) {
650                                 BIF_ThemeColor((efa->f & SELECT)?TH_EDGE_SELECT:TH_WIRE);
651         
652                                 draw_dm_mapped_edge(dm, efa->e1);
653                                 draw_dm_mapped_edge(dm, efa->e2);
654                                 draw_dm_mapped_edge(dm, efa->e3);
655                                 if (efa->e4) {
656                                         draw_dm_mapped_edge(dm, efa->e4);
657                                 }
658                         }
659                 }
660                 
661                 if(G.scene->selectmode & SCE_SELECT_FACE) {
662                         if(efa->fgonf==0) {
663                                 glPointSize(BIF_GetThemeValuef(TH_FACEDOT_SIZE));
664                                 BIF_ThemeColor((efa->f & SELECT)?TH_FACE_DOT:TH_WIRE);
665
666                                 draw_dm_mapped_face_center(dm, efa);
667                         }
668                 }
669         }
670         /* edge selected */
671         if(eed) {
672                 if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_FACE)) {
673                         BIF_ThemeColor((eed->f & SELECT)?TH_EDGE_SELECT:TH_WIRE);
674
675                         draw_dm_mapped_edge(dm, eed);
676                 }
677                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
678                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
679                         
680                         BIF_ThemeColor((eed->f & SELECT)?TH_VERTEX_SELECT:TH_VERTEX);
681                         
682                         draw_dm_mapped_vert(dm, eed->v1);
683                         draw_dm_mapped_vert(dm, eed->v2);
684                 }
685         }
686         if(eve) {
687                 if(G.scene->selectmode & SCE_SELECT_VERTEX) {
688                         glPointSize(BIF_GetThemeValuef(TH_VERTEX_SIZE));
689                         
690                         BIF_ThemeColor((eve->f & SELECT)?TH_VERTEX_SELECT:TH_VERTEX);
691                         
692                         draw_dm_mapped_vert(dm, eve);
693                 }
694         }
695
696         glPointSize(1.0);
697         glPopMatrix();
698
699         glFlush();
700         glDrawBuffer(GL_BACK);
701
702         if(G.vd->flag & V3D_CLIPPING)
703                 view3d_clr_clipping();
704         
705         /* signal that frontbuf differs from back */
706         curarea->win_swap= WIN_FRONT_OK;
707
708         if (dmNeedsFree) {
709                 dm->release(dm);
710         }
711 }
712
713
714 /* best distance based on screen coords. 
715    use g.scene->selectmode to define how to use 
716    selected vertices and edges get disadvantage
717    return 1 if found one
718 */
719 static int unified_findnearest(EditVert **eve, EditEdge **eed, EditFace **efa) 
720 {
721         short dist= 75;
722         
723         *eve= NULL;
724         *eed= NULL;
725         *efa= NULL;
726         
727         if(G.scene->selectmode & SCE_SELECT_VERTEX)
728                 *eve= findnearestvert(&dist, SELECT);
729         if(G.scene->selectmode & SCE_SELECT_FACE)
730                 *efa= findnearestface(&dist);
731
732         dist-= 20;      /* since edges select lines, we give dots advantage of 20 pix */
733         if(G.scene->selectmode & SCE_SELECT_EDGE)
734                 *eed= findnearestedge(&dist);
735
736         /* return only one of 3 pointers, for frontbuffer redraws */
737         if(*eed) {
738                 *efa= NULL; *eve= NULL;
739         }
740         else if(*efa) {
741                 *eve= NULL;
742         }
743         
744         return (*eve || *eed || *efa);
745 }
746
747 /* this as a way to compare the ares, perim  of 2 faces thay will scale to different sizes */
748 #define SCALE_CMP(a,b) (fabs(a-b) <= thresh || (a>0 && fabs(b/a)<=thresh))
749
750 /* ****************  GROUP SELECTS ************** */
751 /* selects new faces/edges/verts based on the
752  existing selection
753
754 FACES GROUP
755  mode 1: same material
756  mode 2: same image
757  mode 3: same area
758  mode 4: same perimeter
759  mode 5: same normal
760  mode 6: same co-planer
761 */
762 int facegroup_select(short mode)
763 {
764         EditMesh *em = G.editMesh;
765         EditFace *efa, *base_efa=NULL;
766         unsigned int selcount=0; /*count how many new faces we select*/
767         
768         /*deselcount, count how many deselected faces are left, so we can bail out early
769         also means that if there are no deselected faces, we can avoid a lot of looping */
770         unsigned int deselcount=0; 
771         
772         short ok=0;
773         float thresh=G.scene->toolsettings->select_thresh;
774         
775         for(efa= em->faces.first; efa; efa= efa->next) {
776                 if (!efa->h) {
777                         if (efa->f & SELECT) {
778                                 efa->f1=1;
779                                 ok=1;
780                         } else {
781                                 efa->f1=0;
782                                 deselcount++; /* a deselected face we may select later */
783                         }
784                 }
785         }
786         
787         if (!ok || !deselcount) /* no data selected OR no more data to select */
788                 return 0;
789         
790         /*if mode is 3 then record face areas, 4 record perimeter */
791         if (mode==3) {
792                 for(efa= em->faces.first; efa; efa= efa->next) {
793                         efa->tmp.fp= EM_face_area(efa);
794                 }
795         } else if (mode==4) {
796                 for(efa= em->faces.first; efa; efa= efa->next) {
797                         efa->tmp.fp= EM_face_perimeter(efa);
798                 }
799         }
800         
801         for(base_efa= em->faces.first; base_efa; base_efa= base_efa->next) {
802                 if (base_efa->f1) {
803                         if (mode==1) { /* same material */
804                                 for(efa= em->faces.first; efa; efa= efa->next) {
805                                         if (
806                                                 !(efa->f & SELECT) &&
807                                                 !efa->h &&
808                                                 base_efa->mat_nr == efa->mat_nr
809                                         ) {
810                                                 EM_select_face(efa, 1);
811                                                 selcount++;
812                                                 deselcount--;
813                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
814                                                         return selcount;
815                                         }
816                                 }
817                         } else if (mode==2) { /* same image */
818                                 for(efa= em->faces.first; efa; efa= efa->next) {
819                                         if (!(efa->f & SELECT) && !efa->h && base_efa->tf.tpage == efa->tf.tpage) {
820                                                 EM_select_face(efa, 1);
821                                                 selcount++;
822                                                 deselcount--;
823                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
824                                                         return selcount;
825                                         }
826                                 }
827                         } else if (mode==3 || mode==4) { /* same area OR same perimeter, both use the same temp var */
828                                 for(efa= em->faces.first; efa; efa= efa->next) {
829                                         if (!(efa->f & SELECT) && !efa->h) {
830                                                 if (SCALE_CMP(base_efa->tmp.fp, efa->tmp.fp)) {
831                                                 
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==5) { /* same normal */
841                                 float angle;
842                                 for(efa= em->faces.first; efa; efa= efa->next) {
843                                         if (!(efa->f & SELECT) && !efa->h) {
844                                                 angle= VecAngle2(base_efa->n, efa->n);
845                                                 if (angle/180.0<=thresh) {
846                                                         EM_select_face(efa, 1);
847                                                         selcount++;
848                                                         deselcount--;
849                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
850                                                                 return selcount;
851                                                 }
852                                         }
853                                 }
854                         } else if (mode==6) { /* same planer */
855                                 float angle, base_dot, dot;
856                                 base_dot= Inpf(base_efa->cent, base_efa->n);
857                                 for(efa= em->faces.first; efa; efa= efa->next) {
858                                         if (!(efa->f & SELECT) && !efa->h) {
859                                                 angle= VecAngle2(base_efa->n, efa->n);
860                                                 if (angle/180.0<=thresh) {
861                                                         dot=Inpf(efa->cent, base_efa->n);
862                                                         if (fabs(base_dot-dot) <= thresh) {
863                                                                 EM_select_face(efa, 1);
864                                                                 selcount++;
865                                                                 deselcount--;
866                                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
867                                                                         return selcount;
868                                                         }
869                                                 }
870                                         }
871                                 }
872                         }
873                 }
874         } /* end base_efa loop */
875         return selcount;
876 }
877
878
879 /*
880 EDGE GROUP
881  mode 1: same length
882  mode 2: same direction
883  mode 3: same number of face users
884  mode 4: similar face angles.
885 */
886
887 /* this function is only used by edgegroup_select's edge angle */
888
889
890
891 int edgegroup_select(short mode)
892 {
893         EditMesh *em = G.editMesh;
894         EditEdge *eed, *base_eed=NULL;
895         unsigned int selcount=0; /* count how many new edges we select*/
896         
897         /*count how many visible selected edges there are,
898         so we can return when there are none left */
899         unsigned int deselcount=0;
900         
901         short ok=0;
902         float thresh=G.scene->toolsettings->select_thresh;
903         
904         for(eed= em->edges.first; eed; eed= eed->next) {
905                 if (!eed->h) {
906                         if (eed->f & SELECT) {
907                                 eed->f1=1;
908                                 ok=1;
909                         } else {
910                                 eed->f1=0;
911                                 deselcount++;
912                         }
913                         /* set all eed->tmp.l to 0 we use it later.
914                         for counting face users*/
915                         eed->tmp.l=0;
916                         eed->f2=0; /* only for mode 4, edge animations */
917                 }
918         }
919         
920         if (!ok || !deselcount) /* no data selected OR no more data to select*/
921                 return 0;
922         
923         if (mode==1) { /*store length*/
924                 for(eed= em->edges.first; eed; eed= eed->next) {
925                         eed->tmp.fp= VecLenf(eed->v1->co, eed->v2->co);
926                 }
927         } else if (mode==3) { /*store face users*/
928                 EditFace *efa;
929                 /* cound how many faces each edge uses use tmp->l */
930                 for(efa= em->faces.first; efa; efa= efa->next) {
931                         efa->e1->tmp.l++;
932                         efa->e2->tmp.l++;
933                         efa->e3->tmp.l++;
934                         if (efa->e4) efa->e4->tmp.l++;
935                 }
936         } else if (mode==4) { /*store edge angles */
937                 EditFace *efa;
938                 int j;
939                 /* cound how many faces each edge uses use tmp.l */
940                 for(efa= em->faces.first; efa; efa= efa->next) {
941                         /* here we use the edges temp data to assign a face
942                         if a face has alredy been assigned (eed->f2==1)
943                         we calculate the angle between the current face and
944                         the edges previously found face.
945                         store the angle in eed->tmp.fp (loosing the face eed->tmp.f)
946                         but tagging eed->f2==2, so we know not to look at it again.
947                         This only works for edges that connect to 2 faces. but its good enough
948                         */
949                         
950                         /* se we can loop through face edges*/
951                         j=0;
952                         eed= efa->e1;
953                         while (j<4) {
954                                 if (j==1) eed= efa->e2;
955                                 else if (j==2) eed= efa->e3;
956                                 else if (j==3) {
957                                         eed= efa->e4;
958                                         if (!eed)
959                                                 break;
960                                 } /* done looping */
961                                 
962                                 if (eed->f2==2)
963                                         break;
964                                 else if (eed->f2==0) /* first access, assign the face */
965                                         eed->tmp.f= efa;
966                                 else if (eed->f2==1) /* second, we assign the angle*/
967                                         eed->tmp.fp= VecAngle2(eed->tmp.f->n, efa->n);
968                                 eed->f2++; /* f2==0 no face assigned. f2==1 one face found. f2==2 angle calculated.*/
969                                 j++;
970                         }
971                 }
972         }
973         
974         for(base_eed= em->edges.first; base_eed; base_eed= base_eed->next) {
975                 if (base_eed->f1) {
976                         if (mode==1) { /* same length */
977                                 for(eed= em->edges.first; eed; eed= eed->next) {
978                                         if (
979                                                 !(eed->f & SELECT) &&
980                                                 !eed->h &&
981                                                 (SCALE_CMP(base_eed->tmp.fp, eed->tmp.fp))
982                                         ) {
983                                                 EM_select_edge(eed, 1);
984                                                 selcount++;
985                                                 deselcount--;
986                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
987                                                         return selcount;
988                                         }
989                                 }
990                         } else if (mode==2) { /* same direction */
991                                 float base_dir[3], dir[3], angle;
992                                 VecSubf(base_dir, base_eed->v1->co, base_eed->v2->co);
993                                 for(eed= em->edges.first; eed; eed= eed->next) {
994                                         if (!(eed->f & SELECT) && !eed->h) {
995                                                 VecSubf(dir, eed->v1->co, eed->v2->co);
996                                                 angle= VecAngle2(base_dir, dir);
997                                                 
998                                                 if (angle>90) /* use the smallest angle between the edges */
999                                                         angle= fabs(angle-180.0f);
1000                                                 
1001                                                 if (angle/90.0<=thresh) {
1002                                                         EM_select_edge(eed, 1);
1003                                                         selcount++;
1004                                                         deselcount--;
1005                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
1006                                                                 return selcount;
1007                                                 }
1008                                         }
1009                                 }
1010                         } else if (mode==3) { /* face users */                          
1011                                 for(eed= em->edges.first; eed; eed= eed->next) {
1012                                         if (
1013                                                 !(eed->f & SELECT) &&
1014                                                 !eed->h &&
1015                                                 base_eed->tmp.l==eed->tmp.l
1016                                         ) {
1017                                                 EM_select_edge(eed, 1);
1018                                                 selcount++;
1019                                                 deselcount--;
1020                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1021                                                         return selcount;
1022                                         }
1023                                 }
1024                         } else if (mode==4 && base_eed->f2==2) { /* edge angles, f2==2 means the edge has an angle. */                          
1025                                 for(eed= em->edges.first; eed; eed= eed->next) {
1026                                         if (
1027                                                 !(eed->f & SELECT) &&
1028                                                 !eed->h &&
1029                                                 eed->f2==2 &&
1030                                                 (SCALE_CMP(base_eed->tmp.fp, eed->tmp.fp))
1031                                         ) {
1032                                                 EM_select_edge(eed, 1);
1033                                                 selcount++;
1034                                                 deselcount--;
1035                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1036                                                         return selcount;
1037                                         }
1038                                 }
1039                         }
1040                         
1041                 }
1042         } 
1043         return selcount;
1044 }
1045
1046
1047 /*
1048 VERT GROUP
1049  mode 1: same normal
1050  mode 2: same number of face users
1051  mode 3: same vertex groups
1052 */
1053 int vertgroup_select(short mode)
1054 {
1055         EditMesh *em = G.editMesh;
1056         EditVert *eve, *base_eve=NULL;
1057         
1058         unsigned int selcount=0; /* count how many new edges we select*/
1059         
1060         /*count how many visible selected edges there are,
1061         so we can return when there are none left */
1062         unsigned int deselcount=0;
1063         
1064         short ok=0;
1065         float thresh=G.scene->toolsettings->select_thresh;
1066         
1067         for(eve= em->verts.first; eve; eve= eve->next) {
1068                 if (!eve->h) {
1069                         if (eve->f & SELECT) {
1070                                 eve->f1=1;
1071                                 ok=1;
1072                         } else {
1073                                 eve->f1=0;
1074                                 deselcount++;
1075                         }
1076                         /* set all eve->tmp.l to 0 we use them later.*/
1077                         eve->tmp.l=0;
1078                 }
1079                 
1080         }
1081         
1082         if (!ok || !deselcount) /* no data selected OR no more data to select*/
1083                 return 0;
1084         
1085         
1086         if (mode==2) { /* store face users */
1087                 EditFace *efa;
1088                 
1089                 /* count how many faces each edge uses use tmp->l */
1090                 for(efa= em->faces.first; efa; efa= efa->next) {
1091                         efa->v1->tmp.l++;
1092                         efa->v2->tmp.l++;
1093                         efa->v3->tmp.l++;
1094                         if (efa->v4) efa->v4->tmp.l++;
1095                 }
1096         }
1097         
1098         
1099         for(base_eve= em->verts.first; base_eve; base_eve= base_eve->next) {
1100                 if (base_eve->f1) {
1101                                 
1102                         if (mode==1) { /* same normal */
1103                                 float angle;
1104                                 for(eve= em->verts.first; eve; eve= eve->next) {
1105                                         if (!(eve->f & SELECT) && !eve->h) {
1106                                                 angle= VecAngle2(base_eve->no, eve->no);
1107                                                 if (angle/180.0<=thresh) {
1108                                                         eve->f |= SELECT;
1109                                                         selcount++;
1110                                                         deselcount--;
1111                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
1112                                                                 return selcount;
1113                                                 }
1114                                         }
1115                                 }
1116                         } else if (mode==2) { /* face users */
1117                                 for(eve= em->verts.first; eve; eve= eve->next) {
1118                                         if (
1119                                                 !(eve->f & SELECT) &&
1120                                                 !eve->h &&
1121                                                 base_eve->tmp.l==eve->tmp.l
1122                                         ) {
1123                                                 eve->f |= SELECT;
1124                                                 selcount++;
1125                                                 deselcount--;
1126                                                 if (!deselcount) /*have we selected all posible faces?, if so return*/
1127                                                         return selcount;
1128                                         }
1129                                 }
1130                         } else if (mode==3 && base_eve->totweight != 0) { /* vertex groups */
1131                                 short i,j; /*weight index*/
1132                                 
1133                                 for(eve= em->verts.first; eve; eve= eve->next) {
1134                                         if (
1135                                                 !(eve->f & SELECT) &&
1136                                                 !eve->h &&
1137                                                 eve->totweight
1138                                         ) {
1139                                                 /* do the extra check for selection in the following if, so were not
1140                                                 checking verts that may be alredy selected */
1141                                                 for (i=0; base_eve->totweight >i && !(eve->f & SELECT); i++) { 
1142                                                         for (j=0; eve->totweight >j; j++) {
1143                                                                 if (base_eve->dw[i].def_nr==eve->dw[j].def_nr) {
1144                                                                         eve->f |= SELECT;
1145                                                                         selcount++;
1146                                                                         deselcount--;
1147                                                                         if (!deselcount) /*have we selected all posible faces?, if so return*/
1148                                                                                 return selcount;
1149                                                                         break;
1150                                                                 }
1151                                                         }
1152                                                 }
1153                                         }
1154                                 }
1155                         }
1156                 }
1157         } /* end basevert loop */
1158         return selcount;
1159 }
1160
1161 /* EditMode menu triggered from space.c by pressing Shift+G
1162 handles face/edge vert context and
1163 facegroup_select/edgegroup_select/vertgroup_select do all the work
1164 */
1165 void select_mesh_group_menu()
1166 {
1167         short ret;
1168         int selcount;
1169         
1170         if(G.scene->selectmode & SCE_SELECT_FACE) {
1171                 ret= pupmenu("Select Grouped Faces %t|Same Material %x1|Same Image %x2|Similar Area %x3|Similar Perimeter %x4|Similar Normal %x5|Similar Co-Planer %x6");
1172                 if (ret<1) return;
1173                 selcount= facegroup_select(ret);
1174                 
1175                 if (selcount) { /* update if data was selected */
1176                         G.totfacesel+=selcount;
1177                         allqueue(REDRAWVIEW3D, 0);
1178                         BIF_undo_push("Select Grouped Faces");
1179                 }
1180                 
1181         } else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1182                 ret= pupmenu("Select Grouped Edges%t|Similar Length %x1|Similar Direction %x2|Same Face Users%x3|Similar Adjacent Face Angle");
1183                 if (ret<1) return;
1184                 selcount= edgegroup_select(ret);
1185                 
1186                 if (selcount) { /* update if data was selected */
1187                         /*EM_select_flush();*/ /* dont use because it can end up selecting more edges and is not usefull*/
1188                         G.totedgesel+=selcount;
1189                         allqueue(REDRAWVIEW3D, 0);
1190                         BIF_undo_push("Select Grouped Edges");
1191                 }
1192                 
1193         } else if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1194                 ret= pupmenu("Select Grouped Verts%t|Similar Normal %x1|Same Face Users %x2|Shared Vertex Groups%x3");
1195                 if (ret<1) return;
1196                 selcount= vertgroup_select(ret);
1197                 
1198                 if (selcount) { /* update if data was selected */
1199                         EM_select_flush(); /* so that selected verts, go onto select faces */
1200                         G.totedgesel+=selcount;
1201                         allqueue(REDRAWVIEW3D, 0);
1202                         BIF_undo_push("Select Grouped Verts");
1203                 }
1204         }
1205         
1206 }
1207
1208
1209 /* ****************  LOOP SELECTS *************** */
1210
1211 /* selects quads in loop direction of indicated edge */
1212 /* only flush over edges with valence <= 2 */
1213 void faceloop_select(EditEdge *startedge, int select)
1214 {
1215         EditMesh *em = G.editMesh;
1216         EditEdge *eed;
1217         EditFace *efa;
1218         int looking= 1;
1219         
1220         /* in eed->f1 we put the valence (amount of faces in edge) */
1221         /* in eed->f2 we put tagged flag as correct loop */
1222         /* in efa->f1 we put tagged flag as correct to select */
1223
1224         for(eed= em->edges.first; eed; eed= eed->next) {
1225                 eed->f1= 0;
1226                 eed->f2= 0;
1227         }
1228         for(efa= em->faces.first; efa; efa= efa->next) {
1229                 efa->f1= 0;
1230                 if(efa->h==0) {
1231                         efa->e1->f1++;
1232                         efa->e2->f1++;
1233                         efa->e3->f1++;
1234                         if(efa->e4) efa->e4->f1++;
1235                 }
1236         }
1237         
1238         /* tag startedge OK*/
1239         startedge->f2= 1;
1240         
1241         while(looking) {
1242                 looking= 0;
1243                 
1244                 for(efa= em->faces.first; efa; efa= efa->next) {
1245                         if(efa->e4 && efa->f1==0) {     /* not done quad */
1246                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1247
1248                                         /* if edge tagged, select opposing edge and mark face ok */
1249                                         if(efa->e1->f2) {
1250                                                 efa->e3->f2= 1;
1251                                                 efa->f1= 1;
1252                                                 looking= 1;
1253                                         }
1254                                         else if(efa->e2->f2) {
1255                                                 efa->e4->f2= 1;
1256                                                 efa->f1= 1;
1257                                                 looking= 1;
1258                                         }
1259                                         if(efa->e3->f2) {
1260                                                 efa->e1->f2= 1;
1261                                                 efa->f1= 1;
1262                                                 looking= 1;
1263                                         }
1264                                         if(efa->e4->f2) {
1265                                                 efa->e2->f2= 1;
1266                                                 efa->f1= 1;
1267                                                 looking= 1;
1268                                         }
1269                                 }
1270                         }
1271                 }
1272         }
1273         
1274         /* (de)select the faces */
1275         if(select!=2) {
1276                 for(efa= em->faces.first; efa; efa= efa->next) {
1277                         if(efa->f1) EM_select_face(efa, select);
1278                 }
1279         }
1280 }
1281
1282
1283 /* helper for edgeloop_select, checks for eed->f2 tag in faces */
1284 static int edge_not_in_tagged_face(EditEdge *eed)
1285 {
1286         EditMesh *em = G.editMesh;
1287         EditFace *efa;
1288         
1289         for(efa= em->faces.first; efa; efa= efa->next) {
1290                 if(efa->h==0) {
1291                         if(efa->e1==eed || efa->e2==eed || efa->e3==eed || efa->e4==eed) {      /* edge is in face */
1292                                 if(efa->e1->f2 || efa->e2->f2 || efa->e3->f2 || (efa->e4 && efa->e4->f2)) {     /* face is tagged */
1293                                         return 0;
1294                                 }
1295                         }
1296                 }
1297         }
1298         return 1;
1299 }
1300
1301 /* selects or deselects edges that:
1302 - if edges has 2 faces:
1303         - has vertices with valence of 4
1304         - not shares face with previous edge
1305 - if edge has 1 face:
1306         - has vertices with valence 4
1307         - not shares face with previous edge
1308         - but also only 1 face
1309 - if edge no face:
1310         - has vertices with valence 2
1311 */
1312 static void edgeloop_select(EditEdge *starteed, int select)
1313 {
1314         EditMesh *em = G.editMesh;
1315         EditVert *eve;
1316         EditEdge *eed;
1317         EditFace *efa;
1318         int looking= 1;
1319         
1320         /* in f1 we put the valence (amount of edges in a vertex, or faces in edge) */
1321         /* in eed->f2 and efa->f1 we put tagged flag as correct loop */
1322         for(eve= em->verts.first; eve; eve= eve->next) {
1323                 eve->f1= 0;
1324                 eve->f2= 0;
1325         }
1326         for(eed= em->edges.first; eed; eed= eed->next) {
1327                 eed->f1= 0;
1328                 eed->f2= 0;
1329                 if((eed->h & 1)==0) {   /* fgon edges add to valence too */
1330                         eed->v1->f1++; eed->v2->f1++;
1331                 }
1332         }
1333         for(efa= em->faces.first; efa; efa= efa->next) {
1334                 efa->f1= 0;
1335                 if(efa->h==0) {
1336                         efa->e1->f1++;
1337                         efa->e2->f1++;
1338                         efa->e3->f1++;
1339                         if(efa->e4) efa->e4->f1++;
1340                 }
1341         }
1342         
1343         /* looped edges & vertices get tagged f2 */
1344         starteed->f2= 1;
1345         if(starteed->v1->f1<5) starteed->v1->f2= 1;
1346         if(starteed->v2->f1<5) starteed->v2->f2= 1;
1347         /* sorry, first edge isnt even ok */
1348         if(starteed->v1->f2==0 && starteed->v2->f2==0) looking= 0;
1349         
1350         while(looking) {
1351                 looking= 0;
1352                 
1353                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
1354                 for(eed= em->edges.first; eed; eed= eed->next) {
1355                         if(eed->h==0 && eed->f2==0) { /* edge not hidden, not tagged */
1356                                 if( (eed->v1->f1<5 && eed->v1->f2) || (eed->v2->f1<5 && eed->v2->f2)) { /* valence of vertex OK, and is tagged */
1357                                         /* new edge is not allowed to be in face with tagged edge */
1358                                         if(edge_not_in_tagged_face(eed)) {
1359                                                 if(eed->f1==starteed->f1) {     /* same amount of faces */
1360                                                         looking= 1;
1361                                                         eed->f2= 1;
1362                                                         if(eed->v2->f1<5) eed->v2->f2= 1;
1363                                                         if(eed->v1->f1<5) eed->v1->f2= 1;
1364                                                 }
1365                                         }
1366                                 }
1367                         }
1368                 }
1369         }
1370         /* and we do the select */
1371         for(eed= em->edges.first; eed; eed= eed->next) {
1372                 if(eed->f2) EM_select_edge(eed, select);
1373         }
1374 }
1375
1376 /* 
1377    Almostly exactly the same code as faceloop select
1378 */
1379 static void edgering_select(EditEdge *startedge, int select){
1380         EditMesh *em = G.editMesh;
1381         EditEdge *eed;
1382         EditFace *efa;
1383         int looking= 1;
1384         
1385         /* in eed->f1 we put the valence (amount of faces in edge) */
1386         /* in eed->f2 we put tagged flag as correct loop */
1387         /* in efa->f1 we put tagged flag as correct to select */
1388
1389         for(eed= em->edges.first; eed; eed= eed->next) {
1390                 eed->f1= 0;
1391                 eed->f2= 0;
1392         }
1393         for(efa= em->faces.first; efa; efa= efa->next) {
1394                 efa->f1= 0;
1395                 if(efa->h==0) {
1396                         efa->e1->f1++;
1397                         efa->e2->f1++;
1398                         efa->e3->f1++;
1399                         if(efa->e4) efa->e4->f1++;
1400                 }
1401         }
1402         
1403         /* tag startedge OK */
1404         startedge->f2= 1;
1405         
1406         while(looking) {
1407                 looking= 0;
1408                 
1409                 for(efa= em->faces.first; efa; efa= efa->next) {
1410                         if(efa->e4 && efa->f1==0 && !efa->h) {  /* not done quad */
1411                                 if(efa->e1->f1<=2 && efa->e2->f1<=2 && efa->e3->f1<=2 && efa->e4->f1<=2) { /* valence ok */
1412
1413                                         /* if edge tagged, select opposing edge and mark face ok */
1414                                         if(efa->e1->f2) {
1415                                                 efa->e3->f2= 1;
1416                                                 efa->f1= 1;
1417                                                 looking= 1;
1418                                         }
1419                                         else if(efa->e2->f2) {
1420                                                 efa->e4->f2= 1;
1421                                                 efa->f1= 1;
1422                                                 looking= 1;
1423                                         }
1424                                         if(efa->e3->f2) {
1425                                                 efa->e1->f2= 1;
1426                                                 efa->f1= 1;
1427                                                 looking= 1;
1428                                         }
1429                                         if(efa->e4->f2) {
1430                                                 efa->e2->f2= 1;
1431                                                 efa->f1= 1;
1432                                                 looking= 1;
1433                                         }
1434                                 }
1435                         }
1436                 }
1437         }
1438         
1439         /* (de)select the edges */
1440         for(eed= em->edges.first; eed; eed= eed->next) {
1441                 if(eed->f2) EM_select_edge(eed, select);
1442         }
1443 }
1444
1445 void loop_multiselect(int looptype)
1446 {
1447         EditEdge *eed;
1448         EditEdge **edarray;
1449         int edindex, edfirstcount;
1450         
1451         /*edarray = MEM_mallocN(sizeof(*edarray)*G.totedgesel,"edge array");*/
1452         edarray = MEM_mallocN(sizeof(EditEdge*)*G.totedgesel,"edge array");
1453         edindex = 0;
1454         edfirstcount = G.totedgesel;
1455         
1456         for(eed=G.editMesh->edges.first; eed; eed=eed->next){
1457                 if(eed->f&SELECT){
1458                         edarray[edindex] = eed;
1459                         edindex += 1;
1460                 }
1461         }
1462         
1463         if(looptype){
1464                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
1465                         eed = edarray[edindex];
1466                         edgering_select(eed,SELECT);
1467                 }
1468                 countall();
1469                 EM_selectmode_flush();
1470                 BIF_undo_push("Edge Ring Multi-Select");
1471         }
1472         else{
1473                 for(edindex = 0; edindex < edfirstcount; edindex +=1){
1474                         eed = edarray[edindex];
1475                         edgeloop_select(eed,SELECT);
1476                 }
1477                 countall();
1478                 EM_selectmode_flush();
1479                 BIF_undo_push("Edge Loop Multi-Select");
1480         }
1481         MEM_freeN(edarray);
1482         allqueue(REDRAWVIEW3D,0);
1483 }
1484                 
1485 /* ***************** MAIN MOUSE SELECTION ************** */
1486
1487 /* just to have the functions nice together */
1488 static void mouse_mesh_loop(void)
1489 {
1490         EditEdge *eed;
1491         int select;
1492         short dist= 50;
1493         
1494         eed= findnearestedge(&dist);
1495         if(eed) {
1496                 
1497                 if((G.qual & LR_SHIFTKEY)==0) EM_clear_flag_all(SELECT);
1498                 
1499                 if((eed->f & SELECT)==0) select=1;
1500                 else if(G.qual & LR_SHIFTKEY) select=0;
1501
1502                 if(G.scene->selectmode & SCE_SELECT_FACE) {
1503                         faceloop_select(eed, select);
1504                 }
1505                 else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1506             if(G.qual == (LR_CTRLKEY | LR_ALTKEY) || G.qual == (LR_CTRLKEY | LR_ALTKEY |LR_SHIFTKEY))
1507                         edgering_select(eed, select);
1508             else if(G.qual & LR_ALTKEY)
1509                         edgeloop_select(eed, select);
1510                 }
1511         else if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1512             if(G.qual == (LR_CTRLKEY | LR_ALTKEY) || G.qual == (LR_CTRLKEY | LR_ALTKEY |LR_SHIFTKEY))
1513                         edgering_select(eed, select);
1514             else if(G.qual & LR_ALTKEY)
1515                         edgeloop_select(eed, select);
1516                 }
1517
1518                 /* frontbuffer draw of last selected only */
1519                 unified_select_draw(NULL, eed, NULL);
1520                 
1521                 EM_selectmode_flush();
1522                 countall();
1523                 
1524                 allqueue(REDRAWVIEW3D, 0);
1525         }
1526 }
1527
1528
1529 /* here actual select happens */
1530 void mouse_mesh(void)
1531 {
1532         EditVert *eve;
1533         EditEdge *eed;
1534         EditFace *efa;
1535         
1536         if(G.qual & LR_ALTKEY) mouse_mesh_loop();
1537         else if(unified_findnearest(&eve, &eed, &efa)) {
1538                 
1539                 if((G.qual & LR_SHIFTKEY)==0) EM_clear_flag_all(SELECT);
1540                 
1541                 if(efa) {
1542                         
1543                         if( (efa->f & SELECT)==0 ) {
1544                                 EM_store_selection(efa, EDITFACE);
1545                                 EM_select_face_fgon(efa, 1);
1546                         }
1547                         else if(G.qual & LR_SHIFTKEY) {
1548                                 EM_remove_selection(efa, EDITFACE);
1549                                 EM_select_face_fgon(efa, 0);
1550                         }
1551                 }
1552                 else if(eed) {
1553                         if((eed->f & SELECT)==0) {
1554                                 EM_store_selection(eed, EDITEDGE);
1555                                 EM_select_edge(eed, 1);
1556                         }
1557                         else if(G.qual & LR_SHIFTKEY) {
1558                                 EM_remove_selection(eed, EDITEDGE);
1559                                 EM_select_edge(eed, 0);
1560                         }
1561                 }
1562                 else if(eve) {
1563                         if((eve->f & SELECT)==0) {
1564                                 eve->f |= SELECT;
1565                                 EM_store_selection(eve, EDITVERT);
1566                         }
1567                         else if(G.qual & LR_SHIFTKEY){ 
1568                                 EM_remove_selection(eve, EDITVERT);
1569                                 eve->f &= ~SELECT;
1570                         }
1571                 }
1572                 
1573                 /* frontbuffer draw of last selected only */
1574                 unified_select_draw(eve, eed, efa);
1575         
1576                 EM_selectmode_flush();
1577                 countall();
1578
1579                 allqueue(REDRAWVIEW3D, 0);
1580         }
1581
1582         rightmouse_transform();
1583 }
1584
1585
1586 static void selectconnectedAll(void)
1587 {
1588         EditMesh *em = G.editMesh;
1589         EditVert *v1,*v2;
1590         EditEdge *eed;
1591         short done=1, toggle=0;
1592
1593         if(em->edges.first==0) return;
1594         
1595         while(done==1) {
1596                 done= 0;
1597                 
1598                 toggle++;
1599                 if(toggle & 1) eed= em->edges.first;
1600                 else eed= em->edges.last;
1601                 
1602                 while(eed) {
1603                         v1= eed->v1;
1604                         v2= eed->v2;
1605                         if(eed->h==0) {
1606                                 if(v1->f & SELECT) {
1607                                         if( (v2->f & SELECT)==0 ) {
1608                                                 v2->f |= SELECT;
1609                                                 done= 1;
1610                                         }
1611                                 }
1612                                 else if(v2->f & SELECT) {
1613                                         if( (v1->f & SELECT)==0 ) {
1614                                                 v1->f |= SELECT;
1615                                                 done= 1;
1616                                         }
1617                                 }
1618                         }
1619                         if(toggle & 1) eed= eed->next;
1620                         else eed= eed->prev;
1621                 }
1622         }
1623
1624         /* now use vertex select flag to select rest */
1625         EM_select_flush();
1626         
1627         countall();
1628
1629         allqueue(REDRAWVIEW3D, 0);
1630         BIF_undo_push("Select Connected (All)");
1631 }
1632
1633 void selectconnected_mesh(int qual)
1634 {
1635         EditMesh *em = G.editMesh;
1636         EditVert *eve, *v1, *v2;
1637         EditEdge *eed;
1638         EditFace *efa;
1639         short done=1, sel, toggle=0;
1640
1641         if(em->edges.first==0) return;
1642
1643         if(qual & LR_CTRLKEY) {
1644                 selectconnectedAll();
1645                 return;
1646         }
1647
1648         
1649         if( unified_findnearest(&eve, &eed, &efa)==0 ) {
1650                 error("Nothing indicated ");
1651                 return;
1652         }
1653         
1654         sel= 1;
1655         if(qual & LR_SHIFTKEY) sel=0;
1656
1657         /* clear test flags */
1658         for(v1= em->verts.first; v1; v1= v1->next) v1->f1= 0;
1659         
1660         /* start vertex/face/edge */
1661         if(eve) eve->f1= 1;
1662         else if(eed) eed->v1->f1= eed->v2->f1= 1;
1663         else efa->v1->f1= efa->v2->f1= efa->v3->f1= 1;
1664         
1665         /* set flag f1 if affected */
1666         while(done==1) {
1667                 done= 0;
1668                 toggle++;
1669                 
1670                 if(toggle & 1) eed= em->edges.first;
1671                 else eed= em->edges.last;
1672                 
1673                 while(eed) {
1674                         v1= eed->v1;
1675                         v2= eed->v2;
1676                         
1677                         if(eed->h==0) {
1678                                 if(v1->f1 && v2->f1==0) {
1679                                         v2->f1= 1;
1680                                         done= 1;
1681                                 }
1682                                 else if(v1->f1==0 && v2->f1) {
1683                                         v1->f1= 1;
1684                                         done= 1;
1685                                 }
1686                         }
1687                         
1688                         if(toggle & 1) eed= eed->next;
1689                         else eed= eed->prev;
1690                 }
1691         }
1692         
1693         /* now use vertex f1 flag to select/deselect */
1694         for(eed= em->edges.first; eed; eed= eed->next) {
1695                 if(eed->v1->f1 && eed->v2->f1) 
1696                         EM_select_edge(eed, sel);
1697         }
1698         for(efa= em->faces.first; efa; efa= efa->next) {
1699                 if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
1700                         EM_select_face(efa, sel);
1701         }
1702         /* no flush needed, connected geometry is done */
1703         
1704         countall();
1705         
1706         allqueue(REDRAWVIEW3D, 0);
1707         BIF_undo_push("Select Linked");
1708         
1709 }
1710
1711 /* swap is 0 or 1, if 1 it hides not selected */
1712 void hide_mesh(int swap)
1713 {
1714         EditMesh *em = G.editMesh;
1715         EditVert *eve;
1716         EditEdge *eed;
1717         EditFace *efa;
1718         int a;
1719         
1720         if(G.obedit==0) return;
1721
1722         /* hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
1723         /*  - vertex hidden, always means edge is hidden too
1724                 - edge hidden, always means face is hidden too
1725                 - face hidden, only set face hide
1726                 - then only flush back down what's absolute hidden
1727         */
1728         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
1729                 for(eve= em->verts.first; eve; eve= eve->next) {
1730                         if((eve->f & SELECT)!=swap) {
1731                                 eve->f &= ~SELECT;
1732                                 eve->h= 1;
1733                         }
1734                 }
1735         
1736                 for(eed= em->edges.first; eed; eed= eed->next) {
1737                         if(eed->v1->h || eed->v2->h) {
1738                                 eed->h |= 1;
1739                                 eed->f &= ~SELECT;
1740                         }
1741                 }
1742         
1743                 for(efa= em->faces.first; efa; efa= efa->next) {
1744                         if(efa->e1->h || efa->e2->h || efa->e3->h || (efa->e4 && efa->e4->h)) {
1745                                 efa->h= 1;
1746                                 efa->f &= ~SELECT;
1747                         }
1748                 }
1749         }
1750         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
1751
1752                 for(eed= em->edges.first; eed; eed= eed->next) {
1753                         if((eed->f & SELECT)!=swap) {
1754                                 eed->h |= 1;
1755                                 EM_select_edge(eed, 0);
1756                         }
1757                 }
1758
1759                 for(efa= em->faces.first; efa; efa= efa->next) {
1760                         if(efa->e1->h || efa->e2->h || efa->e3->h || (efa->e4 && efa->e4->h)) {
1761                                 efa->h= 1;
1762                                 efa->f &= ~SELECT;
1763                         }
1764                 }
1765         }
1766         else {
1767
1768                 for(efa= em->faces.first; efa; efa= efa->next) {
1769                         if((efa->f & SELECT)!=swap) {
1770                                 efa->h= 1;
1771                                 EM_select_face(efa, 0);
1772                         }
1773                 }
1774         }
1775         
1776         /* flush down, only whats 100% hidden */
1777         for(eve= em->verts.first; eve; eve= eve->next) eve->f1= 0;
1778         for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
1779         
1780         if(G.scene->selectmode & SCE_SELECT_FACE) {
1781                 for(efa= em->faces.first; efa; efa= efa->next) {
1782                         if(efa->h) a= 1; else a= 2;
1783                         efa->e1->f1 |= a;
1784                         efa->e2->f1 |= a;
1785                         efa->e3->f1 |= a;
1786                         if(efa->e4) efa->e4->f1 |= a;
1787                 }
1788         }
1789         
1790         if(G.scene->selectmode >= SCE_SELECT_EDGE) {
1791                 for(eed= em->edges.first; eed; eed= eed->next) {
1792                         if(eed->f1==1) eed->h |= 1;
1793                         if(eed->h & 1) a= 1; else a= 2;
1794                         eed->v1->f1 |= a;
1795                         eed->v2->f1 |= a;
1796                 }
1797         }
1798
1799         if(G.scene->selectmode >= SCE_SELECT_VERTEX) {
1800                 for(eve= em->verts.first; eve; eve= eve->next) {
1801                         if(eve->f1==1) eve->h= 1;
1802                 }
1803         }
1804         
1805         G.totedgesel= G.totfacesel= G.totvertsel= 0;
1806         allqueue(REDRAWVIEW3D, 0);
1807         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1808         BIF_undo_push("Hide");
1809 }
1810
1811
1812 void reveal_mesh(void)
1813 {
1814         EditMesh *em = G.editMesh;
1815         EditVert *eve;
1816         EditEdge *eed;
1817         EditFace *efa;
1818         
1819         if(G.obedit==0) return;
1820
1821         for(eve= em->verts.first; eve; eve= eve->next) {
1822                 if(eve->h) {
1823                         eve->h= 0;
1824                         eve->f |= SELECT;
1825                 }
1826         }
1827         for(eed= em->edges.first; eed; eed= eed->next) {
1828                 if(eed->h & 1) {
1829                         eed->h &= ~1;
1830                         if(G.scene->selectmode & SCE_SELECT_VERTEX); 
1831                         else EM_select_edge(eed, 1);
1832                 }
1833         }
1834         for(efa= em->faces.first; efa; efa= efa->next) {
1835                 if(efa->h) {
1836                         efa->h= 0;
1837                         if(G.scene->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)); 
1838                         else EM_select_face(efa, 1);
1839                 }
1840         }
1841
1842         EM_fgon_flags();        /* redo flags and indices for fgons */
1843         EM_selectmode_flush();
1844         countall();
1845
1846         allqueue(REDRAWVIEW3D, 0);
1847         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1848         BIF_undo_push("Reveal");
1849 }
1850
1851 void select_faces_by_numverts(int numverts)
1852 {
1853         EditMesh *em = G.editMesh;
1854         EditFace *efa;
1855
1856         /* Selects isolated verts, and edges that do not have 2 neighboring
1857          * faces
1858          */
1859         
1860         if(G.scene->selectmode!=SCE_SELECT_FACE) {
1861                 error("Only works in face selection mode");
1862                 return;
1863         }
1864
1865         efa= em->faces.first;
1866         while(efa) {
1867                 if (efa->e4) {
1868                         EM_select_face(efa, (numverts==4) );
1869                 }
1870                 else if (efa->e3) {
1871                         EM_select_face(efa, (numverts==3) );
1872                 }
1873                 else 
1874                         EM_select_face(efa, (numverts!=3) && (numverts!=4) );
1875                 efa= efa->next;
1876         }
1877
1878         countall();
1879         addqueue(curarea->win,  REDRAW, 0);
1880
1881         if (numverts==3)
1882                 BIF_undo_push("Select Triangles");
1883         else if (numverts==4)
1884                 BIF_undo_push("Select Quads");
1885         else
1886                 BIF_undo_push("Select non-Triangles/Quads");
1887 }
1888
1889 void select_sharp_edges(void)
1890 {
1891         /* Find edges that have exactly two neighboring faces,
1892          * check the angle between those faces, and if angle is
1893          * small enough, select the edge
1894          */
1895         EditMesh *em = G.editMesh;
1896         EditEdge *eed;
1897         EditFace *efa;
1898         EditFace **efa1;
1899         EditFace **efa2;
1900         long edgecount = 0, i;
1901         static short sharpness = 135;
1902         float fsharpness;
1903
1904         if(G.scene->selectmode==SCE_SELECT_FACE) {
1905                 error("Doesn't work in face selection mode");
1906                 return;
1907         }
1908
1909         if(button(&sharpness,0, 180,"Max Angle:")==0) return;
1910         /* if faces are at angle 'sharpness', then the face normals
1911          * are at angle 180.0 - 'sharpness' (convert to radians too)
1912          */
1913         fsharpness = ((180.0 - sharpness) * M_PI) / 180.0;
1914
1915         i=0;
1916         /* count edges, use tmp.l  */
1917         eed= em->edges.first;
1918         while(eed) {
1919                 edgecount++;
1920                 eed->tmp.l = i;
1921                 eed= eed->next;
1922                 ++i;
1923         }
1924
1925         /* for each edge, we want a pointer to two adjacent faces */
1926         efa1 = MEM_callocN(edgecount*sizeof(EditFace *), 
1927                                            "pairs of edit face pointers");
1928         efa2 = MEM_callocN(edgecount*sizeof(EditFace *), 
1929                                            "pairs of edit face pointers");
1930
1931 #define face_table_edge(eed) { \
1932                 i = eed->tmp.l; \
1933                 if (i != -1) { \
1934                         if (efa1[i]) { \
1935                                 if (efa2[i]) { \
1936                                         /* invalidate, edge has more than two neighbors */ \
1937                                         eed->tmp.l = -1; \
1938                                 } \
1939                                 else { \
1940                                         efa2[i] = efa; \
1941                                 } \
1942                         } \
1943                         else { \
1944                                 efa1[i] = efa; \
1945                         } \
1946                 } \
1947         }
1948
1949         /* find the adjacent faces of each edge, we want only two */
1950         efa= em->faces.first;
1951         while(efa) {
1952                 face_table_edge(efa->e1);
1953                 face_table_edge(efa->e2);
1954                 face_table_edge(efa->e3);
1955                 if (efa->e4) {
1956                         face_table_edge(efa->e4);
1957                 }
1958                 efa= efa->next;
1959         }
1960
1961 #undef face_table_edge
1962
1963         eed = em->edges.first;
1964         while(eed) {
1965                 i = eed->tmp.l;
1966                 if (i != -1) { 
1967                         /* edge has two or less neighboring faces */
1968                         if ( (efa1[i]) && (efa2[i]) ) { 
1969                                 /* edge has exactly two neighboring faces, check angle */
1970                                 float angle;
1971                                 angle = saacos(efa1[i]->n[0]*efa2[i]->n[0] +
1972                                                            efa1[i]->n[1]*efa2[i]->n[1] +
1973                                                            efa1[i]->n[2]*efa2[i]->n[2]);
1974                                 if (fabs(angle) >= fsharpness)
1975                                         EM_select_edge(eed, 1);
1976                         }
1977                 }
1978
1979                 eed= eed->next;
1980         }
1981
1982         MEM_freeN(efa1);
1983         MEM_freeN(efa2);
1984
1985         countall();
1986         addqueue(curarea->win,  REDRAW, 0);
1987         BIF_undo_push("Select Sharp Edges");
1988 }
1989
1990 void select_linked_flat_faces(void)
1991 {
1992         /* Find faces that are linked to selected faces that are 
1993          * relatively flat (angle between faces is higher than
1994          * specified angle)
1995          */
1996         EditMesh *em = G.editMesh;
1997         EditEdge *eed;
1998         EditFace *efa;
1999         EditFace **efa1;
2000         EditFace **efa2;
2001         long edgecount = 0, i, faceselcount=0, faceselcountold=0;
2002         static short sharpness = 135;
2003         float fsharpness;
2004
2005         if(G.scene->selectmode!=SCE_SELECT_FACE) {
2006                 error("Only works in face selection mode");
2007                 return;
2008         }
2009
2010         if(button(&sharpness,0, 180,"Min Angle:")==0) return;
2011         /* if faces are at angle 'sharpness', then the face normals
2012          * are at angle 180.0 - 'sharpness' (convert to radians too)
2013          */
2014         fsharpness = ((180.0 - sharpness) * M_PI) / 180.0;
2015
2016         i=0;
2017         /* count edges, use tmp.l */
2018         eed= em->edges.first;
2019         while(eed) {
2020                 edgecount++;
2021                 eed->tmp.l = i;
2022                 eed= eed->next;
2023                 ++i;
2024         }
2025
2026         /* for each edge, we want a pointer to two adjacent faces */
2027         efa1 = MEM_callocN(edgecount*sizeof(EditFace *), 
2028                                            "pairs of edit face pointers");
2029         efa2 = MEM_callocN(edgecount*sizeof(EditFace *), 
2030                                            "pairs of edit face pointers");
2031
2032 #define face_table_edge(eed) { \
2033                 i = eed->tmp.l; \
2034                 if (i != -1) { \
2035                         if (efa1[i]) { \
2036                                 if (efa2[i]) { \
2037                                         /* invalidate, edge has more than two neighbors */ \
2038                                         eed->tmp.l = -1; \
2039                                 } \
2040                                 else { \
2041                                         efa2[i] = efa; \
2042                                 } \
2043                         } \
2044                         else { \
2045                                 efa1[i] = efa; \
2046                         } \
2047                 } \
2048         }
2049
2050         /* find the adjacent faces of each edge, we want only two */
2051         efa= em->faces.first;
2052         while(efa) {
2053                 face_table_edge(efa->e1);
2054                 face_table_edge(efa->e2);
2055                 face_table_edge(efa->e3);
2056                 if (efa->e4) {
2057                         face_table_edge(efa->e4);
2058                 }
2059
2060                 /* while were at it, count the selected faces */
2061                 if (efa->f & SELECT) ++faceselcount;
2062
2063                 efa= efa->next;
2064         }
2065
2066 #undef face_table_edge
2067
2068         eed= em->edges.first;
2069         while(eed) {
2070                 i = eed->tmp.l;
2071                 if (i != -1) { 
2072                         /* edge has two or less neighboring faces */
2073                         if ( (efa1[i]) && (efa2[i]) ) { 
2074                                 /* edge has exactly two neighboring faces, check angle */
2075                                 float angle;
2076                                 angle = saacos(efa1[i]->n[0]*efa2[i]->n[0] +
2077                                                            efa1[i]->n[1]*efa2[i]->n[1] +
2078                                                            efa1[i]->n[2]*efa2[i]->n[2]);
2079                                 /* invalidate: edge too sharp */
2080                                 if (fabs(angle) >= fsharpness)
2081                                         eed->tmp.l = -1;
2082                         }
2083                         else {
2084                                 /* invalidate: less than two neighbors */
2085                                 eed->tmp.l = -1;
2086                         }
2087                 }
2088
2089                 eed= eed->next;
2090         }
2091
2092 #define select_flat_neighbor(eed) { \
2093                                 i = eed->tmp.l; \
2094                                 if (i!=-1) { \
2095                                         if (! (efa1[i]->f & SELECT) ) { \
2096                                                 EM_select_face(efa1[i], 1); \
2097                                                 ++faceselcount; \
2098                                         } \
2099                                         if (! (efa2[i]->f & SELECT) ) { \
2100                                                 EM_select_face(efa2[i], 1); \
2101                                                 ++faceselcount; \
2102                                         } \
2103                                 } \
2104         }
2105
2106         while (faceselcount != faceselcountold) {
2107                 faceselcountold = faceselcount;
2108
2109                 efa= em->faces.first;
2110                 while(efa) {
2111                         if (efa->f & SELECT) {
2112                                 select_flat_neighbor(efa->e1);
2113                                 select_flat_neighbor(efa->e2);
2114                                 select_flat_neighbor(efa->e3);
2115                                 if (efa->e4) {
2116                                         select_flat_neighbor(efa->e4);
2117                                 }
2118                         }
2119                         efa= efa->next;
2120                 }
2121         }
2122
2123 #undef select_flat_neighbor
2124
2125         MEM_freeN(efa1);
2126         MEM_freeN(efa2);
2127
2128         countall();
2129         addqueue(curarea->win,  REDRAW, 0);
2130         BIF_undo_push("Select Linked Flat Faces");
2131 }
2132
2133 void select_non_manifold(void)
2134 {
2135         EditMesh *em = G.editMesh;
2136         EditVert *eve;
2137         EditEdge *eed;
2138         EditFace *efa;
2139
2140         /* Selects isolated verts, and edges that do not have 2 neighboring
2141          * faces
2142          */
2143         
2144         if(G.scene->selectmode==SCE_SELECT_FACE) {
2145                 error("Doesn't work in face selection mode");
2146                 return;
2147         }
2148
2149         eve= em->verts.first;
2150         while(eve) {
2151                 /* this will count how many edges are connected
2152                  * to this vert */
2153                 eve->f1= 0;
2154                 eve= eve->next;
2155         }
2156
2157         eed= em->edges.first;
2158         while(eed) {
2159                 /* this will count how many faces are connected to
2160                  * this edge */
2161                 eed->f1= 0;
2162                 /* increase edge count for verts */
2163                 ++eed->v1->f1;
2164                 ++eed->v2->f1;
2165                 eed= eed->next;
2166         }
2167
2168         efa= em->faces.first;
2169         while(efa) {
2170                 /* increase face count for edges */
2171                 ++efa->e1->f1;
2172                 ++efa->e2->f1;
2173                 ++efa->e3->f1;
2174                 if (efa->e4)
2175                         ++efa->e4->f1;                  
2176                 efa= efa->next;
2177         }
2178
2179         /* select verts that are attached to an edge that does not
2180          * have 2 neighboring faces */
2181         eed= em->edges.first;
2182         while(eed) {
2183                 if (eed->h==0 && eed->f1 != 2) {
2184                         EM_select_edge(eed, 1);
2185                 }
2186                 eed= eed->next;
2187         }
2188
2189         /* select isolated verts */
2190         eve= em->verts.first;
2191         while(eve) {
2192                 if (eve->f1 == 0) {
2193                         if (!eve->h) eve->f |= SELECT;
2194                 }
2195                 eve= eve->next;
2196         }
2197
2198         countall();
2199         addqueue(curarea->win,  REDRAW, 0);
2200         BIF_undo_push("Select Non Manifold");
2201 }
2202
2203 void selectswap_mesh(void) /* UI level */
2204 {
2205         EditMesh *em = G.editMesh;
2206         EditVert *eve;
2207         EditEdge *eed;
2208         EditFace *efa;
2209         
2210         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
2211
2212                 for(eve= em->verts.first; eve; eve= eve->next) {
2213                         if(eve->h==0) {
2214                                 if(eve->f & SELECT) eve->f &= ~SELECT;
2215                                 else eve->f|= SELECT;
2216                         }
2217                 }
2218         }
2219         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
2220                 for(eed= em->edges.first; eed; eed= eed->next) {
2221                         if(eed->h==0) {
2222                                 EM_select_edge(eed, !(eed->f & SELECT));
2223                         }
2224                 }
2225         }
2226         else {
2227                 for(efa= em->faces.first; efa; efa= efa->next) {
2228                         if(efa->h==0) {
2229                                 EM_select_face(efa, !(efa->f & SELECT));
2230                         }
2231                 }
2232         }
2233
2234         EM_selectmode_flush();
2235         
2236         countall();
2237         allqueue(REDRAWVIEW3D, 0);
2238
2239         BIF_undo_push("Select Swap");
2240         
2241 }
2242
2243 void deselectall_mesh(void)      /* this toggles!!!, UI level */
2244 {
2245         
2246         if(G.obedit->lay & G.vd->lay) {
2247
2248                 if( EM_nvertices_selected() ) {
2249                         EM_clear_flag_all(SELECT);
2250                         BIF_undo_push("Deselect All");
2251                 }
2252                 else  {
2253                         EM_set_flag_all(SELECT);
2254                         BIF_undo_push("Select All");
2255                 }
2256                 
2257                 countall();
2258                 allqueue(REDRAWVIEW3D, 0);
2259         }
2260 }
2261
2262 void select_more(void)
2263 {
2264         EditMesh *em = G.editMesh;
2265         EditVert *eve;
2266         EditEdge *eed;
2267         EditFace *efa;
2268         
2269         for(eve= em->verts.first; eve; eve= eve->next) {
2270                 if(eve->f & SELECT) eve->f1= 1;
2271                 else eve->f1 = 0;
2272         }
2273         
2274         /* set f1 flags in vertices to select 'more' */
2275         for(eed= em->edges.first; eed; eed= eed->next) {
2276                 if(eed->h==0) {
2277                         if (eed->v1->f & SELECT)
2278                                 eed->v2->f1 = 1;
2279                         if (eed->v2->f & SELECT)
2280                                 eed->v1->f1 = 1;
2281                 }
2282         }
2283
2284         /* new selected edges, but not in facemode */
2285         if(G.scene->selectmode <= SCE_SELECT_EDGE) {
2286                 
2287                 for(eed= em->edges.first; eed; eed= eed->next) {
2288                         if(eed->h==0) {
2289                                 if(eed->v1->f1 && eed->v2->f1) EM_select_edge(eed, 1);
2290                         }
2291                 }
2292         }
2293         /* new selected faces */
2294         for(efa= em->faces.first; efa; efa= efa->next) {
2295                 if(efa->h==0) {
2296                         if(efa->v1->f1 && efa->v2->f1 && efa->v3->f1 && (efa->v4==NULL || efa->v4->f1)) 
2297                                 EM_select_face(efa, 1);
2298                 }
2299         }
2300
2301         countall();
2302         addqueue(curarea->win,  REDRAW, 0);
2303         BIF_undo_push("Select More");
2304 }
2305
2306 void select_less(void)
2307 {
2308         EditMesh *em = G.editMesh;
2309         EditEdge *eed;
2310         EditFace *efa;
2311
2312         if(G.scene->selectmode <= SCE_SELECT_EDGE) {
2313                 /* eed->f1 == 1:  edge with a selected and deselected vert */ 
2314
2315                 for(eed= em->edges.first; eed; eed= eed->next) {
2316                         eed->f1= 0;
2317                         if(eed->h==0) {
2318                                 
2319                                 if ( !(eed->v1->f & SELECT) && (eed->v2->f & SELECT) ) 
2320                                         eed->f1= 1;
2321                                 if ( (eed->v1->f & SELECT) && !(eed->v2->f & SELECT) ) 
2322                                         eed->f1= 1;
2323                         }
2324                 }
2325                 
2326                 /* deselect edges with flag set */
2327                 for(eed= em->edges.first; eed; eed= eed->next) {
2328                         if (eed->h==0 && eed->f1 == 1) {
2329                                 EM_select_edge(eed, 0);
2330                         }
2331                 }
2332                 EM_deselect_flush();
2333                 
2334         }
2335         else {
2336                 /* deselect faces with 1 or more deselect edges */
2337                 /* eed->f1 == mixed selection edge */
2338                 for(eed= em->edges.first; eed; eed= eed->next) eed->f1= 0;
2339
2340                 for(efa= em->faces.first; efa; efa= efa->next) {
2341                         if(efa->h==0) {
2342                                 if(efa->f & SELECT) {
2343                                         efa->e1->f1 |= 1;
2344                                         efa->e2->f1 |= 1;
2345                                         efa->e3->f1 |= 1;
2346                                         if(efa->e4) efa->e4->f1 |= 1;
2347                                 }
2348                                 else {
2349                                         efa->e1->f1 |= 2;
2350                                         efa->e2->f1 |= 2;
2351                                         efa->e3->f1 |= 2;
2352                                         if(efa->e4) efa->e4->f1 |= 2;
2353                                 }
2354                         }
2355                 }
2356                 for(efa= em->faces.first; efa; efa= efa->next) {
2357                         if(efa->h==0) {
2358                                 if(efa->e1->f1==3 || efa->e2->f1==3 || efa->e3->f1==3 || (efa->e4 && efa->e4->f1==3)) { 
2359                                         EM_select_face(efa, 0);
2360                                 }
2361                         }
2362                 }
2363                 EM_selectmode_flush();
2364                 
2365         }
2366         
2367         countall();
2368         BIF_undo_push("Select Less");
2369         allqueue(REDRAWVIEW3D, 0);
2370 }
2371
2372
2373 void selectrandom_mesh(void) /* randomly selects a user-set % of vertices/edges/faces */
2374 {
2375         EditMesh *em = G.editMesh;
2376         EditVert *eve;
2377         EditEdge *eed;
2378         EditFace *efa;
2379         short randfac = 50;
2380
2381         if(G.obedit==NULL || (G.obedit->lay & G.vd->lay)==0) return;
2382
2383         /* Get the percentage of vertices to randomly select as 'randfac' */
2384         if(button(&randfac,0, 100,"Percentage:")==0) return;
2385
2386         BLI_srand( BLI_rand() ); /* random seed */
2387         
2388         if(G.scene->selectmode & SCE_SELECT_VERTEX) {
2389                 for(eve= em->verts.first; eve; eve= eve->next) {
2390                         if(eve->h==0) {
2391                                 if ( (BLI_frand() * 100) < randfac) 
2392                                         eve->f |= SELECT;
2393                         }
2394                 }
2395                 EM_selectmode_flush();
2396                 countall();
2397                 BIF_undo_push("Select Random: Vertices");
2398         }
2399         else if(G.scene->selectmode & SCE_SELECT_EDGE) {
2400                 for(eed= em->edges.first; eed; eed= eed->next) {
2401                         if(eed->h==0) {
2402                                 if ( (BLI_frand() * 100) < randfac) 
2403                                         EM_select_edge(eed, 1);
2404                         }
2405                 }
2406                 EM_selectmode_flush();
2407                 countall();
2408                 BIF_undo_push("Select Random:Edges");
2409         }
2410         else {
2411                 for(efa= em->faces.first; efa; efa= efa->next) {
2412                         if(efa->h==0) {
2413                                 if ( (BLI_frand() * 100) < randfac) 
2414                                         EM_select_face(efa, 1);
2415                         }
2416                 }
2417                 
2418                 EM_selectmode_flush();
2419                 countall();
2420                 BIF_undo_push("Select Random:Faces");
2421         }
2422         allqueue(REDRAWVIEW3D, 0);
2423 }
2424
2425 void editmesh_select_by_material(int index) 
2426 {
2427         EditMesh *em = G.editMesh;
2428         EditFace *efa;
2429         
2430         for (efa=em->faces.first; efa; efa= efa->next) {
2431                 if (efa->mat_nr==index) {
2432                         EM_select_face(efa, 1);
2433                 }
2434         }
2435
2436         EM_selectmode_flush();
2437 }
2438
2439 void editmesh_deselect_by_material(int index) 
2440 {
2441         EditMesh *em = G.editMesh;
2442         EditFace *efa;
2443         
2444         for (efa=em->faces.first; efa; efa= efa->next) {
2445                 if (efa->mat_nr==index) {
2446                         EM_select_face(efa, 0);
2447                 }
2448         }
2449
2450         EM_selectmode_flush();
2451 }
2452
2453 void EM_selectmode_menu(void)
2454 {
2455         int val;
2456         
2457         if(G.scene->selectmode & SCE_SELECT_VERTEX) pupmenu_set_active(1);
2458         else if(G.scene->selectmode & SCE_SELECT_EDGE) pupmenu_set_active(2);
2459         else pupmenu_set_active(3);
2460         
2461         val= pupmenu("Select Mode%t|Vertices|Edges|Faces");
2462         
2463         
2464         if(val>0) {
2465                 if(val==1){ 
2466                         G.scene->selectmode= SCE_SELECT_VERTEX;
2467                         EM_selectmode_set();
2468                         countall(); 
2469                         BIF_undo_push("Selectmode Set: Vertex");
2470                         }
2471                 else if(val==2){
2472                         if((G.qual==LR_CTRLKEY)) EM_convertsel(G.scene->selectmode, SCE_SELECT_EDGE);
2473                         G.scene->selectmode= SCE_SELECT_EDGE;
2474                         EM_selectmode_set();
2475                         countall();
2476                         BIF_undo_push("Selectmode Set: Edge");
2477                 }
2478                 
2479                 else{
2480                         if((G.qual==LR_CTRLKEY)) EM_convertsel(G.scene->selectmode, SCE_SELECT_FACE);
2481                         G.scene->selectmode= SCE_SELECT_FACE;
2482                         EM_selectmode_set();
2483                         countall();
2484                         BIF_undo_push("Selectmode Set: Vertex");
2485                 }
2486                 
2487                 allqueue(REDRAWVIEW3D, 1);
2488         }
2489 }
2490
2491 /* ************************* SEAMS AND EDGES **************** */
2492
2493 void editmesh_mark_seam(int clear)
2494 {
2495         EditMesh *em= G.editMesh;
2496         EditEdge *eed;
2497
2498         /* auto-enable seams drawing */
2499         if(clear==0) {
2500                 if(!(G.f & G_DRAWSEAMS)) {
2501                         G.f |= G_DRAWSEAMS;
2502                         allqueue(REDRAWBUTSEDIT, 0);
2503                 }
2504         }
2505
2506         if(clear) {
2507                 eed= em->edges.first;
2508                 while(eed) {
2509                         if((eed->h==0) && (eed->f & SELECT)) {
2510                                 eed->seam = 0;
2511                         }
2512                         eed= eed->next;
2513                 }
2514                 BIF_undo_push("Mark Seam");
2515         }
2516         else {
2517                 eed= em->edges.first;
2518                 while(eed) {
2519                         if((eed->h==0) && (eed->f & SELECT)) {
2520                                 eed->seam = 1;
2521                         }
2522                         eed= eed->next;
2523                 }
2524                 BIF_undo_push("Clear Seam");
2525         }
2526
2527         allqueue(REDRAWVIEW3D, 0);
2528 }
2529
2530 void Edge_Menu() {
2531         short ret;
2532
2533         ret= pupmenu("Edge Specials%t|Mark Seam %x1|Clear Seam %x2|Rotate Edge CW%x3|Rotate Edge CCW%x4|Loopcut%x6|Edge Slide%x5|Edge Loop Select%x7|Edge Ring Select%x8|Loop to Region%x9|Region to Loop%x10");
2534
2535         switch(ret)
2536         {
2537         case 1:
2538                 editmesh_mark_seam(0);
2539                 break;
2540         case 2:
2541                 editmesh_mark_seam(1);
2542                 break;
2543         case 3:
2544                 edge_rotate_selected(2);
2545                 break;
2546         case 4:
2547                 edge_rotate_selected(1);
2548                 break;
2549         case 5:
2550                 EdgeSlide(0,0.0);
2551                 BIF_undo_push("EdgeSlide");
2552                 break;
2553         case 6:
2554                 CutEdgeloop(1);
2555                 BIF_undo_push("Loopcut New");
2556                 break;
2557         case 7:
2558                 loop_multiselect(0);
2559                 break;
2560         case 8:
2561                 loop_multiselect(1);
2562                 break;
2563         case 9:
2564                 loop_to_region();
2565                 break;
2566         case 10:
2567                 region_to_loop();
2568                 break;
2569         }
2570 }
2571
2572
2573 /* **************** NORMALS ************** */
2574
2575 void righthandfaces(int select) /* makes faces righthand turning */
2576 {
2577         EditMesh *em = G.editMesh;
2578         EditEdge *eed, *ed1, *ed2, *ed3, *ed4;
2579         EditFace *efa, *startvl;
2580         float maxx, nor[3], cent[3];
2581         int totsel, found, foundone, direct, turn, tria_nr;
2582
2583    /* based at a select-connected to witness loose objects */
2584
2585         /* count per edge the amount of faces */
2586
2587         /* find the ultimate left, front, upper face (not manhattan dist!!) */
2588         /* also evaluate both triangle cases in quad, since these can be non-flat */
2589
2590         /* put normal to the outside, and set the first direction flags in edges */
2591
2592         /* then check the object, and set directions / direction-flags: but only for edges with 1 or 2 faces */
2593         /* this is in fact the 'select connected' */
2594         
2595         /* in case (selected) faces were not done: start over with 'find the ultimate ...' */
2596
2597         waitcursor(1);
2598         
2599         eed= em->edges.first;
2600         while(eed) {
2601                 eed->f2= 0;             /* edge direction */
2602                 eed->f1= 0;             /* counter */
2603                 eed= eed->next;
2604         }
2605
2606         /* count faces and edges */
2607         totsel= 0;
2608         efa= em->faces.first;
2609         while(efa) {
2610                 if(select==0 || (efa->f & SELECT) ) {
2611                         efa->f1= 1;
2612                         totsel++;
2613                         efa->e1->f1++;
2614                         efa->e2->f1++;
2615                         efa->e3->f1++;
2616                         if(efa->v4) efa->e4->f1++;
2617                 }
2618                 else efa->f1= 0;
2619
2620                 efa= efa->next;
2621         }
2622
2623         while(totsel>0) {
2624                 /* from the outside to the inside */
2625
2626                 efa= em->faces.first;
2627                 startvl= NULL;
2628                 maxx= -1.0e10;
2629                 tria_nr= 0;
2630
2631                 while(efa) {
2632                         if(efa->f1) {
2633                                 CalcCent3f(cent, efa->v1->co, efa->v2->co, efa->v3->co);
2634                                 cent[0]= cent[0]*cent[0] + cent[1]*cent[1] + cent[2]*cent[2];
2635                                 
2636                                 if(cent[0]>maxx) {
2637                                         maxx= cent[0];
2638                                         startvl= efa;
2639                                         tria_nr= 0;
2640                                 }
2641                                 if(efa->v4) {
2642                                         CalcCent3f(cent, efa->v1->co, efa->v3->co, efa->v4->co);
2643                                         cent[0]= cent[0]*cent[0] + cent[1]*cent[1] + cent[2]*cent[2];
2644                                         
2645                                         if(cent[0]>maxx) {
2646                                                 maxx= cent[0];
2647                                                 startvl= efa;
2648                                                 tria_nr= 1;
2649                                         }
2650                                 }
2651                         }
2652                         efa= efa->next;
2653                 }
2654                 
2655                 /* set first face correct: calc normal */
2656                 
2657                 if(tria_nr==1) {
2658                         CalcNormFloat(startvl->v1->co, startvl->v3->co, startvl->v4->co, nor);
2659                         CalcCent3f(cent, startvl->v1->co, startvl->v3->co, startvl->v4->co);
2660                 } else {
2661                         CalcNormFloat(startvl->v1->co, startvl->v2->co, startvl->v3->co, nor);
2662                         CalcCent3f(cent, startvl->v1->co, startvl->v2->co, startvl->v3->co);
2663                 }
2664                 /* first normal is oriented this way or the other */
2665                 if(select) {
2666                         if(select==2) {
2667                                 if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] > 0.0) flipface(startvl);
2668                         }
2669                         else {
2670                                 if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] < 0.0) flipface(startvl);
2671                         }
2672                 }
2673                 else if(cent[0]*nor[0]+cent[1]*nor[1]+cent[2]*nor[2] < 0.0) flipface(startvl);
2674
2675
2676                 eed= startvl->e1;
2677                 if(eed->v1==startvl->v1) eed->f2= 1; 
2678                 else eed->f2= 2;
2679                 
2680                 eed= startvl->e2;
2681                 if(eed->v1==startvl->v2) eed->f2= 1; 
2682                 else eed->f2= 2;
2683                 
2684                 eed= startvl->e3;
2685                 if(eed->v1==startvl->v3) eed->f2= 1; 
2686                 else eed->f2= 2;
2687                 
2688                 eed= startvl->e4;
2689                 if(eed) {
2690                         if(eed->v1==startvl->v4) eed->f2= 1; 
2691                         else eed->f2= 2;
2692                 }
2693                 
2694                 startvl->f1= 0;
2695                 totsel--;
2696
2697                 /* test normals */
2698                 found= 1;
2699                 direct= 1;
2700                 while(found) {
2701                         found= 0;
2702                         if(direct) efa= em->faces.first;
2703                         else efa= em->faces.last;
2704                         while(efa) {
2705                                 if(efa->f1) {
2706                                         turn= 0;
2707                                         foundone= 0;
2708
2709                                         ed1= efa->e1;
2710                                         ed2= efa->e2;
2711                                         ed3= efa->e3;
2712                                         ed4= efa->e4;
2713
2714                                         if(ed1->f2) {
2715                                                 if(ed1->v1==efa->v1 && ed1->f2==1) turn= 1;
2716                                                 if(ed1->v2==efa->v1 && ed1->f2==2) turn= 1;
2717                                                 foundone= 1;
2718                                         }
2719                                         else if(ed2->f2) {
2720                                                 if(ed2->v1==efa->v2 && ed2->f2==1) turn= 1;
2721                                                 if(ed2->v2==efa->v2 && ed2->f2==2) turn= 1;
2722                                                 foundone= 1;
2723                                         }
2724                                         else if(ed3->f2) {
2725                                                 if(ed3->v1==efa->v3 && ed3->f2==1) turn= 1;
2726                                                 if(ed3->v2==efa->v3 && ed3->f2==2) turn= 1;
2727                                                 foundone= 1;
2728                                         }
2729                                         else if(ed4 && ed4->f2) {
2730                                                 if(ed4->v1==efa->v4 && ed4->f2==1) turn= 1;
2731                                                 if(ed4->v2==efa->v4 && ed4->f2==2) turn= 1;
2732                                                 foundone= 1;
2733                                         }
2734
2735                                         if(foundone) {
2736                                                 found= 1;
2737                                                 totsel--;
2738                                                 efa->f1= 0;
2739
2740                                                 if(turn) {
2741                                                         if(ed1->v1==efa->v1) ed1->f2= 2; 
2742                                                         else ed1->f2= 1;
2743                                                         if(ed2->v1==efa->v2) ed2->f2= 2; 
2744                                                         else ed2->f2= 1;
2745                                                         if(ed3->v1==efa->v3) ed3->f2= 2; 
2746                                                         else ed3->f2= 1;
2747                                                         if(ed4) {
2748                                                                 if(ed4->v1==efa->v4) ed4->f2= 2; 
2749                                                                 else ed4->f2= 1;
2750                                                         }
2751
2752                                                         flipface(efa);
2753
2754                                                 }
2755                                                 else {
2756                                                         if(ed1->v1== efa->v1) ed1->f2= 1; 
2757                                                         else ed1->f2= 2;
2758                                                         if(ed2->v1==efa->v2) ed2->f2= 1; 
2759                                                         else ed2->f2= 2;
2760                                                         if(ed3->v1==efa->v3) ed3->f2= 1; 
2761                                                         else ed3->f2= 2;
2762                                                         if(ed4) {
2763                                                                 if(ed4->v1==efa->v4) ed4->f2= 1; 
2764                                                                 else ed4->f2= 2;
2765                                                         }
2766                                                 }
2767                                         }
2768                                 }
2769                                 if(direct) efa= efa->next;
2770                                 else efa= efa->prev;
2771                         }
2772                         direct= 1-direct;
2773                 }
2774         }
2775
2776         recalc_editnormals();
2777         
2778         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
2779         
2780         waitcursor(0);
2781 }
2782
2783
2784 /* ********** ALIGN WITH VIEW **************** */
2785
2786
2787 static void editmesh_calc_selvert_center(float cent_r[3])
2788 {
2789         EditMesh *em = G.editMesh;
2790         EditVert *eve;
2791         int nsel= 0;
2792
2793         cent_r[0]= cent_r[1]= cent_r[0]= 0.0;
2794
2795         for (eve= em->verts.first; eve; eve= eve->next) {
2796                 if (eve->f & SELECT) {
2797                         cent_r[0]+= eve->co[0];
2798                         cent_r[1]+= eve->co[1];
2799                         cent_r[2]+= eve->co[2];
2800                         nsel++;
2801                 }
2802         }
2803
2804         if (nsel) {
2805                 cent_r[0]/= nsel;
2806                 cent_r[1]/= nsel;
2807                 cent_r[2]/= nsel;
2808         }
2809 }
2810
2811 static int tface_is_selected(TFace *tf)
2812 {
2813         return (!(tf->flag & TF_HIDE) && (tf->flag & TF_SELECT));
2814 }
2815
2816 static int faceselect_nfaces_selected(Mesh *me)
2817 {
2818         int i, count= 0;
2819
2820         for (i=0; i<me->totface; i++)
2821                 if (tface_is_selected(&me->tface[i]))
2822                         count++;
2823
2824         return count;
2825 }
2826
2827         /* XXX, code for both these functions should be abstract,
2828          * then unified, then written for other things (like objects,
2829          * which would use same as vertices method), then added
2830          * to interface! Hoera! - zr
2831          */
2832 void faceselect_align_view_to_selected(View3D *v3d, Mesh *me, int axis)
2833 {
2834         if (!faceselect_nfaces_selected(me)) {
2835                 error("No faces selected.");
2836         } else {
2837                 float norm[3];
2838                 int i;
2839
2840                 norm[0]= norm[1]= norm[2]= 0.0;
2841                 for (i=0; i<me->totface; i++) {
2842                         MFace *mf= ((MFace*) me->mface) + i;
2843                         TFace *tf= ((TFace*) me->tface) + i;
2844         
2845                         if (tface_is_selected(tf)) {
2846                                 float *v1, *v2, *v3, fno[3];
2847
2848                                 v1= me->mvert[mf->v1].co;
2849                                 v2= me->mvert[mf->v2].co;
2850                                 v3= me->mvert[mf->v3].co;
2851                                 if (mf->v4) {
2852                                         float *v4= me->mvert[mf->v4].co;
2853                                         CalcNormFloat4(v1, v2, v3, v4, fno);
2854                                 } else {
2855                                         CalcNormFloat(v1, v2, v3, fno);
2856                                 }
2857
2858                                 norm[0]+= fno[0];
2859                                 norm[1]+= fno[1];
2860                                 norm[2]+= fno[2];
2861                         }
2862                 }
2863
2864                 view3d_align_axis_to_vector(v3d, axis, norm);
2865         }
2866 }
2867
2868 void editmesh_align_view_to_selected(View3D *v3d, int axis)
2869 {
2870         EditMesh *em = G.editMesh;
2871         int nselverts= EM_nvertices_selected();
2872         float norm[3]={0.0, 0.0, 0.0}; /* used for storing the mesh normal */
2873         
2874         if (nselverts==0) {
2875                 error("No faces or vertices selected.");
2876         } else if (EM_nfaces_selected()) {
2877                 EditFace *efa;
2878                 for (efa= em->faces.first; efa; efa= efa->next) {
2879                         if (faceselectedAND(efa, SELECT)) {
2880                                 float fno[3];
2881                                 if (efa->v4) CalcNormFloat4(efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co, fno);
2882                                 else CalcNormFloat(efa->v1->co, efa->v2->co, efa->v3->co, fno);
2883                                                 /* XXX, fixme, should be flipped intp a 
2884                                                  * consistent direction. -zr
2885                                                  */
2886                                 norm[0]+= fno[0];
2887                                 norm[1]+= fno[1];
2888                                 norm[2]+= fno[2];
2889                         }
2890                 }
2891
2892                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2893                 view3d_align_axis_to_vector(v3d, axis, norm);
2894         } else if (nselverts>2) {
2895                 float cent[3];
2896                 EditVert *eve, *leve= NULL;
2897
2898                 editmesh_calc_selvert_center(cent);
2899                 for (eve= em->verts.first; eve; eve= eve->next) {
2900                         if (eve->f & SELECT) {
2901                                 if (leve) {
2902                                         float tno[3];
2903                                         CalcNormFloat(cent, leve->co, eve->co, tno);
2904                                         
2905                                                 /* XXX, fixme, should be flipped intp a 
2906                                                  * consistent direction. -zr
2907                                                  */
2908                                         norm[0]+= tno[0];
2909                                         norm[1]+= tno[1];
2910                                         norm[2]+= tno[2];
2911                                 }
2912                                 leve= eve;
2913                         }
2914                 }
2915
2916                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2917                 view3d_align_axis_to_vector(v3d, axis, norm);
2918         } else if (nselverts==2) { /* Align view to edge (or 2 verts) */ 
2919                 EditVert *eve, *leve= NULL;
2920
2921                 for (eve= em->verts.first; eve; eve= eve->next) {
2922                         if (eve->f & SELECT) {
2923                                 if (leve) {
2924                                         norm[0]= leve->co[0] - eve->co[0];
2925                                         norm[1]= leve->co[1] - eve->co[1];
2926                                         norm[2]= leve->co[2] - eve->co[2];
2927                                         break; /* we know there are only 2 verts so no need to keep looking */
2928                                 }
2929                                 leve= eve;
2930                         }
2931                 }
2932                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2933                 view3d_align_axis_to_vector(v3d, axis, norm);
2934         } else if (nselverts==1) { /* Align view to vert normal */ 
2935                 EditVert *eve;
2936
2937                 for (eve= em->verts.first; eve; eve= eve->next) {
2938                         if (eve->f & SELECT) {
2939                                 norm[0]= eve->no[0];
2940                                 norm[1]= eve->no[1];
2941                                 norm[2]= eve->no[2];
2942                                 break; /* we know this is the only selected vert, so no need to keep looking */
2943                         }
2944                 }
2945                 Mat4Mul3Vecfl(G.obedit->obmat, norm);
2946                 view3d_align_axis_to_vector(v3d, axis, norm);
2947         }
2948
2949
2950 /* **************** VERTEX DEFORMS *************** */
2951
2952 void vertexsmooth(void)
2953 {
2954         EditMesh *em = G.editMesh;
2955         EditVert *eve;
2956         EditEdge *eed;
2957         float *adror, *adr, fac;
2958         float fvec[3];
2959         int teller=0;
2960         ModifierData *md= G.obedit->modifiers.first;
2961
2962         if(G.obedit==0) return;
2963
2964         /* count */
2965         eve= em->verts.first;
2966         while(eve) {
2967                 if(eve->f & SELECT) teller++;
2968                 eve= eve->next;
2969         }
2970         if(teller==0) return;
2971         
2972         adr=adror= (float *)MEM_callocN(3*sizeof(float *)*teller, "vertsmooth");
2973         eve= em->verts.first;
2974         while(eve) {
2975                 if(eve->f & SELECT) {
2976                         eve->tmp.fp = adr;
2977                         eve->f1= 0;
2978                         eve->f2= 0;
2979                         adr+= 3;
2980                 }
2981                 eve= eve->next;
2982         }
2983
2984         /* if there is a mirror modifier with clipping, flag the verts that
2985          * are within tolerance of the plane(s) of reflection 
2986          */
2987         for (; md; md=md->next) {
2988                 if (md->type==eModifierType_Mirror) {
2989                         MirrorModifierData *mmd = (MirrorModifierData*) md;     
2990                 
2991                         if(mmd->flag & MOD_MIR_CLIPPING) {
2992                                 for (eve= em->verts.first; eve; eve= eve->next) {
2993                                         if(eve->f & SELECT) {
2994
2995                                                 switch(mmd->axis){
2996                                                         case 0:
2997                                                                 if (fabs(eve->co[0]) < mmd->tolerance)
2998                                                                         eve->f2 |= 1;
2999                                                                 break;
3000                                                         case 1:
3001                                                                 if (fabs(eve->co[1]) < mmd->tolerance)
3002                                                                         eve->f2 |= 2;
3003                                                                 break;
3004                                                         case 2:
3005                                                                 if (fabs(eve->co[2]) < mmd->tolerance)
3006                                                                         eve->f2 |= 4;
3007                                                                 break;
3008                                                 }
3009                                         }
3010                                 }
3011                         }
3012                 }
3013         }
3014         
3015         eed= em->edges.first;
3016         while(eed) {
3017                 if( (eed->v1->f & SELECT) || (eed->v2->f & SELECT) ) {
3018                         fvec[0]= (eed->v1->co[0]+eed->v2->co[0])/2.0;
3019                         fvec[1]= (eed->v1->co[1]+eed->v2->co[1])/2.0;
3020                         fvec[2]= (eed->v1->co[2]+eed->v2->co[2])/2.0;
3021                         
3022                         if((eed->v1->f & SELECT) && eed->v1->f1<255) {
3023                                 eed->v1->f1++;
3024                                 VecAddf(eed->v1->tmp.fp, eed->v1->tmp.fp, fvec);
3025                         }
3026                         if((eed->v2->f & SELECT) && eed->v2->f1<255) {
3027                                 eed->v2->f1++;
3028                                 VecAddf(eed->v2->tmp.fp, eed->v2->tmp.fp, fvec);
3029                         }
3030                 }
3031                 eed= eed->next;
3032         }
3033
3034         eve= em->verts.first;
3035         while(eve) {
3036                 if(eve->f & SELECT) {
3037                         if(eve->f1) {
3038                                 adr = eve->tmp.fp;
3039                                 fac= 0.5/(float)eve->f1;
3040                                 
3041                                 eve->co[0]= 0.5*eve->co[0]+fac*adr[0];
3042                                 eve->co[1]= 0.5*eve->co[1]+fac*adr[1];
3043                                 eve->co[2]= 0.5*eve->co[2]+fac*adr[2];
3044
3045                                 /* clip if needed by mirror modifier */
3046                                 if (eve->f2) {
3047                                         if (eve->f2 & 1) {
3048                                                 eve->co[0]= 0.0f;
3049                                         }
3050                                         if (eve->f2 & 2) {
3051                                                 eve->co[1]= 0.0f;
3052                                         }
3053                                         if (eve->f2 & 4) {
3054                                                 eve->co[2]= 0.0f;
3055                                         }
3056                                 }
3057                         }
3058                         eve->tmp.fp= 0;