Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / uvedit / uvedit_ops.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Antony Riakiotakis.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/uvedit/uvedit_ops.c
29  *  \ingroup eduv
30  */
31
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_object_types.h"
41 #include "DNA_material_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_node_types.h"
45 #include "DNA_image_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BLI_utildefines.h"
50 #include "BLI_alloca.h"
51 #include "BLI_math.h"
52 #include "BLI_lasso.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_array.h"
55
56 #include "BLT_translation.h"
57
58 #include "BKE_context.h"
59 #include "BKE_customdata.h"
60 #include "BKE_image.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_material.h"
64 #include "BKE_mesh_mapping.h"
65 #include "BKE_node.h"
66 #include "BKE_report.h"
67 #include "BKE_scene.h"
68 #include "BKE_editmesh.h"
69
70 #include "DEG_depsgraph.h"
71
72 #include "ED_image.h"
73 #include "ED_mesh.h"
74 #include "ED_node.h"
75 #include "ED_uvedit.h"
76 #include "ED_object.h"
77 #include "ED_screen.h"
78 #include "ED_transform.h"
79
80 #include "RNA_access.h"
81 #include "RNA_define.h"
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "UI_interface.h"
87 #include "UI_resources.h"
88 #include "UI_view2d.h"
89
90 #include "uvedit_intern.h"
91
92 static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int action);
93 static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
94 static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
95
96 /************************* state testing ************************/
97
98 bool ED_uvedit_test(Object *obedit)
99 {
100         BMEditMesh *em;
101         int ret;
102
103         if (!obedit)
104                 return 0;
105         
106         if (obedit->type != OB_MESH)
107                 return 0;
108
109         em = BKE_editmesh_from_object(obedit);
110         ret = EDBM_uv_check(em);
111         
112         return ret;
113 }
114
115 static int ED_operator_uvedit_can_uv_sculpt(struct bContext *C)
116 {
117         SpaceImage *sima = CTX_wm_space_image(C);
118         ToolSettings *toolsettings = CTX_data_tool_settings(C);
119         Object *obedit = CTX_data_edit_object(C);
120
121         return ED_space_image_show_uvedit(sima, obedit) && !(toolsettings->use_uv_sculpt);
122 }
123
124 static int UNUSED_FUNCTION(ED_operator_uvmap_mesh) (bContext *C)
125 {
126         Object *ob = CTX_data_active_object(C);
127
128         if (ob && ob->type == OB_MESH) {
129                 Mesh *me = ob->data;
130
131                 if (CustomData_get_layer(&me->fdata, CD_MTFACE) != NULL)
132                         return 1;
133         }
134
135         return 0;
136 }
137 /**************************** object active image *****************************/
138
139 static bool is_image_texture_node(bNode *node)
140 {
141         return ELEM(node->type, SH_NODE_TEX_IMAGE, SH_NODE_TEX_ENVIRONMENT);
142 }
143
144 bool ED_object_get_active_image(Object *ob, int mat_nr,
145                                 Image **r_ima, ImageUser **r_iuser, bNode **r_node, bNodeTree **r_ntree)
146 {
147         Material *ma = give_current_material(ob, mat_nr);
148         bNodeTree *ntree = (ma && ma->use_nodes) ? ma->nodetree : NULL;
149         bNode *node = (ntree) ? nodeGetActiveTexture(ntree) : NULL;
150
151         if (node && is_image_texture_node(node)) {
152                 if (r_ima) *r_ima = (Image *)node->id;
153                 if (r_iuser) *r_iuser = NULL;
154                 if (r_node) *r_node = node;
155                 if (r_ntree) *r_ntree = ntree;
156                 return true;
157         }
158         
159         if (r_ima) *r_ima = NULL;
160         if (r_iuser) *r_iuser = NULL;
161         if (r_node) *r_node = node;
162         if (r_ntree) *r_ntree = ntree;
163
164         return false;
165 }
166
167 void ED_object_assign_active_image(Main *bmain, Object *ob, int mat_nr, Image *ima)
168 {
169         Material *ma = give_current_material(ob, mat_nr);
170         bNode *node = (ma && ma->use_nodes) ? nodeGetActiveTexture(ma->nodetree) : NULL;
171
172         if (node && is_image_texture_node(node)) {
173                 node->id = &ima->id;
174                 ED_node_tag_update_nodetree(bmain, ma->nodetree, node);
175         }
176 }
177
178 /************************* assign image ************************/
179
180 //#define USE_SWITCH_ASPECT
181
182 void ED_uvedit_assign_image(Main *UNUSED(bmain), Scene *scene, Object *obedit, Image *ima, Image *previma)
183 {
184         BMEditMesh *em;
185         BMIter iter;
186         bool update = false;
187         const bool selected = !(scene->toolsettings->uv_flag & UV_SYNC_SELECTION);
188         
189         /* skip assigning these procedural images... */
190         if (ima && (ima->type == IMA_TYPE_R_RESULT || ima->type == IMA_TYPE_COMPOSITE))
191                 return;
192
193         /* verify we have a mesh we can work with */
194         if (!obedit || (obedit->type != OB_MESH))
195                 return;
196
197         em = BKE_editmesh_from_object(obedit);
198         if (!em || !em->bm->totface) {
199                 return;
200         }
201
202         if (BKE_scene_use_new_shading_nodes(scene)) {
203                 /* new shading system, do not assign anything */
204         }
205         else {
206                 BMFace *efa;
207
208                 int cd_loop_uv_offset;
209                 /* old shading system, assign image to selected faces */
210 #ifdef USE_SWITCH_ASPECT
211                 float prev_aspect[2], fprev_aspect;
212                 float aspect[2], faspect;
213
214                 ED_image_get_uv_aspect(previma, prev_aspect, prev_aspect + 1);
215                 ED_image_get_uv_aspect(ima, aspect, aspect + 1);
216
217                 fprev_aspect = prev_aspect[0] / prev_aspect[1];
218                 faspect = aspect[0] / aspect[1];
219 #endif
220
221                 /* ensure we have a uv map */
222                 if (!CustomData_has_layer(&em->bm->ldata, CD_MLOOPUV)) {
223                         BM_data_layer_add(em->bm, &em->bm->ldata, CD_MLOOPUV);
224                         /* make UVs all nice 0-1 */
225                         ED_mesh_uv_loop_reset_ex(obedit->data, CustomData_get_active_layer(&em->bm->ldata, CD_MLOOPUV));
226                         update = true;
227                 }
228
229                 cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
230
231                 /* now assign to all visible faces */
232                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
233                         if (uvedit_face_visible_test(scene, previma, efa) &&
234                             (selected == true || uvedit_face_select_test(scene, efa, cd_loop_uv_offset)))
235                         {
236 #ifdef USE_SWITCH_ASPECT
237                                 if (ima) {
238                                         /* we also need to correct the aspect of uvs */
239                                         if (scene->toolsettings->uvcalc_flag & UVCALC_NO_ASPECT_CORRECT) {
240                                                 /* do nothing */
241                                         }
242                                         else {
243                                                 BMIter liter;
244                                                 BMLoop *l;
245
246                                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
247                                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
248
249                                                         luv->uv[0] *= fprev_aspect;
250                                                         luv->uv[0] /= faspect;
251                                                 }
252                                         }
253                                 }
254 #endif
255                                 BKE_object_material_edit_image_set(obedit, efa->mat_nr, ima);
256
257                                 update = true;
258                         }
259                 }
260
261                 /* and update depdency graph */
262                 if (update) {
263                         DEG_id_tag_update(obedit->data, 0);
264                 }
265         }
266
267 }
268
269 /*********************** space conversion *********************/
270
271 static void uvedit_pixel_to_float(SpaceImage *sima, float *dist, float pixeldist)
272 {
273         int width, height;
274
275         if (sima) {
276                 ED_space_image_get_size(sima, &width, &height);
277         }
278         else {
279                 width =  IMG_SIZE_FALLBACK;
280                 height = IMG_SIZE_FALLBACK;
281         }
282
283         dist[0] = pixeldist / width;
284         dist[1] = pixeldist / height;
285 }
286
287 /*************** visibility and selection utilities **************/
288
289 bool uvedit_face_visible_nolocal(Scene *scene, BMFace *efa)
290 {
291         ToolSettings *ts = scene->toolsettings;
292
293         if (ts->uv_flag & UV_SYNC_SELECTION)
294                 return (BM_elem_flag_test(efa, BM_ELEM_HIDDEN) == 0);
295         else
296                 return (BM_elem_flag_test(efa, BM_ELEM_HIDDEN) == 0 && BM_elem_flag_test(efa, BM_ELEM_SELECT));
297 }
298
299 bool uvedit_face_visible_test(Scene *scene, Image *ima, BMFace *efa)
300 {
301         ToolSettings *ts = scene->toolsettings;
302
303         if (ts->uv_flag & UV_SHOW_SAME_IMAGE) {
304                 const Image *face_image = BKE_object_material_edit_image_get(scene->obedit, efa->mat_nr);
305                 return (face_image == ima) ? uvedit_face_visible_nolocal(scene, efa) : false;
306         }
307         else {
308                 return uvedit_face_visible_nolocal(scene, efa);
309         }
310 }
311
312 bool uvedit_face_select_test(Scene *scene, BMFace *efa,
313                              const int cd_loop_uv_offset)
314 {
315         ToolSettings *ts = scene->toolsettings;
316         if (ts->uv_flag & UV_SYNC_SELECTION) {
317                 return (BM_elem_flag_test(efa, BM_ELEM_SELECT));
318         }
319         else {
320                 BMLoop *l;
321                 MLoopUV *luv;
322                 BMIter liter;
323
324                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
325                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
326                         if (!(luv->flag & MLOOPUV_VERTSEL))
327                                 return false;
328                 }
329
330                 return true;
331         }
332 }
333
334 bool uvedit_face_select_set(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
335                             const bool do_history, const int cd_loop_uv_offset)
336 {
337         if (select) {
338                 return uvedit_face_select_enable(scene, em, efa, do_history, cd_loop_uv_offset);
339         }
340         else {
341                 return uvedit_face_select_disable(scene, em, efa, cd_loop_uv_offset);
342         }
343 }
344
345 bool uvedit_face_select_enable(Scene *scene, BMEditMesh *em, BMFace *efa, const bool do_history,
346                                const int cd_loop_uv_offset)
347 {
348         ToolSettings *ts = scene->toolsettings;
349
350         if (ts->uv_flag & UV_SYNC_SELECTION) {
351                 BM_face_select_set(em->bm, efa, true);
352                 if (do_history) {
353                         BM_select_history_store(em->bm, (BMElem *)efa);
354                 }
355         }
356         else {
357                 BMLoop *l;
358                 MLoopUV *luv;
359                 BMIter liter;
360
361                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
362                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
363                         luv->flag |= MLOOPUV_VERTSEL;
364                 }
365
366                 return true;
367         }
368
369         return false;
370 }
371
372 bool uvedit_face_select_disable(Scene *scene, BMEditMesh *em, BMFace *efa,
373                                 const int cd_loop_uv_offset)
374 {
375         ToolSettings *ts = scene->toolsettings;
376
377         if (ts->uv_flag & UV_SYNC_SELECTION) {
378                 BM_face_select_set(em->bm, efa, false);
379         }
380         else {
381                 BMLoop *l;
382                 MLoopUV *luv;
383                 BMIter liter;
384
385                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
386                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
387                         luv->flag &= ~MLOOPUV_VERTSEL;
388                 }
389
390                 return true;
391         }
392
393         return false;
394 }
395
396 bool uvedit_edge_select_test(Scene *scene, BMLoop *l,
397                              const int cd_loop_uv_offset)
398 {
399         ToolSettings *ts = scene->toolsettings;
400
401         if (ts->uv_flag & UV_SYNC_SELECTION) {
402                 if (ts->selectmode & SCE_SELECT_FACE) {
403                         return BM_elem_flag_test(l->f, BM_ELEM_SELECT);
404                 }
405                 else if (ts->selectmode == SCE_SELECT_EDGE) {
406                         return BM_elem_flag_test(l->e, BM_ELEM_SELECT);
407                 }
408                 else {
409                         return BM_elem_flag_test(l->v, BM_ELEM_SELECT) && 
410                                BM_elem_flag_test(l->next->v, BM_ELEM_SELECT);
411                 }
412         }
413         else {
414                 MLoopUV *luv1, *luv2;
415
416                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
417                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
418
419                 return (luv1->flag & MLOOPUV_VERTSEL) && (luv2->flag & MLOOPUV_VERTSEL);
420         }
421 }
422
423 void uvedit_edge_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
424                             const bool do_history, const int cd_loop_uv_offset)
425
426 {
427         if (select) {
428                 uvedit_edge_select_enable(em, scene, l, do_history, cd_loop_uv_offset);
429         }
430         else {
431                 uvedit_edge_select_disable(em, scene, l, cd_loop_uv_offset);
432         }
433 }
434
435 void uvedit_edge_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l, const bool do_history,
436                                const int cd_loop_uv_offset)
437
438 {
439         ToolSettings *ts = scene->toolsettings;
440
441         if (ts->uv_flag & UV_SYNC_SELECTION) {
442                 if (ts->selectmode & SCE_SELECT_FACE)
443                         BM_face_select_set(em->bm, l->f, true);
444                 else if (ts->selectmode & SCE_SELECT_EDGE)
445                         BM_edge_select_set(em->bm, l->e, true);
446                 else {
447                         BM_vert_select_set(em->bm, l->e->v1, true);
448                         BM_vert_select_set(em->bm, l->e->v2, true);
449                 }
450
451                 if (do_history) {
452                         BM_select_history_store(em->bm, (BMElem *)l->e);
453                 }
454         }
455         else {
456                 MLoopUV *luv1, *luv2;
457
458                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
459                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
460                 
461                 luv1->flag |= MLOOPUV_VERTSEL;
462                 luv2->flag |= MLOOPUV_VERTSEL;
463         }
464 }
465
466 void uvedit_edge_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
467                                 const int cd_loop_uv_offset)
468
469 {
470         ToolSettings *ts = scene->toolsettings;
471
472         if (ts->uv_flag & UV_SYNC_SELECTION) {
473                 if (ts->selectmode & SCE_SELECT_FACE)
474                         BM_face_select_set(em->bm, l->f, false);
475                 else if (ts->selectmode & SCE_SELECT_EDGE)
476                         BM_edge_select_set(em->bm, l->e, false);
477                 else {
478                         BM_vert_select_set(em->bm, l->e->v1, false);
479                         BM_vert_select_set(em->bm, l->e->v2, false);
480                 }
481         }
482         else {
483                 MLoopUV *luv1, *luv2;
484
485                 luv1 = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
486                 luv2 = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
487                 
488                 luv1->flag &= ~MLOOPUV_VERTSEL;
489                 luv2->flag &= ~MLOOPUV_VERTSEL;
490         }
491 }
492
493 bool uvedit_uv_select_test(Scene *scene, BMLoop *l,
494                            const int cd_loop_uv_offset)
495 {
496         ToolSettings *ts = scene->toolsettings;
497
498         if (ts->uv_flag & UV_SYNC_SELECTION) {
499                 if (ts->selectmode & SCE_SELECT_FACE)
500                         return BM_elem_flag_test_bool(l->f, BM_ELEM_SELECT);
501                 else
502                         return BM_elem_flag_test_bool(l->v, BM_ELEM_SELECT);
503         }
504         else {
505                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
506                 return (luv->flag & MLOOPUV_VERTSEL) != 0;
507         }
508 }
509
510 void uvedit_uv_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
511                           const bool do_history, const int cd_loop_uv_offset)
512 {
513         if (select) {
514                 uvedit_uv_select_enable(em, scene, l, do_history, cd_loop_uv_offset);
515         }
516         else {
517                 uvedit_uv_select_disable(em, scene, l, cd_loop_uv_offset);
518         }
519 }
520
521 void uvedit_uv_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l,
522                              const bool do_history, const int cd_loop_uv_offset)
523 {
524         ToolSettings *ts = scene->toolsettings;
525
526         if (ts->uv_flag & UV_SYNC_SELECTION) {
527                 if (ts->selectmode & SCE_SELECT_FACE)
528                         BM_face_select_set(em->bm, l->f, true);
529                 else
530                         BM_vert_select_set(em->bm, l->v, true);
531
532                 if (do_history) {
533                         BM_select_history_remove(em->bm, (BMElem *)l->v);
534                 }
535         }
536         else {
537                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
538                 luv->flag |= MLOOPUV_VERTSEL;
539         }
540 }
541
542 void uvedit_uv_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
543                               const int cd_loop_uv_offset)
544 {
545         ToolSettings *ts = scene->toolsettings;
546
547         if (ts->uv_flag & UV_SYNC_SELECTION) {
548                 if (ts->selectmode & SCE_SELECT_FACE)
549                         BM_face_select_set(em->bm, l->f, false);
550                 else
551                         BM_vert_select_set(em->bm, l->v, false);
552         }
553         else {
554                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
555                 luv->flag &= ~MLOOPUV_VERTSEL;
556         }
557 }
558
559 /*********************** live unwrap utilities ***********************/
560
561 void uvedit_live_unwrap_update(SpaceImage *sima, Scene *scene, Object *obedit)
562 {
563         if (sima && (sima->flag & SI_LIVE_UNWRAP)) {
564                 ED_uvedit_live_unwrap_begin(scene, obedit);
565                 ED_uvedit_live_unwrap_re_solve();
566                 ED_uvedit_live_unwrap_end(0);
567         }
568 }
569
570 /*********************** geometric utilities ***********************/
571 void uv_poly_center(BMFace *f, float r_cent[2], const int cd_loop_uv_offset)
572 {
573         BMLoop *l;
574         MLoopUV *luv;
575         BMIter liter;
576
577         zero_v2(r_cent);
578
579         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
580                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
581                 add_v2_v2(r_cent, luv->uv);
582         }
583
584         mul_v2_fl(r_cent, 1.0f / (float)f->len);
585 }
586
587 void uv_poly_copy_aspect(float uv_orig[][2], float uv[][2], float aspx, float aspy, int len)
588 {
589         int i;
590         for (i = 0; i < len; i++) {
591                 uv[i][0] = uv_orig[i][0] * aspx;
592                 uv[i][1] = uv_orig[i][1] * aspy;
593         }
594 }
595
596 bool ED_uvedit_minmax(Scene *scene, Image *ima, Object *obedit, float r_min[2], float r_max[2])
597 {
598         BMEditMesh *em = BKE_editmesh_from_object(obedit);
599         BMFace *efa;
600         BMLoop *l;
601         BMIter iter, liter;
602         MLoopUV *luv;
603         bool changed = false;
604
605         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
606
607         INIT_MINMAX2(r_min, r_max);
608
609         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
610                 if (!uvedit_face_visible_test(scene, ima, efa))
611                         continue;
612                 
613                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
614                         if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
615                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
616                                 minmax_v2v2_v2(r_min, r_max, luv->uv);
617                                 changed = true;
618                         }
619                 }
620         }
621
622         return changed;
623 }
624
625 /* Be careful when using this, it bypasses all synchronization options */
626 void ED_uvedit_select_all(BMesh *bm)
627 {
628         BMFace *efa;
629         BMLoop *l;
630         BMIter iter, liter;
631         MLoopUV *luv;
632
633         const int cd_loop_uv_offset  = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
634
635         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
636                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
637                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
638                         luv->flag |= MLOOPUV_VERTSEL;
639                 }
640         }
641 }
642
643 static bool ED_uvedit_median(Scene *scene, Image *ima, Object *obedit, float co[2])
644 {
645         BMEditMesh *em = BKE_editmesh_from_object(obedit);
646         BMFace *efa;
647         BMLoop *l;
648         BMIter iter, liter;
649         MLoopUV *luv;
650         unsigned int sel = 0;
651
652         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
653
654         zero_v2(co);
655         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
656                 if (!uvedit_face_visible_test(scene, ima, efa))
657                         continue;
658                 
659                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
660                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
661                         if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
662                                 add_v2_v2(co, luv->uv);
663                                 sel++;
664                         }
665                 }
666         }
667
668         mul_v2_fl(co, 1.0f / (float)sel);
669
670         return (sel != 0);
671 }
672
673 bool ED_uvedit_center(Scene *scene, Image *ima, Object *obedit, float cent[2], char mode)
674 {
675         bool changed = false;
676         
677         if (mode == V3D_AROUND_CENTER_BOUNDS) {  /* bounding box */
678                 float min[2], max[2];
679                 if (ED_uvedit_minmax(scene, ima, obedit, min, max)) {
680                         mid_v2_v2v2(cent, min, max);
681                         changed = true;
682                 }
683         }
684         else {
685                 if (ED_uvedit_median(scene, ima, obedit, cent)) {
686                         changed = true;
687                 }
688         }
689
690         return changed;
691 }
692
693 /************************** find nearest ****************************/
694
695 void uv_find_nearest_edge(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
696 {
697         BMFace *efa;
698         BMLoop *l;
699         BMIter iter, liter;
700         MLoopUV *luv, *luv_next;
701         float mindist_squared, dist_squared;
702         int i;
703
704         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
705
706         mindist_squared = 1e10f;
707         memset(hit, 0, sizeof(*hit));
708
709         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
710         
711         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
712                 if (!uvedit_face_visible_test(scene, ima, efa))
713                         continue;
714                 
715                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
716                         luv      = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
717                         luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
718
719                         dist_squared = dist_squared_to_line_segment_v2(co, luv->uv, luv_next->uv);
720
721                         if (dist_squared < mindist_squared) {
722                                 hit->efa = efa;
723                                 
724                                 hit->l = l;
725                                 hit->luv = luv;
726                                 hit->luv_next = luv_next;
727                                 hit->lindex = i;
728
729                                 mindist_squared = dist_squared;
730                         }
731                 }
732         }
733 }
734
735 static void uv_find_nearest_face(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
736 {
737         BMFace *efa;
738         BMIter iter;
739         float mindist, dist, cent[2];
740
741         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
742
743         mindist = 1e10f;
744         memset(hit, 0, sizeof(*hit));
745
746         /*this will fill in hit.vert1 and hit.vert2*/
747         uv_find_nearest_edge(scene, ima, em, co, hit);
748         hit->l = NULL;
749         hit->luv = hit->luv_next = NULL;
750
751         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
752                 if (!uvedit_face_visible_test(scene, ima, efa))
753                         continue;
754
755                 uv_poly_center(efa, cent, cd_loop_uv_offset);
756
757                 dist = len_manhattan_v2v2(co, cent);
758
759                 if (dist < mindist) {
760                         hit->efa = efa;
761                         mindist = dist;
762                 }
763         }
764 }
765
766 static bool uv_nearest_between(const BMLoop *l, const float co[2],
767                                const int cd_loop_uv_offset)
768 {
769         const float *uv_prev = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l->prev, cd_loop_uv_offset))->uv;
770         const float *uv_curr = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l,       cd_loop_uv_offset))->uv;
771         const float *uv_next = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset))->uv;
772
773         return ((line_point_side_v2(uv_prev, uv_curr, co) >  0.0f) &&
774                 (line_point_side_v2(uv_next, uv_curr, co) <= 0.0f));
775 }
776
777 void uv_find_nearest_vert(Scene *scene, Image *ima, BMEditMesh *em,
778                           float const co[2], const float penalty[2], NearestHit *hit)
779 {
780         BMFace *efa;
781         BMLoop *l;
782         BMIter iter, liter;
783         MLoopUV *luv;
784         float mindist, dist;
785         int i;
786
787         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
788
789         /*this will fill in hit.vert1 and hit.vert2*/
790         uv_find_nearest_edge(scene, ima, em, co, hit);
791         hit->l = NULL;
792         hit->luv = hit->luv_next = NULL;
793
794         mindist = 1e10f;
795         memset(hit, 0, sizeof(*hit));
796         
797         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
798
799         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
800                 if (!uvedit_face_visible_test(scene, ima, efa))
801                         continue;
802
803                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
804                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
805                         if (penalty && uvedit_uv_select_test(scene, l, cd_loop_uv_offset))
806                                 dist = len_manhattan_v2v2(co, luv->uv) + len_manhattan_v2(penalty);
807                         else
808                                 dist = len_manhattan_v2v2(co, luv->uv);
809
810                         if (dist <= mindist) {
811                                 if (dist == mindist) {
812                                         if (!uv_nearest_between(l, co, cd_loop_uv_offset)) {
813                                                 continue;
814                                         }
815                                 }
816
817                                 mindist = dist;
818
819                                 hit->l = l;
820                                 hit->luv = luv;
821                                 hit->luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
822                                 hit->efa = efa;
823                                 hit->lindex = i;
824                         }
825                 }
826         }
827 }
828
829 bool ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, const float co[2], float r_uv[2])
830 {
831         BMEditMesh *em = BKE_editmesh_from_object(obedit);
832         BMFace *efa;
833         BMLoop *l;
834         BMIter iter, liter;
835         MLoopUV *luv;
836         float mindist, dist;
837         bool found = false;
838
839         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
840
841         mindist = 1e10f;
842         copy_v2_v2(r_uv, co);
843         
844         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
845                 if (!uvedit_face_visible_test(scene, ima, efa))
846                         continue;
847                 
848                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
849                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
850                         dist = len_manhattan_v2v2(co, luv->uv);
851
852                         if (dist <= mindist) {
853                                 mindist = dist;
854
855                                 copy_v2_v2(r_uv, luv->uv);
856                                 found = true;
857                         }
858                 }
859         }
860
861         return found;
862 }
863
864 /*********************** loop select ***********************/
865
866 static void uv_select_edgeloop_vertex_loop_flag(UvMapVert *first)
867 {
868         UvMapVert *iterv;
869         int count = 0;
870
871         for (iterv = first; iterv; iterv = iterv->next) {
872                 if (iterv->separate && iterv != first)
873                         break;
874
875                 count++;
876         }
877         
878         if (count < 5)
879                 first->flag = 1;
880 }
881
882 static UvMapVert *uv_select_edgeloop_vertex_map_get(UvVertMap *vmap, BMFace *efa, BMLoop *l)
883 {
884         UvMapVert *iterv, *first;
885         first = BM_uv_vert_map_at_index(vmap,  BM_elem_index_get(l->v));
886
887         for (iterv = first; iterv; iterv = iterv->next) {
888                 if (iterv->separate)
889                         first = iterv;
890                 if (iterv->f == BM_elem_index_get(efa))
891                         return first;
892         }
893         
894         return NULL;
895 }
896
897 static bool uv_select_edgeloop_edge_tag_faces(BMEditMesh *em, UvMapVert *first1, UvMapVert *first2, int *totface)
898 {
899         UvMapVert *iterv1, *iterv2;
900         BMFace *efa;
901         int tot = 0;
902
903         /* count number of faces this edge has */
904         for (iterv1 = first1; iterv1; iterv1 = iterv1->next) {
905                 if (iterv1->separate && iterv1 != first1)
906                         break;
907
908                 for (iterv2 = first2; iterv2; iterv2 = iterv2->next) {
909                         if (iterv2->separate && iterv2 != first2)
910                                 break;
911
912                         if (iterv1->f == iterv2->f) {
913                                 /* if face already tagged, don't do this edge */
914                                 efa = BM_face_at_index(em->bm, iterv1->f);
915                                 if (BM_elem_flag_test(efa, BM_ELEM_TAG))
916                                         return false;
917
918                                 tot++;
919                                 break;
920                         }
921                 }
922         }
923
924         if (*totface == 0) /* start edge */
925                 *totface = tot;
926         else if (tot != *totface) /* check for same number of faces as start edge */
927                 return false;
928
929         /* tag the faces */
930         for (iterv1 = first1; iterv1; iterv1 = iterv1->next) {
931                 if (iterv1->separate && iterv1 != first1)
932                         break;
933
934                 for (iterv2 = first2; iterv2; iterv2 = iterv2->next) {
935                         if (iterv2->separate && iterv2 != first2)
936                                 break;
937
938                         if (iterv1->f == iterv2->f) {
939                                 efa = BM_face_at_index(em->bm, iterv1->f);
940                                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
941                                 break;
942                         }
943                 }
944         }
945
946         return true;
947 }
948
949 static int uv_select_edgeloop(Scene *scene, Image *ima, BMEditMesh *em, NearestHit *hit,
950                               const float limit[2], const bool extend)
951 {
952         BMFace *efa;
953         BMIter iter, liter;
954         BMLoop *l;
955         UvVertMap *vmap;
956         UvMapVert *iterv_curr;
957         UvMapVert *iterv_next;
958         int starttotf;
959         bool looking, select;
960
961         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
962
963         /* setup */
964         BM_mesh_elem_table_ensure(em->bm, BM_FACE);
965         vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
966
967         BM_mesh_elem_index_ensure(em->bm, BM_VERT | BM_FACE);
968
969         if (!extend) {
970                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
971         }
972
973         BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
974
975         /* set flags for first face and verts */
976         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l);
977         iterv_next = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l->next);
978         uv_select_edgeloop_vertex_loop_flag(iterv_curr);
979         uv_select_edgeloop_vertex_loop_flag(iterv_next);
980
981         starttotf = 0;
982         uv_select_edgeloop_edge_tag_faces(em, iterv_curr, iterv_next, &starttotf);
983
984         /* sorry, first edge isn't even ok */
985         looking = !(iterv_curr->flag == 0 && iterv_next->flag == 0);
986
987         /* iterate */
988         while (looking) {
989                 looking = false;
990
991                 /* find correct valence edges which are not tagged yet, but connect to tagged one */
992
993                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
994                         if (!BM_elem_flag_test(efa, BM_ELEM_TAG) && uvedit_face_visible_test(scene, ima, efa)) {
995                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
996                                         /* check face not hidden and not tagged */
997                                         if (!(iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, efa, l)))
998                                                 continue;
999                                         if (!(iterv_next = uv_select_edgeloop_vertex_map_get(vmap, efa, l->next)))
1000                                                 continue;
1001
1002                                         /* check if vertex is tagged and has right valence */
1003                                         if (iterv_curr->flag || iterv_next->flag) {
1004                                                 if (uv_select_edgeloop_edge_tag_faces(em, iterv_curr, iterv_next, &starttotf)) {
1005                                                         looking = true;
1006                                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
1007
1008                                                         uv_select_edgeloop_vertex_loop_flag(iterv_curr);
1009                                                         uv_select_edgeloop_vertex_loop_flag(iterv_next);
1010                                                         break;
1011                                                 }
1012                                         }
1013                                 }
1014                         }
1015                 }
1016         }
1017
1018         /* do the actual select/deselect */
1019         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l);
1020         iterv_next = uv_select_edgeloop_vertex_map_get(vmap, hit->efa, hit->l->next);
1021         iterv_curr->flag = 1;
1022         iterv_next->flag = 1;
1023
1024         if (extend) {
1025                 select = !(uvedit_uv_select_test(scene, hit->l, cd_loop_uv_offset));
1026         }
1027         else {
1028                 select = true;
1029         }
1030         
1031         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1032                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1033                         iterv_curr = uv_select_edgeloop_vertex_map_get(vmap, efa, l);
1034
1035                         if (iterv_curr->flag) {
1036                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
1037                         }
1038                 }
1039         }
1040
1041         /* cleanup */
1042         BM_uv_vert_map_free(vmap);
1043
1044         return (select) ? 1 : -1;
1045 }
1046
1047 /*********************** linked select ***********************/
1048
1049 static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const float limit[2], NearestHit *hit, bool extend, bool select_faces)
1050 {
1051         BMFace *efa;
1052         BMLoop *l;
1053         BMIter iter, liter;
1054         MLoopUV *luv;
1055         UvVertMap *vmap;
1056         UvMapVert *vlist, *iterv, *startv;
1057         int i, stacksize = 0, *stack;
1058         unsigned int a;
1059         char *flag;
1060
1061         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1062
1063         BM_mesh_elem_table_ensure(em->bm, BM_FACE); /* we can use this too */
1064
1065         /* Note, we had 'use winding' so we don't consider overlapping islands as connected, see T44320
1066          * this made *every* projection split the island into front/back islands.
1067          * Keep 'use_winding' to false, see: T50970.
1068          *
1069          * Better solve this by having a delimit option for select-linked operator,
1070          * keeping island-select working as is. */
1071         vmap = BM_uv_vert_map_create(em->bm, limit, !select_faces, false);
1072
1073         if (vmap == NULL)
1074                 return;
1075
1076         stack = MEM_mallocN(sizeof(*stack) * (em->bm->totface + 1), "UvLinkStack");
1077         flag = MEM_callocN(sizeof(*flag) * em->bm->totface, "UvLinkFlag");
1078
1079         if (!hit) {
1080                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1081                         if (uvedit_face_visible_test(scene, ima, efa)) {
1082                                 if (select_faces) {
1083                                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1084                                                 stack[stacksize] = a;
1085                                                 stacksize++;
1086                                                 flag[a] = 1;
1087                                         }
1088                                 }
1089                                 else {
1090                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1091                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1092
1093                                                 if (luv->flag & MLOOPUV_VERTSEL) {
1094                                                         stack[stacksize] = a;
1095                                                         stacksize++;
1096                                                         flag[a] = 1;
1097
1098                                                         break;
1099                                                 }
1100                                         }
1101                                 }
1102                         }
1103                 }
1104         }
1105         else {
1106                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1107                         if (efa == hit->efa) {
1108                                 stack[stacksize] = a;
1109                                 stacksize++;
1110                                 flag[a] = 1;
1111                                 break;
1112                         }
1113                 }
1114         }
1115
1116         while (stacksize > 0) {
1117
1118                 stacksize--;
1119                 a = stack[stacksize];
1120
1121                 efa = BM_face_at_index(em->bm, a);
1122
1123                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1124
1125                         /* make_uv_vert_map_EM sets verts tmp.l to the indices */
1126                         vlist = BM_uv_vert_map_at_index(vmap, BM_elem_index_get(l->v));
1127                         
1128                         startv = vlist;
1129
1130                         for (iterv = vlist; iterv; iterv = iterv->next) {
1131                                 if (iterv->separate)
1132                                         startv = iterv;
1133                                 if (iterv->f == a)
1134                                         break;
1135                         }
1136
1137                         for (iterv = startv; iterv; iterv = iterv->next) {
1138                                 if ((startv != iterv) && (iterv->separate))
1139                                         break;
1140                                 else if (!flag[iterv->f]) {
1141                                         flag[iterv->f] = 1;
1142                                         stack[stacksize] = iterv->f;
1143                                         stacksize++;
1144                                 }
1145                         }
1146                 }
1147         }
1148
1149         if (!extend) {
1150                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1151                         if (select_faces) {
1152                                 if (flag[a])
1153                                         BM_face_select_set(em->bm, efa, true);
1154                                 else
1155                                         BM_face_select_set(em->bm, efa, false);
1156                         }
1157                         else {
1158                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1159                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1160
1161                                         if (flag[a])
1162                                                 luv->flag |= MLOOPUV_VERTSEL;
1163                                         else
1164                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1165                                 }
1166                         }
1167                 }
1168         }
1169         else {
1170                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1171                         if (!flag[a]) {
1172                                 continue;
1173                         }
1174
1175                         if (select_faces) {
1176                                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
1177                                         break;
1178                         }
1179                         else {
1180                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1181                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1182
1183                                         if (luv->flag & MLOOPUV_VERTSEL) {
1184                                                 break;
1185                                         }
1186                                 }
1187
1188                                 if (l) {
1189                                         break;
1190                                 }
1191                         }
1192                 }
1193
1194                 if (efa) {
1195                         BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1196                                 if (!flag[a]) {
1197                                         continue;
1198                                 }
1199
1200                                 if (select_faces) {
1201                                         BM_face_select_set(em->bm, efa, false);
1202                                 }
1203                                 else {
1204                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1205                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1206
1207                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1208                                         }
1209                                 }
1210                         }
1211                 }
1212                 else {
1213                         BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
1214                                 if (!flag[a]) {
1215                                         continue;
1216                                 }
1217
1218                                 if (select_faces) {
1219                                         BM_face_select_set(em->bm, efa, true);
1220                                 }
1221                                 else {
1222                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1223                                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1224
1225                                                 luv->flag |= MLOOPUV_VERTSEL;
1226                                         }
1227                                 }
1228                         }
1229                 }
1230         }
1231         
1232         MEM_freeN(stack);
1233         MEM_freeN(flag);
1234         BM_uv_vert_map_free(vmap);
1235 }
1236
1237 /* WATCH IT: this returns first selected UV,
1238  * not ideal in many cases since there could be multiple */
1239 static float *uv_sel_co_from_eve(Scene *scene, Image *ima, BMEditMesh *em, BMVert *eve)
1240 {
1241         BMIter liter;
1242         BMLoop *l;
1243
1244         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1245
1246         BM_ITER_ELEM (l, &liter, eve, BM_LOOPS_OF_VERT) {
1247                 if (!uvedit_face_visible_test(scene, ima, l->f))
1248                         continue;
1249
1250                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1251                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1252                         return luv->uv;
1253                 }
1254         }
1255
1256         return NULL;
1257 }
1258
1259 static int uv_select_more_less(bContext *C, const bool select)
1260 {
1261         Scene *scene = CTX_data_scene(C);
1262         Object *obedit = CTX_data_edit_object(C);
1263         Image *ima = CTX_data_edit_image(C);
1264         SpaceImage *sima = CTX_wm_space_image(C);
1265         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1266
1267         BMFace *efa;
1268         BMLoop *l;
1269         BMIter iter, liter;
1270         ToolSettings *ts = scene->toolsettings;
1271
1272         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1273
1274         if (ts->uv_flag & UV_SYNC_SELECTION) {
1275                 if (select) {
1276                         EDBM_select_more(em, true);
1277                 }
1278                 else {
1279                         EDBM_select_less(em, true);
1280                 }
1281
1282                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1283                 return OPERATOR_FINISHED;
1284         }
1285
1286         if (ts->uv_selectmode == UV_SELECT_FACE) {
1287
1288                 /* clear tags */
1289                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1290                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
1291                 }
1292
1293                 /* mark loops to be selected */
1294                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1295                         if (uvedit_face_visible_test(scene, ima, efa)) {
1296
1297 #define IS_SEL   1
1298 #define IS_UNSEL 2
1299
1300                                 int sel_state = 0;
1301
1302                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1303                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1304                                         if (luv->flag & MLOOPUV_VERTSEL) {
1305                                                 sel_state |= IS_SEL;
1306                                         }
1307                                         else {
1308                                                 sel_state |= IS_UNSEL;
1309                                         }
1310
1311                                         /* if we have a mixed selection, tag to grow it */
1312                                         if (sel_state == (IS_SEL | IS_UNSEL)) {
1313                                                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
1314                                                 break;
1315                                         }
1316                                 }
1317
1318 #undef IS_SEL
1319 #undef IS_UNSEL
1320
1321                         }
1322                 }
1323
1324                 /* select tagged faces */
1325                 uv_select_flush_from_tag_face(sima, scene, obedit, select);
1326         }
1327         else {
1328
1329                 /* clear tags */
1330                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1331                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1332                                 BM_elem_flag_disable(l, BM_ELEM_TAG);
1333                         }
1334                 }
1335
1336                 /* mark loops to be selected */
1337                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1338                         if (uvedit_face_visible_test(scene, ima, efa)) {
1339                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1340
1341                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1342
1343                                         if (((luv->flag & MLOOPUV_VERTSEL) != 0) == select) {
1344                                                 BM_elem_flag_enable(l->next, BM_ELEM_TAG);
1345                                                 BM_elem_flag_enable(l->prev, BM_ELEM_TAG);
1346                                         }
1347                                 }
1348                         }
1349                 }
1350
1351                 /* select tagged loops */
1352                 uv_select_flush_from_tag_loop(sima, scene, obedit, select);
1353         }
1354
1355         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1356
1357         return OPERATOR_FINISHED;
1358 }
1359
1360 static int uv_select_more_exec(bContext *C, wmOperator *UNUSED(op))
1361 {
1362         return uv_select_more_less(C, true);
1363 }
1364
1365 static void UV_OT_select_more(wmOperatorType *ot)
1366 {
1367         /* identifiers */
1368         ot->name = "Select More";
1369         ot->description = "Select more UV vertices connected to initial selection";
1370         ot->idname = "UV_OT_select_more";
1371         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1372
1373         /* api callbacks */
1374         ot->exec = uv_select_more_exec;
1375         ot->poll = ED_operator_uvedit_space_image;
1376 }
1377
1378 static int uv_select_less_exec(bContext *C, wmOperator *UNUSED(op))
1379 {
1380         return uv_select_more_less(C, false);
1381 }
1382
1383 static void UV_OT_select_less(wmOperatorType *ot)
1384 {
1385         /* identifiers */
1386         ot->name = "Select Less";
1387         ot->description = "Deselect UV vertices at the boundary of each selection region";
1388         ot->idname = "UV_OT_select_less";
1389         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1390
1391         /* api callbacks */
1392         ot->exec = uv_select_less_exec;
1393         ot->poll = ED_operator_uvedit_space_image;
1394 }
1395
1396 /* ******************** align operator **************** */
1397
1398 static void uv_weld_align(bContext *C, int tool)
1399 {
1400         Object *obedit = CTX_data_edit_object(C);
1401         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1402         SpaceImage *sima;
1403         Scene *scene;
1404         Image *ima;
1405         float cent[2], min[2], max[2];
1406
1407         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1408
1409         scene = CTX_data_scene(C);
1410         ima = CTX_data_edit_image(C);
1411         sima = CTX_wm_space_image(C);
1412
1413         INIT_MINMAX2(min, max);
1414
1415         if (tool == 'a') {
1416                 BMIter iter, liter;
1417                 BMFace *efa;
1418                 BMLoop *l;
1419
1420                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1421                         if (!uvedit_face_visible_test(scene, ima, efa))
1422                                 continue;
1423
1424                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1425                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1426                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1427                                         minmax_v2v2_v2(min, max, luv->uv);
1428                                 }
1429                         }
1430                 }
1431
1432                 tool = (max[0] - min[0] >= max[1] - min[1]) ? 'y' : 'x';
1433         }
1434
1435         ED_uvedit_center(scene, ima, obedit, cent, 0);
1436
1437         if (tool == 'x' || tool == 'w') {
1438                 BMIter iter, liter;
1439                 BMFace *efa;
1440                 BMLoop *l;
1441
1442                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1443                         if (!uvedit_face_visible_test(scene, ima, efa))
1444                                 continue;
1445
1446                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1447                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1448                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1449                                         luv->uv[0] = cent[0];
1450                                 }
1451
1452                         }
1453                 }
1454         }
1455
1456         if (tool == 'y' || tool == 'w') {
1457                 BMIter iter, liter;
1458                 BMFace *efa;
1459                 BMLoop *l;
1460
1461                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1462                         if (!uvedit_face_visible_test(scene, ima, efa))
1463                                 continue;
1464
1465                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1466                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1467                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1468                                         luv->uv[1] = cent[1];
1469                                 }
1470
1471                         }
1472                 }
1473         }
1474
1475         if (tool == 's' || tool == 't' || tool == 'u') {
1476                 BMEdge *eed;
1477                 BMLoop *l;
1478                 BMVert *eve;
1479                 BMVert *eve_start;
1480                 BMIter iter, liter, eiter;
1481
1482                 /* clear tag */
1483                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1484                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
1485                 }
1486
1487                 /* tag verts with a selected UV */
1488                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1489                         BM_ITER_ELEM (l, &liter, eve, BM_LOOPS_OF_VERT) {
1490                                 if (!uvedit_face_visible_test(scene, ima, l->f))
1491                                         continue;
1492
1493                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1494                                         BM_elem_flag_enable(eve, BM_ELEM_TAG);
1495                                         break;
1496                                 }
1497                         }
1498                 }
1499
1500                 /* flush vertex tags to edges */
1501                 BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
1502                         BM_elem_flag_set(eed, BM_ELEM_TAG, (BM_elem_flag_test(eed->v1, BM_ELEM_TAG) &&
1503                                                             BM_elem_flag_test(eed->v2, BM_ELEM_TAG)));
1504                 }
1505
1506                 /* find a vertex with only one tagged edge */
1507                 eve_start = NULL;
1508                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1509                         int tot_eed_tag = 0;
1510                         BM_ITER_ELEM (eed, &eiter, eve, BM_EDGES_OF_VERT) {
1511                                 if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1512                                         tot_eed_tag++;
1513                                 }
1514                         }
1515
1516                         if (tot_eed_tag == 1) {
1517                                 eve_start = eve;
1518                                 break;
1519                         }
1520                 }
1521
1522                 if (eve_start) {
1523                         BMVert **eve_line = NULL;
1524                         BMVert *eve_next = NULL;
1525                         BLI_array_declare(eve_line);
1526                         int i;
1527
1528                         eve = eve_start;
1529
1530                         /* walk over edges, building an array of verts in a line */
1531                         while (eve) {
1532                                 BLI_array_append(eve_line, eve);
1533                                 /* don't touch again */
1534                                 BM_elem_flag_disable(eve, BM_ELEM_TAG);
1535
1536                                 eve_next = NULL;
1537
1538                                 /* find next eve */
1539                                 BM_ITER_ELEM (eed, &eiter, eve, BM_EDGES_OF_VERT) {
1540                                         if (BM_elem_flag_test(eed, BM_ELEM_TAG)) {
1541                                                 BMVert *eve_other = BM_edge_other_vert(eed, eve);
1542                                                 if (BM_elem_flag_test(eve_other, BM_ELEM_TAG)) {
1543                                                         /* this is a tagged vert we didnt walk over yet, step onto it */
1544                                                         eve_next = eve_other;
1545                                                         break;
1546                                                 }
1547                                         }
1548                                 }
1549
1550                                 eve = eve_next;
1551                         }
1552
1553                         /* now we have all verts, make into a line */
1554                         if (BLI_array_count(eve_line) > 2) {
1555
1556                                 /* we know the returns from these must be valid */
1557                                 const float *uv_start = uv_sel_co_from_eve(scene, ima, em, eve_line[0]);
1558                                 const float *uv_end   = uv_sel_co_from_eve(scene, ima, em, eve_line[BLI_array_count(eve_line) - 1]);
1559                                 /* For t & u modes */
1560                                 float a = 0.0f;
1561
1562                                 if (tool == 't') {
1563                                         if (uv_start[1] == uv_end[1])
1564                                                 tool = 's';
1565                                         else
1566                                                 a = (uv_end[0] - uv_start[0]) / (uv_end[1] - uv_start[1]);
1567                                 }
1568                                 else if (tool == 'u') {
1569                                         if (uv_start[0] == uv_end[0])
1570                                                 tool = 's';
1571                                         else
1572                                                 a = (uv_end[1] - uv_start[1]) / (uv_end[0] - uv_start[0]);
1573                                 }
1574
1575                                 /* go over all verts except for endpoints */
1576                                 for (i = 0; i < BLI_array_count(eve_line); i++) {
1577                                         BM_ITER_ELEM (l, &liter, eve_line[i], BM_LOOPS_OF_VERT) {
1578                                                 if (!uvedit_face_visible_test(scene, ima, l->f))
1579                                                         continue;
1580
1581                                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1582                                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1583                                                         /* Projection of point (x, y) over line (x1, y1, x2, y2) along X axis:
1584                                                          * new_y = (y2 - y1) / (x2 - x1) * (x - x1) + y1
1585                                                          * Maybe this should be a BLI func? Or is it already existing?
1586                                                          * Could use interp_v2_v2v2, but not sure it's worth it here...*/
1587                                                         if (tool == 't')
1588                                                                 luv->uv[0] = a * (luv->uv[1] - uv_start[1]) + uv_start[0];
1589                                                         else if (tool == 'u')
1590                                                                 luv->uv[1] = a * (luv->uv[0] - uv_start[0]) + uv_start[1];
1591                                                         else
1592                                                                 closest_to_line_segment_v2(luv->uv, luv->uv, uv_start, uv_end);
1593                                                 }
1594                                         }
1595                                 }
1596                         }
1597                         else {
1598                                 /* error - not a line, needs 3+ points  */
1599                         }
1600
1601                         if (eve_line) {
1602                                 MEM_freeN(eve_line);
1603                         }
1604                 }
1605                 else {
1606                         /* error - cant find an endpoint */
1607                 }
1608         }
1609
1610
1611         uvedit_live_unwrap_update(sima, scene, obedit);
1612         DEG_id_tag_update(obedit->data, 0);
1613         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1614 }
1615
1616 static int uv_align_exec(bContext *C, wmOperator *op)
1617 {
1618         uv_weld_align(C, RNA_enum_get(op->ptr, "axis"));
1619
1620         return OPERATOR_FINISHED;
1621 }
1622
1623 static void UV_OT_align(wmOperatorType *ot)
1624 {
1625         static const EnumPropertyItem axis_items[] = {
1626                 {'s', "ALIGN_S", 0, "Straighten", "Align UVs along the line defined by the endpoints"},
1627                 {'t', "ALIGN_T", 0, "Straighten X", "Align UVs along the line defined by the endpoints along the X axis"},
1628                 {'u', "ALIGN_U", 0, "Straighten Y", "Align UVs along the line defined by the endpoints along the Y axis"},
1629                 {'a', "ALIGN_AUTO", 0, "Align Auto", "Automatically choose the axis on which there is most alignment already"},
1630                 {'x', "ALIGN_X", 0, "Align X", "Align UVs on X axis"},
1631                 {'y', "ALIGN_Y", 0, "Align Y", "Align UVs on Y axis"},
1632                 {0, NULL, 0, NULL, NULL}};
1633
1634         /* identifiers */
1635         ot->name = "Align";
1636         ot->description = "Align selected UV vertices to an axis";
1637         ot->idname = "UV_OT_align";
1638         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1639         
1640         /* api callbacks */
1641         ot->exec = uv_align_exec;
1642         ot->poll = ED_operator_uvedit;
1643
1644         /* properties */
1645         RNA_def_enum(ot->srna, "axis", axis_items, 'a', "Axis", "Axis to align UV locations on");
1646 }
1647 /* ******************** weld near operator **************** */
1648
1649 typedef struct UVvert {
1650         MLoopUV *uv_loop;
1651         bool weld;
1652 } UVvert;
1653
1654 static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
1655 {
1656         const float threshold = RNA_float_get(op->ptr, "threshold");
1657         const bool use_unselected = RNA_boolean_get(op->ptr, "use_unselected");
1658
1659         SpaceImage *sima;
1660         Scene *scene;
1661         Object *obedit = CTX_data_edit_object(C);
1662         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1663         Image *ima;
1664         int uv_a_index;
1665         int uv_b_index;
1666         float *uv_a;
1667         const float *uv_b;
1668
1669         BMIter iter, liter;
1670         BMFace *efa;
1671         BMLoop *l;
1672
1673         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1674
1675         sima = CTX_wm_space_image(C);
1676         scene = CTX_data_scene(C);
1677         ima = CTX_data_edit_image(C);
1678
1679         if (use_unselected == false) {
1680                 UVvert *vert_arr = NULL;
1681                 BLI_array_declare(vert_arr);
1682                 MLoopUV **loop_arr = NULL;
1683                 BLI_array_declare(loop_arr);
1684
1685                 /* TODO, use qsort as with MESH_OT_remove_doubles, this isn't optimal */
1686                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1687                         if (!uvedit_face_visible_test(scene, ima, efa))
1688                                 continue;
1689
1690                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1691                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1692                                         MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1693                                         UVvert vert;
1694                                         vert.uv_loop = luv;
1695                                         vert.weld = false;
1696                                         BLI_array_append(vert_arr, vert);
1697                                 }
1698
1699                         }
1700                 }
1701
1702                 for (uv_a_index = 0; uv_a_index < BLI_array_count(vert_arr); uv_a_index++) {
1703                         if (vert_arr[uv_a_index].weld == false) {
1704                                 float uv_min[2];
1705                                 float uv_max[2];
1706
1707                                 BLI_array_clear(loop_arr);
1708                                 BLI_array_append(loop_arr, vert_arr[uv_a_index].uv_loop);
1709
1710                                 uv_a = vert_arr[uv_a_index].uv_loop->uv;
1711
1712                                 copy_v2_v2(uv_max, uv_a);
1713                                 copy_v2_v2(uv_min, uv_a);
1714
1715                                 vert_arr[uv_a_index].weld = true;
1716                                 for (uv_b_index = uv_a_index + 1; uv_b_index < BLI_array_count(vert_arr); uv_b_index++) {
1717                                         uv_b = vert_arr[uv_b_index].uv_loop->uv;
1718                                         if ((vert_arr[uv_b_index].weld == false) &&
1719                                             (len_manhattan_v2v2(uv_a, uv_b) < threshold))
1720                                         {
1721                                                 minmax_v2v2_v2(uv_min, uv_max, uv_b);
1722                                                 BLI_array_append(loop_arr, vert_arr[uv_b_index].uv_loop);
1723                                                 vert_arr[uv_b_index].weld = true;
1724                                         }
1725                                 }
1726                                 if (BLI_array_count(loop_arr)) {
1727                                         float uv_mid[2];
1728                                         mid_v2_v2v2(uv_mid, uv_min, uv_max);
1729                                         for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr); uv_b_index++) {
1730                                                 copy_v2_v2(loop_arr[uv_b_index]->uv, uv_mid);
1731                                         }
1732                                 }
1733                         }
1734                 }
1735
1736                 BLI_array_free(vert_arr);
1737                 BLI_array_free(loop_arr);
1738         }
1739         else {
1740                 /* selected -> unselected
1741                  *
1742                  * No need to use 'UVvert' here */
1743                 MLoopUV **loop_arr = NULL;
1744                 BLI_array_declare(loop_arr);
1745                 MLoopUV **loop_arr_unselected = NULL;
1746                 BLI_array_declare(loop_arr_unselected);
1747
1748                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1749                         if (!uvedit_face_visible_test(scene, ima, efa))
1750                                 continue;
1751
1752                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1753                                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1754                                 if (uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
1755                                         BLI_array_append(loop_arr, luv);
1756                                 }
1757                                 else {
1758                                         BLI_array_append(loop_arr_unselected, luv);
1759                                 }
1760                         }
1761                 }
1762
1763                 for (uv_a_index = 0; uv_a_index < BLI_array_count(loop_arr); uv_a_index++) {
1764                         float dist_best = FLT_MAX, dist;
1765                         const float *uv_best = NULL;
1766
1767                         uv_a = loop_arr[uv_a_index]->uv;
1768                         for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr_unselected); uv_b_index++) {
1769                                 uv_b = loop_arr_unselected[uv_b_index]->uv;
1770                                 dist = len_manhattan_v2v2(uv_a, uv_b);
1771                                 if ((dist < threshold) && (dist < dist_best)) {
1772                                         uv_best = uv_b;
1773                                         dist_best = dist;
1774                                 }
1775                         }
1776                         if (uv_best) {
1777                                 copy_v2_v2(uv_a, uv_best);
1778                         }
1779                 }
1780
1781                 BLI_array_free(loop_arr);
1782                 BLI_array_free(loop_arr_unselected);
1783         }
1784
1785         uvedit_live_unwrap_update(sima, scene, obedit);
1786         DEG_id_tag_update(obedit->data, 0);
1787         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1788
1789         return OPERATOR_FINISHED;
1790 }
1791
1792 static void UV_OT_remove_doubles(wmOperatorType *ot)
1793 {
1794         /* identifiers */
1795         ot->name = "Remove Doubles UV";
1796         ot->description = "Selected UV vertices that are within a radius of each other are welded together";
1797         ot->idname = "UV_OT_remove_doubles";
1798         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1799
1800         /* api callbacks */
1801         ot->exec = uv_remove_doubles_exec;
1802         ot->poll = ED_operator_uvedit;
1803
1804         RNA_def_float(ot->srna, "threshold", 0.02f, 0.0f, 10.0f,
1805                       "Merge Distance", "Maximum distance between welded vertices", 0.0f, 1.0f);
1806         RNA_def_boolean(ot->srna, "use_unselected", 0, "Unselected", "Merge selected to other unselected vertices");
1807 }
1808 /* ******************** weld operator **************** */
1809
1810 static int uv_weld_exec(bContext *C, wmOperator *UNUSED(op))
1811 {
1812         uv_weld_align(C, 'w');
1813
1814         return OPERATOR_FINISHED;
1815 }
1816
1817 static void UV_OT_weld(wmOperatorType *ot)
1818 {
1819         /* identifiers */
1820         ot->name = "Weld";
1821         ot->description = "Weld selected UV vertices together";
1822         ot->idname = "UV_OT_weld";
1823         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1824         
1825         /* api callbacks */
1826         ot->exec = uv_weld_exec;
1827         ot->poll = ED_operator_uvedit;
1828 }
1829
1830
1831 /* ******************** (de)select all operator **************** */
1832
1833 static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int action)
1834 {
1835         ToolSettings *ts = scene->toolsettings;
1836         BMFace *efa;
1837         BMLoop *l;
1838         BMIter iter, liter;
1839         MLoopUV *luv;
1840
1841         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1842
1843         if (ts->uv_flag & UV_SYNC_SELECTION) {
1844
1845                 switch (action) {
1846                         case SEL_TOGGLE:
1847                                 EDBM_select_toggle_all(em);
1848                                 break;
1849                         case SEL_SELECT:
1850                                 EDBM_flag_enable_all(em, BM_ELEM_SELECT);
1851                                 break;
1852                         case SEL_DESELECT:
1853                                 EDBM_flag_disable_all(em, BM_ELEM_SELECT);
1854                                 break;
1855                         case SEL_INVERT:
1856                                 EDBM_select_swap(em);
1857                                 EDBM_selectmode_flush(em);
1858                                 break;
1859                 }
1860         }
1861         else {
1862                 if (action == SEL_TOGGLE) {
1863                         action = SEL_SELECT;
1864                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1865                                 if (!uvedit_face_visible_test(scene, ima, efa))
1866                                         continue;
1867
1868                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1869                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1870
1871                                         if (luv->flag & MLOOPUV_VERTSEL) {
1872                                                 action = SEL_DESELECT;
1873                                                 break;
1874                                         }
1875                                 }
1876                         }
1877                 }
1878         
1879                 
1880                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1881                         if (!uvedit_face_visible_test(scene, ima, efa))
1882                                 continue;
1883
1884                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1885                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
1886
1887                                 switch (action) {
1888                                         case SEL_SELECT:
1889                                                 luv->flag |= MLOOPUV_VERTSEL;
1890                                                 break;
1891                                         case SEL_DESELECT:
1892                                                 luv->flag &= ~MLOOPUV_VERTSEL;
1893                                                 break;
1894                                         case SEL_INVERT:
1895                                                 luv->flag ^= MLOOPUV_VERTSEL;
1896                                                 break;
1897                                 }
1898                         }
1899                 }
1900         }
1901 }
1902
1903 static int uv_select_all_exec(bContext *C, wmOperator *op)
1904 {
1905         Scene *scene = CTX_data_scene(C);
1906         Object *obedit = CTX_data_edit_object(C);
1907         Image *ima = CTX_data_edit_image(C);
1908         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1909
1910         int action = RNA_enum_get(op->ptr, "action");
1911
1912         uv_select_all_perform(scene, ima, em, action);
1913
1914         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
1915
1916         return OPERATOR_FINISHED;
1917 }
1918
1919 static void UV_OT_select_all(wmOperatorType *ot)
1920 {
1921         /* identifiers */
1922         ot->name = "(De)select All";
1923         ot->description = "Change selection of all UV vertices";
1924         ot->idname = "UV_OT_select_all";
1925         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1926         
1927         /* api callbacks */
1928         ot->exec = uv_select_all_exec;
1929         ot->poll = ED_operator_uvedit;
1930
1931         WM_operator_properties_select_all(ot);
1932 }
1933
1934 /* ******************** mouse select operator **************** */
1935
1936 static bool uv_sticky_select(float *limit, int hitv[4], int v, float *hituv[4], float *uv, int sticky, int hitlen)
1937 {
1938         int i;
1939
1940         /* this function test if some vertex needs to selected
1941          * in addition to the existing ones due to sticky select */
1942         if (sticky == SI_STICKY_DISABLE)
1943                 return false;
1944
1945         for (i = 0; i < hitlen; i++) {
1946                 if (hitv[i] == v) {
1947                         if (sticky == SI_STICKY_LOC) {
1948                                 if (fabsf(hituv[i][0] - uv[0]) < limit[0] && fabsf(hituv[i][1] - uv[1]) < limit[1])
1949                                         return true;
1950                         }
1951                         else if (sticky == SI_STICKY_VERTEX)
1952                                 return true;
1953                 }
1954         }
1955
1956         return false;
1957 }
1958
1959 static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loop)
1960 {
1961         SpaceImage *sima = CTX_wm_space_image(C);
1962         Scene *scene = CTX_data_scene(C);
1963         ToolSettings *ts = scene->toolsettings;
1964         Object *obedit = CTX_data_edit_object(C);
1965         Image *ima = CTX_data_edit_image(C);
1966         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1967         BMFace *efa;
1968         BMLoop *l;
1969         BMIter iter, liter;
1970         MLoopUV *luv;
1971         NearestHit hit;
1972         int i, selectmode, sticky, sync, *hitv = NULL;
1973         bool select = true;
1974         int flush = 0, hitlen = 0; /* 0 == don't flush, 1 == sel, -1 == desel;  only use when selection sync is enabled */
1975         float limit[2], **hituv = NULL;
1976         float penalty[2];
1977
1978         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
1979
1980         /* notice 'limit' is the same no matter the zoom level, since this is like
1981          * remove doubles and could annoying if it joined points when zoomed out.
1982          * 'penalty' is in screen pixel space otherwise zooming in on a uv-vert and
1983          * shift-selecting can consider an adjacent point close enough to add to
1984          * the selection rather than de-selecting the closest. */
1985
1986         uvedit_pixel_to_float(sima, limit, 0.05f);
1987         uvedit_pixel_to_float(sima, penalty, 5.0f / (sima ? sima->zoom : 1.0f));
1988
1989         /* retrieve operation mode */
1990         if (ts->uv_flag & UV_SYNC_SELECTION) {
1991                 sync = 1;
1992
1993                 if (ts->selectmode & SCE_SELECT_FACE)
1994                         selectmode = UV_SELECT_FACE;
1995                 else if (ts->selectmode & SCE_SELECT_EDGE)
1996                         selectmode = UV_SELECT_EDGE;
1997                 else
1998                         selectmode = UV_SELECT_VERTEX;
1999
2000                 sticky = SI_STICKY_DISABLE;
2001         }
2002         else {
2003                 sync = 0;
2004                 selectmode = ts->uv_selectmode;
2005                 sticky = (sima) ? sima->sticky : 1;
2006         }
2007
2008         /* find nearest element */
2009         if (loop) {
2010                 /* find edge */
2011                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2012                 if (hit.efa == NULL) {
2013                         return OPERATOR_CANCELLED;
2014                 }
2015
2016                 hitlen = 0;
2017         }
2018         else if (selectmode == UV_SELECT_VERTEX) {
2019                 /* find vertex */
2020                 uv_find_nearest_vert(scene, ima, em, co, penalty, &hit);
2021                 if (hit.efa == NULL) {
2022                         return OPERATOR_CANCELLED;
2023                 }
2024
2025                 /* mark 1 vertex as being hit */
2026                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2027                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2028                 copy_vn_i(hitv, hit.efa->len, 0xFFFFFFFF);
2029
2030                 hitv[hit.lindex] = BM_elem_index_get(hit.l->v);
2031                 hituv[hit.lindex] = hit.luv->uv;
2032
2033                 hitlen = hit.efa->len;
2034         }
2035         else if (selectmode == UV_SELECT_EDGE) {
2036                 /* find edge */
2037                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2038                 if (hit.efa == NULL) {
2039                         return OPERATOR_CANCELLED;
2040                 }
2041
2042                 /* mark 2 edge vertices as being hit */
2043                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2044                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2045                 copy_vn_i(hitv, hit.efa->len, 0xFFFFFFFF);
2046
2047                 hitv[hit.lindex] = BM_elem_index_get(hit.l->v);
2048                 hitv[(hit.lindex + 1) % hit.efa->len] = BM_elem_index_get(hit.l->next->v);
2049                 hituv[hit.lindex] = hit.luv->uv;
2050                 hituv[(hit.lindex + 1) % hit.efa->len] = hit.luv_next->uv;
2051
2052                 hitlen = hit.efa->len;
2053         }
2054         else if (selectmode == UV_SELECT_FACE) {
2055                 /* find face */
2056                 uv_find_nearest_face(scene, ima, em, co, &hit);
2057                 if (hit.efa == NULL) {
2058                         return OPERATOR_CANCELLED;
2059                 }
2060                 
2061                 /* make active */
2062                 BM_mesh_active_face_set(em->bm, hit.efa);
2063
2064                 /* mark all face vertices as being hit */
2065
2066                 hitv  = BLI_array_alloca(hitv,  hit.efa->len);
2067                 hituv = BLI_array_alloca(hituv, hit.efa->len);
2068                 BM_ITER_ELEM_INDEX (l, &liter, hit.efa, BM_LOOPS_OF_FACE, i) {
2069                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2070                         hituv[i] = luv->uv;
2071                         hitv[i] = BM_elem_index_get(l->v);
2072                 }
2073                 
2074                 hitlen = hit.efa->len;
2075         }
2076         else if (selectmode == UV_SELECT_ISLAND) {
2077                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2078
2079                 if (hit.efa == NULL) {
2080                         return OPERATOR_CANCELLED;
2081                 }
2082
2083                 hitlen = 0;
2084         }
2085         else {
2086                 hitlen = 0;
2087                 return OPERATOR_CANCELLED;
2088         }
2089
2090         /* do selection */
2091         if (loop) {
2092                 flush = uv_select_edgeloop(scene, ima, em, &hit, limit, extend);
2093         }
2094         else if (selectmode == UV_SELECT_ISLAND) {
2095                 uv_select_linked(scene, ima, em, limit, &hit, extend, false);
2096         }
2097         else if (extend) {
2098                 if (selectmode == UV_SELECT_VERTEX) {
2099                         /* (de)select uv vertex */
2100                         select = !uvedit_uv_select_test(scene, hit.l, cd_loop_uv_offset);
2101                         uvedit_uv_select_set(em, scene, hit.l, select, true, cd_loop_uv_offset);
2102                         flush = 1;
2103                 }
2104                 else if (selectmode == UV_SELECT_EDGE) {
2105                         /* (de)select edge */
2106                         select = !(uvedit_edge_select_test(scene, hit.l, cd_loop_uv_offset));
2107                         uvedit_edge_select_set(em, scene, hit.l, select, true, cd_loop_uv_offset);
2108                         flush = 1;
2109                 }
2110                 else if (selectmode == UV_SELECT_FACE) {
2111                         /* (de)select face */
2112                         select = !(uvedit_face_select_test(scene, hit.efa, cd_loop_uv_offset));
2113                         uvedit_face_select_set(scene, em, hit.efa, select, true, cd_loop_uv_offset);
2114                         flush = -1;
2115                 }
2116
2117                 /* de-selecting an edge may deselect a face too - validate */
2118                 if (sync) {
2119                         if (select == false) {
2120                                 BM_select_history_validate(em->bm);
2121                         }
2122                 }
2123
2124                 /* (de)select sticky uv nodes */
2125                 if (sticky != SI_STICKY_DISABLE) {
2126
2127                         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
2128
2129                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2130                                 if (!uvedit_face_visible_test(scene, ima, efa))
2131                                         continue;
2132
2133                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2134                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2135                                         if (uv_sticky_select(limit, hitv, BM_elem_index_get(l->v), hituv, luv->uv, sticky, hitlen))
2136                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2137                                 }
2138                         }
2139
2140                         flush = select ? 1 : -1;
2141                 }
2142         }
2143         else {
2144                 /* deselect all */
2145                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
2146
2147                 if (selectmode == UV_SELECT_VERTEX) {
2148                         /* select vertex */
2149                         uvedit_uv_select_enable(em, scene, hit.l, true, cd_loop_uv_offset);
2150                         flush = 1;
2151                 }
2152                 else if (selectmode == UV_SELECT_EDGE) {
2153                         /* select edge */
2154                         uvedit_edge_select_enable(em, scene, hit.l, true, cd_loop_uv_offset);
2155                         flush = 1;
2156                 }
2157                 else if (selectmode == UV_SELECT_FACE) {
2158                         /* select face */
2159                         uvedit_face_select_enable(scene, em, hit.efa, true, cd_loop_uv_offset);
2160                 }
2161
2162                 /* select sticky uvs */
2163                 if (sticky != SI_STICKY_DISABLE) {
2164                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2165                                 if (!uvedit_face_visible_test(scene, ima, efa))
2166                                         continue;
2167                                 
2168                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2169                                         if (sticky == SI_STICKY_DISABLE) continue;
2170                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2171
2172                                         if (uv_sticky_select(limit, hitv, BM_elem_index_get(l->v), hituv, luv->uv, sticky, hitlen))
2173                                                 uvedit_uv_select_enable(em, scene, l, false, cd_loop_uv_offset);
2174
2175                                         flush = 1;
2176                                 }
2177                         }
2178                 }
2179         }
2180
2181         if (sync) {
2182                 /* flush for mesh selection */
2183
2184                 /* before bmesh */
2185 #if 0
2186                 if (ts->selectmode != SCE_SELECT_FACE) {
2187                         if (flush == 1) EDBM_select_flush(em);
2188                         else if (flush == -1) EDBM_deselect_flush(em);
2189                 }
2190 #else
2191                 if (flush != 0) {
2192                         if (loop) {
2193                                 /* push vertex -> edge selection */
2194                                 if (select) {
2195                                         EDBM_select_flush(em);
2196                                 }
2197                                 else {
2198                                         EDBM_deselect_flush(em);
2199                                 }
2200                         }
2201                         else {
2202                                 EDBM_selectmode_flush(em);
2203                         }
2204                 }
2205 #endif
2206         }
2207
2208         DEG_id_tag_update(obedit->data, 0);
2209         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2210
2211         return OPERATOR_PASS_THROUGH | OPERATOR_FINISHED;
2212 }
2213
2214 static int uv_select_exec(bContext *C, wmOperator *op)
2215 {
2216         float co[2];
2217         bool extend, loop;
2218
2219         RNA_float_get_array(op->ptr, "location", co);
2220         extend = RNA_boolean_get(op->ptr, "extend");
2221         loop = false;
2222
2223         return uv_mouse_select(C, co, extend, loop);
2224 }
2225
2226 static int uv_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2227 {
2228         ARegion *ar = CTX_wm_region(C);
2229         float co[2];
2230
2231         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2232         RNA_float_set_array(op->ptr, "location", co);
2233
2234         return uv_select_exec(C, op);
2235 }
2236
2237 static void UV_OT_select(wmOperatorType *ot)
2238 {
2239         /* identifiers */
2240         ot->name = "Select";
2241         ot->description = "Select UV vertices";
2242         ot->idname = "UV_OT_select";
2243         ot->flag = OPTYPE_UNDO;
2244         
2245         /* api callbacks */
2246         ot->exec = uv_select_exec;
2247         ot->invoke = uv_select_invoke;
2248         ot->poll = ED_operator_uvedit; /* requires space image */;
2249
2250         /* properties */
2251         RNA_def_boolean(ot->srna, "extend", 0,
2252                         "Extend", "Extend selection rather than clearing the existing selection");
2253         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2254                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2255 }
2256
2257 /* ******************** loop select operator **************** */
2258
2259 static int uv_select_loop_exec(bContext *C, wmOperator *op)
2260 {
2261         float co[2];
2262         bool extend, loop;
2263
2264         RNA_float_get_array(op->ptr, "location", co);
2265         extend = RNA_boolean_get(op->ptr, "extend");
2266         loop = true;
2267
2268         return uv_mouse_select(C, co, extend, loop);
2269 }
2270
2271 static int uv_select_loop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2272 {
2273         ARegion *ar = CTX_wm_region(C);
2274         float co[2];
2275
2276         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2277         RNA_float_set_array(op->ptr, "location", co);
2278
2279         return uv_select_loop_exec(C, op);
2280 }
2281
2282 static void UV_OT_select_loop(wmOperatorType *ot)
2283 {
2284         /* identifiers */
2285         ot->name = "Loop Select";
2286         ot->description = "Select a loop of connected UV vertices";
2287         ot->idname = "UV_OT_select_loop";
2288         ot->flag = OPTYPE_UNDO;
2289         
2290         /* api callbacks */
2291         ot->exec = uv_select_loop_exec;
2292         ot->invoke = uv_select_loop_invoke;
2293         ot->poll = ED_operator_uvedit; /* requires space image */;
2294
2295         /* properties */
2296         RNA_def_boolean(ot->srna, "extend", 0,
2297                         "Extend", "Extend selection rather than clearing the existing selection");
2298         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2299                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2300 }
2301
2302 /* ******************** linked select operator **************** */
2303
2304 static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent *event, int pick)
2305 {
2306         SpaceImage *sima = CTX_wm_space_image(C);
2307         Scene *scene = CTX_data_scene(C);
2308         ToolSettings *ts = scene->toolsettings;
2309         Object *obedit = CTX_data_edit_object(C);
2310         Image *ima = CTX_data_edit_image(C);
2311         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2312         float limit[2];
2313         int extend;
2314         bool select_faces = (ts->uv_flag & UV_SYNC_SELECTION) && (ts->selectmode & SCE_SELECT_FACE);
2315
2316         NearestHit hit, *hit_p = NULL;
2317
2318         if ((ts->uv_flag & UV_SYNC_SELECTION) && !(ts->selectmode & SCE_SELECT_FACE)) {
2319                 BKE_report(op->reports, RPT_ERROR, "Select linked only works in face select mode when sync selection is enabled");
2320                 return OPERATOR_CANCELLED;
2321         }
2322
2323         extend = RNA_boolean_get(op->ptr, "extend");
2324         uvedit_pixel_to_float(sima, limit, 0.05f);
2325
2326         if (pick) {
2327                 float co[2];
2328
2329                 if (event) {
2330                         /* invoke */
2331                         ARegion *ar = CTX_wm_region(C);
2332
2333                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2334                         RNA_float_set_array(op->ptr, "location", co);
2335                 }
2336                 else {
2337                         /* exec */
2338                         RNA_float_get_array(op->ptr, "location", co);
2339                 }
2340
2341                 uv_find_nearest_edge(scene, ima, em, co, &hit);
2342                 hit_p = &hit;
2343         }
2344
2345         uv_select_linked(scene, ima, em, limit, hit_p, extend, select_faces);
2346
2347         DEG_id_tag_update(obedit->data, 0);
2348         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2349
2350         return OPERATOR_FINISHED;
2351 }
2352
2353 static int uv_select_linked_exec(bContext *C, wmOperator *op)
2354 {
2355         return uv_select_linked_internal(C, op, NULL, 0);
2356 }
2357
2358 static void UV_OT_select_linked(wmOperatorType *ot)
2359 {
2360         /* identifiers */
2361         ot->name = "Select Linked";
2362         ot->description = "Select all UV vertices linked to the active UV map";
2363         ot->idname = "UV_OT_select_linked";
2364         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2365         
2366         /* api callbacks */
2367         ot->exec = uv_select_linked_exec;
2368         ot->poll = ED_operator_uvedit;    /* requires space image */
2369
2370         /* properties */
2371         RNA_def_boolean(ot->srna, "extend", 0,
2372                         "Extend", "Extend selection rather than clearing the existing selection");
2373 }
2374
2375 static int uv_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2376 {
2377         return uv_select_linked_internal(C, op, event, 1);
2378 }
2379
2380 static int uv_select_linked_pick_exec(bContext *C, wmOperator *op)
2381 {
2382         return uv_select_linked_internal(C, op, NULL, 1);
2383 }
2384
2385 static void UV_OT_select_linked_pick(wmOperatorType *ot)
2386 {
2387         /* identifiers */
2388         ot->name = "Select Linked Pick";
2389         ot->description = "Select all UV vertices linked under the mouse";
2390         ot->idname = "UV_OT_select_linked_pick";
2391         ot->flag = OPTYPE_UNDO;
2392
2393         /* api callbacks */
2394         ot->invoke = uv_select_linked_pick_invoke;
2395         ot->exec = uv_select_linked_pick_exec;
2396         ot->poll = ED_operator_uvedit; /* requires space image */;
2397
2398         /* properties */
2399         RNA_def_boolean(ot->srna, "extend", 0,
2400                         "Extend", "Extend selection rather than clearing the existing selection");
2401
2402         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
2403                              "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
2404 }
2405
2406 /* note: this is based on similar use case to MESH_OT_split(), which has a similar effect
2407  * but in this case they are not joined to begin with (only having the behavior of being joined)
2408  * so its best to call this uv_select_split() instead of just split(), but assigned to the same key
2409  * as MESH_OT_split - Campbell */
2410 static int uv_select_split_exec(bContext *C, wmOperator *op)
2411 {
2412         Scene *scene = CTX_data_scene(C);
2413         ToolSettings *ts = scene->toolsettings;
2414         Image *ima = CTX_data_edit_image(C);
2415         Object *obedit = CTX_data_edit_object(C);
2416         BMesh *bm = BKE_editmesh_from_object(obedit)->bm;
2417
2418         BMFace *efa;
2419         BMLoop *l;
2420         BMIter iter, liter;
2421         MLoopUV *luv;
2422         bool changed = false;
2423
2424         const int cd_loop_uv_offset  = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
2425
2426         if (ts->uv_flag & UV_SYNC_SELECTION) {
2427                 BKE_report(op->reports, RPT_ERROR, "Cannot split selection when sync selection is enabled");
2428                 return OPERATOR_CANCELLED;
2429         }
2430
2431
2432
2433         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
2434                 bool is_sel = false;
2435                 bool is_unsel = false;
2436
2437                 if (!uvedit_face_visible_test(scene, ima, efa))
2438                         continue;
2439
2440                 /* are we all selected? */
2441                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2442                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2443
2444                         if (luv->flag & MLOOPUV_VERTSEL) {
2445                                 is_sel = true;
2446                         }
2447                         else {
2448                                 is_unsel = true;
2449                         }
2450
2451                         /* we have mixed selection, bail out */
2452                         if (is_sel && is_unsel) {
2453                                 break;
2454                         }
2455                 }
2456
2457                 if (is_sel && is_unsel) {
2458                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2459                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2460                                 luv->flag &= ~MLOOPUV_VERTSEL;
2461                         }
2462
2463                         changed = true;
2464                 }
2465         }
2466
2467         if (changed) {
2468                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_IMAGE, NULL);
2469                 return OPERATOR_FINISHED;
2470         }
2471         else {
2472                 return OPERATOR_CANCELLED;
2473         }
2474 }
2475
2476
2477 static void UV_OT_select_split(wmOperatorType *ot)
2478 {
2479         /* identifiers */
2480         ot->name = "Select Split";
2481         ot->description = "Select only entirely selected faces";
2482         ot->idname = "UV_OT_select_split";
2483         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2484
2485         /* api callbacks */
2486         ot->exec = uv_select_split_exec;
2487         ot->poll = ED_operator_uvedit; /* requires space image */;
2488 }
2489
2490 static void uv_select_sync_flush(ToolSettings *ts, BMEditMesh *em, const short select)
2491 {
2492         /* bmesh API handles flushing but not on de-select */
2493         if (ts->uv_flag & UV_SYNC_SELECTION) {
2494                 if (ts->selectmode != SCE_SELECT_FACE) {
2495                         if (select == false) {
2496                                 EDBM_deselect_flush(em);
2497                         }
2498                         else {
2499                                 EDBM_select_flush(em);
2500                         }
2501                 }
2502
2503                 if (select == false) {
2504                         BM_select_history_validate(em->bm);
2505                 }
2506         }
2507 }
2508
2509
2510
2511 /* -------------------------------------------------------------------- */
2512 /* Utility functions to flush the uv-selection from tags */
2513
2514 /**
2515  * helper function for #uv_select_flush_from_tag_loop and uv_select_flush_from_tag_face
2516  */
2517 static void uv_select_flush_from_tag_sticky_loc_internal(Scene *scene, BMEditMesh *em, UvVertMap *vmap,
2518                                                          const unsigned int efa_index, BMLoop *l,
2519                                                          const bool select, const int cd_loop_uv_offset)
2520 {
2521         UvMapVert *start_vlist = NULL, *vlist_iter;
2522         BMFace *efa_vlist;
2523
2524         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2525
2526         vlist_iter = BM_uv_vert_map_at_index(vmap, BM_elem_index_get(l->v));
2527
2528         while (vlist_iter) {
2529                 if (vlist_iter->separate)
2530                         start_vlist = vlist_iter;
2531
2532                 if (efa_index == vlist_iter->f)
2533                         break;
2534
2535                 vlist_iter = vlist_iter->next;
2536         }
2537
2538         vlist_iter = start_vlist;
2539         while (vlist_iter) {
2540
2541                 if (vlist_iter != start_vlist && vlist_iter->separate)
2542                         break;
2543
2544                 if (efa_index != vlist_iter->f) {
2545                         BMLoop *l_other;
2546                         efa_vlist = BM_face_at_index(em->bm, vlist_iter->f);
2547                         /* tf_vlist = BM_ELEM_CD_GET_VOID_P(efa_vlist, cd_poly_tex_offset); */ /* UNUSED */
2548
2549                         l_other = BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex);
2550
2551                         uvedit_uv_select_set(em, scene, l_other, select, false, cd_loop_uv_offset);
2552                 }
2553                 vlist_iter = vlist_iter->next;
2554         }
2555 }
2556
2557 /**
2558  * Flush the selection from face tags based on sticky and selection modes.
2559  *
2560  * needed because settings the selection a face is done in a number of places but it also needs to respect
2561  * the sticky modes for the UV verts, so dealing with the sticky modes is best done in a separate function.
2562  *
2563  * \note! This function is very similar to #uv_select_flush_from_tag_loop, be sure to update both upon changing.
2564  */
2565 static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object *obedit, const bool select)
2566 {
2567         /* Selecting UV Faces with some modes requires us to change 
2568          * the selection in other faces (depending on the sticky mode).
2569          * 
2570          * This only needs to be done when the Mesh is not used for
2571          * selection (so for sticky modes, vertex or location based). */
2572         
2573         ToolSettings *ts = scene->toolsettings;
2574         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2575         BMFace *efa;
2576         BMLoop *l;
2577         BMIter iter, liter;
2578         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2579         
2580         if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
2581                 /* Tag all verts as untouched, then touch the ones that have a face center
2582                  * in the loop and select all MLoopUV's that use a touched vert. */
2583                 BMVert *eve;
2584                 
2585                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2586                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
2587                 }
2588                 
2589                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2590                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2591                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2592                                         BM_elem_flag_enable(l->v, BM_ELEM_TAG);
2593                                 }
2594                         }
2595                 }
2596
2597                 /* now select tagged verts */
2598                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2599                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2600
2601                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2602                                 if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
2603                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2604                                 }
2605                         }
2606                 }
2607         }
2608         else if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_LOC) {
2609                 struct UvVertMap *vmap;
2610                 float limit[2];
2611                 unsigned int efa_index;
2612                 
2613                 uvedit_pixel_to_float(sima, limit, 0.05);
2614                 
2615                 BM_mesh_elem_table_ensure(em->bm, BM_FACE);
2616                 vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
2617                 if (vmap == NULL) {
2618                         return;
2619                 }
2620                 
2621                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, efa_index) {
2622                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2623                                 /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2624                                 
2625                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2626                                         uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
2627                                                                                      select, cd_loop_uv_offset);
2628                                 }
2629                         }
2630                 }
2631                 BM_uv_vert_map_free(vmap);
2632                 
2633         }
2634         else { /* SI_STICKY_DISABLE or ts->uv_flag & UV_SYNC_SELECTION */
2635                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2636                         if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
2637                                 uvedit_face_select_set(scene, em, efa, select, false, cd_loop_uv_offset);
2638                         }
2639                 }
2640         }
2641 }
2642
2643
2644
2645 /**
2646  * Flush the selection from loop tags based on sticky and selection modes.
2647  *
2648  * needed because settings the selection a face is done in a number of places but it also needs to respect
2649  * the sticky modes for the UV verts, so dealing with the sticky modes is best done in a separate function.
2650  *
2651  * \note! This function is very similar to #uv_select_flush_from_tag_loop, be sure to update both upon changing.
2652  */
2653 static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object *obedit, const bool select)
2654 {
2655         /* Selecting UV Loops with some modes requires us to change
2656          * the selection in other faces (depending on the sticky mode).
2657          *
2658          * This only needs to be done when the Mesh is not used for
2659          * selection (so for sticky modes, vertex or location based). */
2660
2661         ToolSettings *ts = scene->toolsettings;
2662         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2663         BMFace *efa;
2664         BMLoop *l;
2665         BMIter iter, liter;
2666
2667         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2668
2669
2670         if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
2671                 /* Tag all verts as untouched, then touch the ones that have a face center
2672                  * in the loop and select all MLoopUV's that use a touched vert. */
2673                 BMVert *eve;
2674
2675                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2676                         BM_elem_flag_disable(eve, BM_ELEM_TAG);
2677                 }
2678
2679                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2680                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2681                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2682                                         BM_elem_flag_enable(l->v, BM_ELEM_TAG);
2683                                 }
2684                         }
2685                 }
2686
2687                 /* now select tagged verts */
2688                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2689                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2690
2691                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2692                                 if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
2693                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2694                                 }
2695                         }
2696                 }
2697         }
2698         else if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_LOC) {
2699                 struct UvVertMap *vmap;
2700                 float limit[2];
2701                 unsigned int efa_index;
2702
2703                 uvedit_pixel_to_float(sima, limit, 0.05);
2704
2705                 BM_mesh_elem_table_ensure(em->bm, BM_FACE);
2706                 vmap = BM_uv_vert_map_create(em->bm, limit, false, false);
2707                 if (vmap == NULL) {
2708                         return;
2709                 }
2710
2711                 BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, efa_index) {
2712                         /* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
2713
2714                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2715                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2716                                         uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
2717                                                                                      select, cd_loop_uv_offset);
2718                                 }
2719                         }
2720                 }
2721                 BM_uv_vert_map_free(vmap);
2722
2723         }
2724         else { /* SI_STICKY_DISABLE or ts->uv_flag & UV_SYNC_SELECTION */
2725                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2726                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2727                                 if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
2728                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2729                                 }
2730                         }
2731                 }
2732         }
2733 }
2734
2735 /* ******************** border select operator **************** */
2736
2737 static int uv_border_select_exec(bContext *C, wmOperator *op)
2738 {
2739         SpaceImage *sima = CTX_wm_space_image(C);
2740         Scene *scene = CTX_data_scene(C);
2741         ToolSettings *ts = scene->toolsettings;
2742         Object *obedit = CTX_data_edit_object(C);
2743         Image *ima = CTX_data_edit_image(C);
2744         ARegion *ar = CTX_wm_region(C);
2745         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2746         BMFace *efa;
2747         BMLoop *l;
2748         BMIter iter, liter;
2749         MLoopUV *luv;
2750         rctf rectf;
2751         bool changed, pinned, select, extend;
2752         const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
2753                                     (ts->selectmode == SCE_SELECT_FACE) :
2754                                     (ts->uv_selectmode == UV_SELECT_FACE);
2755
2756         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2757
2758         /* get rectangle from operator */
2759         WM_operator_properties_border_to_rctf(op, &rectf);
2760         UI_view2d_region_to_view_rctf(&ar->v2d, &rectf, &rectf);
2761
2762         /* figure out what to select/deselect */
2763         select = !RNA_boolean_get(op->ptr, "deselect");
2764         extend = RNA_boolean_get(op->ptr, "extend");
2765         pinned = RNA_boolean_get(op->ptr, "pinned");
2766
2767         if (!extend)
2768                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
2769
2770         /* do actual selection */
2771         if (use_face_center && !pinned) {
2772                 /* handle face selection mode */
2773                 float cent[2];
2774
2775                 changed = false;
2776
2777                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2778                         /* assume not touched */
2779                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
2780
2781                         if (uvedit_face_visible_test(scene, ima, efa)) {
2782                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
2783                                 if (BLI_rctf_isect_pt_v(&rectf, cent)) {
2784                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
2785                                         changed = true;
2786                                 }
2787                         }
2788                 }
2789
2790                 /* (de)selects all tagged faces and deals with sticky modes */
2791                 if (changed) {
2792                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
2793                 }
2794         }
2795         else {
2796                 /* other selection modes */
2797                 changed = true;
2798                 
2799                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2800                         if (!uvedit_face_visible_test(scene, ima, efa))
2801                                 continue;
2802                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2803                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2804
2805                                 if (!pinned || (ts->uv_flag & UV_SYNC_SELECTION)) {
2806
2807                                         /* UV_SYNC_SELECTION - can't do pinned selection */
2808                                         if (BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
2809                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2810                                         }
2811                                 }
2812                                 else if (pinned) {
2813                                         if ((luv->flag & MLOOPUV_PINNED) && BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
2814                                                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2815                                         }
2816                                 }
2817                         }
2818                 }
2819         }
2820
2821         if (changed) {
2822                 uv_select_sync_flush(ts, em, select);
2823
2824                 if (ts->uv_flag & UV_SYNC_SELECTION) {
2825                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2826                 }
2827                 
2828                 return OPERATOR_FINISHED;
2829         }
2830
2831         return OPERATOR_CANCELLED;
2832
2833
2834 static void UV_OT_select_border(wmOperatorType *ot)
2835 {
2836         /* identifiers */
2837         ot->name = "Border Select";
2838         ot->description = "Select UV vertices using border selection";
2839         ot->idname = "UV_OT_select_border";
2840         
2841         /* api callbacks */
2842         ot->invoke = WM_gesture_border_invoke;
2843         ot->exec = uv_border_select_exec;
2844         ot->modal = WM_gesture_border_modal;
2845         ot->poll = ED_operator_uvedit_space_image; /* requires space image */;
2846         ot->cancel = WM_gesture_border_cancel;
2847         
2848         /* flags */
2849         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2850         
2851         /* properties */
2852         RNA_def_boolean(ot->srna, "pinned", 0, "Pinned", "Border select pinned UVs only");
2853
2854         WM_operator_properties_gesture_border_select(ot);
2855 }
2856
2857 /* ******************** circle select operator **************** */
2858
2859 static int uv_inside_circle(const float uv[2], const float offset[2], const float ellipse[2])
2860 {
2861         /* normalized ellipse: ell[0] = scaleX, ell[1] = scaleY */
2862         float x, y;
2863         x = (uv[0] - offset[0]) * ellipse[0];
2864         y = (uv[1] - offset[1]) * ellipse[1];
2865         return ((x * x + y * y) < 1.0f);
2866 }
2867
2868 static bool uv_select_inside_ellipse(BMEditMesh *em, Scene *scene, const bool select,
2869                                      const float offset[2], const float ellipse[2], BMLoop *l, MLoopUV *luv,
2870                                      const int cd_loop_uv_offset)
2871 {
2872         if (uv_inside_circle(luv->uv, offset, ellipse)) {
2873                 uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
2874                 return true;
2875         }
2876         else {
2877                 return false;
2878         }
2879 }
2880
2881 static int uv_circle_select_exec(bContext *C, wmOperator *op)
2882 {
2883         SpaceImage *sima = CTX_wm_space_image(C);
2884         Scene *scene = CTX_data_scene(C);
2885         ToolSettings *ts = scene->toolsettings;
2886         Object *obedit = CTX_data_edit_object(C);
2887         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2888         ARegion *ar = CTX_wm_region(C);
2889         BMFace *efa;
2890         BMLoop *l;
2891         BMIter iter, liter;
2892         MLoopUV *luv;
2893         int x, y, radius, width, height;
2894         float zoomx, zoomy, offset[2], ellipse[2];
2895         const bool select = !RNA_boolean_get(op->ptr, "deselect");
2896         bool changed = false;
2897         const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
2898                                      (ts->selectmode == SCE_SELECT_FACE) :
2899                                      (ts->uv_selectmode == UV_SELECT_FACE);
2900
2901         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2902
2903         /* get operator properties */
2904         x = RNA_int_get(op->ptr, "x");
2905         y = RNA_int_get(op->ptr, "y");
2906         radius = RNA_int_get(op->ptr, "radius");
2907
2908         /* compute ellipse size and location, not a circle since we deal
2909          * with non square image. ellipse is normalized, r = 1.0. */
2910         ED_space_image_get_size(sima, &width, &height);
2911         ED_space_image_get_zoom(sima, ar, &zoomx, &zoomy);
2912
2913         ellipse[0] = width * zoomx / radius;
2914         ellipse[1] = height * zoomy / radius;
2915
2916         UI_view2d_region_to_view(&ar->v2d, x, y, &offset[0], &offset[1]);
2917         
2918         /* do selection */
2919         if (use_face_center) {
2920                 changed = false;
2921                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2922                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
2923                         /* assume not touched */
2924                         if (select != uvedit_face_select_test(scene, efa, cd_loop_uv_offset)) {
2925                                 float cent[2];
2926                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
2927                                 if (uv_inside_circle(cent, offset, ellipse)) {
2928                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
2929                                         changed = true;
2930                                 }
2931                         }
2932                 }
2933
2934                 /* (de)selects all tagged faces and deals with sticky modes */
2935                 if (changed) {
2936                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
2937                 }
2938         }
2939         else {
2940                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
2941                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
2942                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
2943                                 changed |= uv_select_inside_ellipse(em, scene, select, offset, ellipse, l, luv, cd_loop_uv_offset);
2944                         }
2945                 }
2946         }
2947
2948         if (changed) {
2949                 uv_select_sync_flush(ts, em, select);
2950
2951                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
2952         }
2953
2954         return OPERATOR_FINISHED;
2955 }
2956
2957 static void UV_OT_circle_select(wmOperatorType *ot)
2958 {
2959         /* identifiers */
2960         ot->name = "Circle Select";
2961         ot->description = "Select UV vertices using circle selection";
2962         ot->idname = "UV_OT_circle_select";
2963         
2964         /* api callbacks */
2965         ot->invoke = WM_gesture_circle_invoke;
2966         ot->modal = WM_gesture_circle_modal;
2967         ot->exec = uv_circle_select_exec;
2968         ot->poll = ED_operator_uvedit_space_image; /* requires space image */;
2969         ot->cancel = WM_gesture_circle_cancel;
2970         
2971         /* flags */
2972         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2973
2974         /* properties */
2975         WM_operator_properties_gesture_circle_select(ot);
2976 }
2977
2978
2979 /* ******************** lasso select operator **************** */
2980
2981 static bool do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short moves,
2982                                     const bool select, const bool extend)
2983 {
2984         SpaceImage *sima = CTX_wm_space_image(C);
2985         Image *ima = CTX_data_edit_image(C);
2986         ARegion *ar = CTX_wm_region(C);
2987         Object *obedit = CTX_data_edit_object(C);
2988         Scene *scene = CTX_data_scene(C);
2989         ToolSettings *ts = scene->toolsettings;
2990         BMEditMesh *em = BKE_editmesh_from_object(obedit);
2991         const bool use_face_center = (
2992                 (ts->uv_flag & UV_SYNC_SELECTION) ?
2993                 (ts->selectmode == SCE_SELECT_FACE) :
2994                 (ts->uv_selectmode == UV_SELECT_FACE));
2995
2996         const int cd_loop_uv_offset  = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2997
2998         BMIter iter, liter;
2999
3000         BMFace *efa;
3001         BMLoop *l;
3002         int screen_uv[2];
3003         bool changed = false;
3004         rcti rect;
3005
3006         BLI_lasso_boundbox(&rect, mcords, moves);
3007
3008         if (!extend && select) {
3009                 uv_select_all_perform(scene, ima, em, SEL_DESELECT);
3010         }
3011
3012         if (use_face_center) { /* Face Center Sel */
3013                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
3014                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
3015                         /* assume not touched */
3016                         if (select != uvedit_face_select_test(scene, efa, cd_loop_uv_offset)) {
3017                                 float cent[2];
3018                                 uv_poly_center(efa, cent, cd_loop_uv_offset);
3019
3020                                 if (UI_view2d_view_to_region_clip(&ar->v2d, cent[0], cent[1], &screen_uv[0], &screen_uv[1]) &&
3021                                     BLI_rcti_isect_pt_v(&rect, screen_uv) &&
3022                                     BLI_lasso_is_point_inside(mcords, moves, screen_uv[0], screen_uv[1], V2D_IS_CLIPPED))
3023                                 {
3024                                         BM_elem_flag_enable(efa, BM_ELEM_TAG);
3025                                         changed = true;
3026                                 }
3027                         }
3028                 }
3029
3030                 /* (de)selects all tagged faces and deals with sticky modes */
3031                 if (changed) {
3032                         uv_select_flush_from_tag_face(sima, scene, obedit, select);
3033                 }
3034         }
3035         else { /* Vert Sel */
3036                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
3037                         if (uvedit_face_visible_test(scene, ima, efa)) {
3038                                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
3039                                         if ((select) != (uvedit_uv_select_test(scene, l, cd_loop_uv_offset))) {
3040                                                 MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
3041                                                 if (UI_view2d_view_to_region_clip(&ar->v2d,
3042                                                                                   luv->uv[0], luv->uv[1],
3043                                                                                   &screen_uv[0], &screen_uv[1]) &&
3044                                                     BLI_rcti_isect_pt_v(&rect, screen_uv) &&
3045                                                     BLI_lasso_is_point_inside(mcords, moves, screen_uv[0], screen_uv[1], V2D_IS_CLIPPED))
3046                                                 {
3047                                                         uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
3048                                                         changed = true;
3049                                                 }
3050                                         }
3051                                 }
3052                         }
3053                 }
3054         }
3055
3056         if (changed) {
3057                 uv_select_sync_flush(scene->toolsettings, em, select);
3058
3059                 if (ts->uv_flag & UV_SYNC_SELECTION) {
3060                         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
3061                 }
3062         }
3063
3064         return changed;
3065 }
3066
3067 static int uv_lasso_select_exec(bContext *C, wmOperator *op)
3068 {
3069         int mcords_tot;
3070         const int (*mcords)[2] = WM_gesture_lasso_path_to_array(C, op, &mcords_tot);
3071
3072         if (mcords) {
3073                 bool select, extend;
3074                 bool changed;
3075
3076                 select = !RNA_boolean_get(op->ptr, "deselect");
3077                 extend = RNA_boolean_get(op->ptr, "extend");
3078                 changed = do_lasso_select_mesh_uv(C, mcords, mcords_tot, select, extend);
3079
3080                 MEM_freeN((void *)mcords);
3081
3082                 return changed ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
3083         }
3084
3085         return OPERATOR_PASS_THROUGH;
3086 }
3087
3088 static void UV_OT_select_lasso(wmOperatorType *ot)
3089 {
3090         ot->name = "Lasso Select UV";
3091         ot->description = "Select UVs using lasso selection";
3092         ot->idname = "UV_OT_select_lasso";
3093
3094         ot->invoke = WM_gesture_lasso_invoke;
3095         ot->modal = WM_gesture_lasso_modal;
3096         ot->exec = uv_lasso_select_exec;
3097         ot->poll = ED_operator_uvedit_space_image;
3098         ot->cancel = WM_gesture_lasso_cancel;
3099
3100         /* flags */
3101         ot->flag = OPTYPE_UNDO;
3102
3103         /* properties */
3104         WM_operator_properties_gesture_lasso_select(ot);
3105 }
3106
3107
3108
3109 /* ******************** snap cursor operator **************** */
3110
3111 static void uv_snap_to_pixel(float uvco[2], float w, float h)
3112 {
3113         uvco[0] = roundf(uvco[0] * w) / w;
3114         uvco[1] = roundf(uvco[1] * h) / h;
3115 }
3116
3117</