Stitch tool fully functional again. Many thanks to Howard Trickey for proposing the...
[blender-staging.git] / source / blender / editors / uvedit / uvedit_smart_stitch.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_stitch.c
29  *  \ingroup eduv
30  */
31
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_object_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_ghash.h"
45 #include "BLI_math.h"
46 #include "BLI_math_vector.h"
47 #include "BLI_string.h"
48
49 #include "BKE_context.h"
50 #include "BKE_customdata.h"
51 #include "BKE_depsgraph.h"
52 #include "BKE_mesh.h"
53 #include "BKE_tessmesh.h"
54
55 #include "ED_mesh.h"
56 #include "ED_uvedit.h"
57 #include "ED_screen.h"
58
59 #include "RNA_access.h"
60 #include "RNA_define.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "UI_view2d.h"
66
67 #include "uvedit_intern.h"
68
69 /* ********************** smart stitch operator *********************** */
70
71
72 struct IslandStitchData;
73
74 /* This is a straightforward implementation, count the uv's in the island that will move and take the mean displacement/rotation and apply it to all
75  * elements of the island except from the stitchable */
76 typedef struct IslandStitchData{
77         /* rotation can be used only for edges, for vertices there is no such notion */
78         float rotation;
79         float translation[2];
80         /* Used for rotation, the island will rotate around this point */
81         float medianPoint[2];
82         int numOfElements;
83         int num_rot_elements;
84         /* flag to remember if island has been added for preview */
85         char addedForPreview;
86         /* flag an island to be considered for determining static island */
87         char stitchableCandidate;
88         /* if edge rotation is used, flag so that vertex rotation is not used */
89         char use_edge_rotation;
90 }IslandStitchData;
91
92 /* just for averaging UVs */
93 typedef struct UVVertAverage {
94         float uv[2];
95         unsigned short count;
96 } UVVertAverage;
97
98 typedef struct UvEdge {
99         /* index to uv buffer */
100         unsigned int uv1;
101         unsigned int uv2;
102         /* general use flag (Used to check if edge is boundary here, and propagates to adjacency elements) */
103         char flag;
104         /* element that guarantees element->face has the face on element->tfindex and element->tfindex+1 is the second uv */
105         UvElement *element;
106 }UvEdge;
107
108
109 /* stitch state object */
110 typedef struct StitchState {
111         /* use limit flag */
112         char use_limit;
113         /* limit to operator, same as original operator */
114         float limit_dist;
115         /* snap uv islands together during stitching */
116         char snap_islands;
117         /* stich at midpoints or at islands */
118         char midpoints;
119         /* editmesh, cached for use in modal handler */
120         BMEditMesh *em;
121         /* element map for getting info about uv connectivity */
122         UvElementMap *element_map;
123         /* edge container */
124         UvEdge *uvedges;
125         /* container of first of a group of coincident uvs, these will be operated upon */
126         UvElement **uvs;
127         /* maps uvelements to their first coincident uv */
128         int *map;
129         /* 2D normals per uv to calculate rotation for snapping */
130         float *normals;
131         /* edge storage */
132         UvEdge *edges;
133
134         /* count of separate uvs and edges */
135         int total_boundary_edges;
136         int total_separate_uvs;
137         /* hold selection related information */
138         UvElement **selection_stack;
139         int selection_size;
140         /* island that stays in place */
141         int static_island;
142         /* store number of primitives per face so that we can allocate the active island buffer later */
143         unsigned int *tris_per_island;
144 } StitchState;
145
146 typedef struct PreviewPosition{
147         int data_position;
148         int polycount_position;
149 }PreviewPosition;
150 /*
151  * defines for UvElement flags
152  */
153 #define STITCH_SELECTED 1
154 #define STITCH_STITCHABLE 2
155 #define STITCH_PROCESSED 4
156 #define STITCH_BOUNDARY 8
157 #define STITCH_STITCHABLE_CANDIDATE 16
158
159 #define STITCH_NO_PREVIEW -1
160
161 /* previewer stuff (see uvedit_intern.h for more info) */
162 static StitchPreviewer *_stitch_preview;
163
164 /* constructor */
165 static StitchPreviewer * stitch_preview_init(void)
166 {
167         _stitch_preview = MEM_mallocN(sizeof(StitchPreviewer), "stitch_previewer");
168         _stitch_preview->preview_polys = NULL;
169         _stitch_preview->preview_stitchable = NULL;
170         _stitch_preview->preview_unstitchable = NULL;
171         _stitch_preview->uvs_per_polygon = NULL;
172
173         _stitch_preview->preview_uvs = 0;
174         _stitch_preview->num_polys = 0;
175         _stitch_preview->num_stitchable = 0;
176         _stitch_preview->num_unstitchable = 0;
177
178         _stitch_preview->static_tris = NULL;
179
180         _stitch_preview->num_static_tris = 0;
181
182         return _stitch_preview;
183 }
184
185 /* destructor...yeah this should be C++ :) */
186 static void stitch_preview_delete(void)
187 {
188         if(_stitch_preview)
189         {
190                 if(_stitch_preview->preview_polys){
191                         MEM_freeN(_stitch_preview->preview_polys);
192                         _stitch_preview->preview_polys = NULL;
193                 }
194                 if(_stitch_preview->uvs_per_polygon){
195                         MEM_freeN(_stitch_preview->uvs_per_polygon);
196                         _stitch_preview->uvs_per_polygon = NULL;
197                 }
198                 if(_stitch_preview->preview_stitchable){
199                         MEM_freeN(_stitch_preview->preview_stitchable);
200                         _stitch_preview->preview_stitchable = NULL;
201                 }
202                 if(_stitch_preview->preview_unstitchable){
203                         MEM_freeN(_stitch_preview->preview_unstitchable);
204                         _stitch_preview->preview_unstitchable = NULL;
205                 }
206                 if(_stitch_preview->static_tris){
207                         MEM_freeN(_stitch_preview->static_tris);
208                         _stitch_preview->static_tris = NULL;
209                 }
210
211                 MEM_freeN(_stitch_preview);
212                 _stitch_preview = NULL;
213         }
214 }
215
216
217 /* "getter method" */
218 StitchPreviewer *uv_get_stitch_previewer(void)
219 {
220         return _stitch_preview;
221 }
222
223 #define HEADER_LENGTH 256
224
225 /* This function updates the header of the UV editor when the stitch tool updates its settings */
226 static void stitch_update_header(StitchState *stitch_state, bContext *C)
227 {
228         static char str[] = "(S)nap %s, (M)idpoints %s, (L)imit %.2f (Alt Wheel adjust) %s, Switch (I)sland, shift select vertices";
229
230         char msg[HEADER_LENGTH];
231         ScrArea *sa= CTX_wm_area(C);
232
233         if(sa) {
234                 BLI_snprintf(msg, HEADER_LENGTH, str,
235                                 stitch_state->snap_islands? "On" : "Off",
236                                 stitch_state->midpoints? "On": "Off",
237                                 stitch_state->limit_dist,
238                                 stitch_state->use_limit? "On" : "Off");
239
240                 ED_area_headerprint(sa, msg);
241         }
242 }
243
244 static int getNumOfIslandUvs(UvElementMap *elementMap, int island){
245         if(island == elementMap->totalIslands-1){
246                 return elementMap->totalUVs - elementMap->islandIndices[island];
247         }else{
248                 return elementMap->islandIndices[island+1] - elementMap->islandIndices[island];
249         }
250 }
251
252 static void stitch_uv_rotate(float rotation, float medianPoint[2], float uv[2]){
253         float uv_rotation_result[2];
254
255         uv[0] -= medianPoint[0];
256         uv[1] -= medianPoint[1];
257
258         uv_rotation_result[0] = cos(rotation)*uv[0] - sin(rotation)*uv[1];
259         uv_rotation_result[1] = sin(rotation)*uv[0] + cos(rotation)*uv[1];
260
261         uv[0] = uv_rotation_result[0] + medianPoint[0];
262         uv[1] = uv_rotation_result[1] + medianPoint[1];
263 }
264
265 static int stitch_check_uvs_stitchable(UvElement *element, UvElement *element_iter, StitchState *state){
266         float limit;
267         int do_limit;
268
269         if(element_iter == element){
270                 return 0;
271         }
272
273         limit = state->limit_dist;
274         do_limit = state->use_limit;
275
276         if(do_limit){
277                 MLoopUV *luv_orig, *luv_iter;
278                 BMLoop *l_orig, *l_iter;
279
280
281                 l_orig = element->l;
282                 luv_orig = CustomData_bmesh_get(&state->em->bm->ldata, l_orig->head.data, CD_MLOOPUV);
283                 l_iter = element_iter->l;
284                 luv_iter = CustomData_bmesh_get(&state->em->bm->ldata, l_iter->head.data, CD_MLOOPUV);
285
286                 if(fabs(luv_orig->uv[0] - luv_iter->uv[0]) < limit
287                         && fabs(luv_orig->uv[1] - luv_iter->uv[1]) < limit){
288                         return 1;
289                 }else
290                         return 0;
291         }else
292                 return 1;
293 }
294
295
296 static int stitch_check_uvs_state_stitchable(UvElement *element, UvElement *element_iter, StitchState *state){
297         if((state->snap_islands && element->island == element_iter->island) ||
298                         (!state->midpoints && element->island == element_iter->island))
299                 return 0;
300
301         return stitch_check_uvs_stitchable(element, element_iter, state);
302 }
303
304
305 /* calculate snapping for islands */
306 static void stitch_calculate_island_snapping(StitchState *state, PreviewPosition *preview_position, StitchPreviewer *preview, IslandStitchData *island_stitch_data, int final){
307         int i;
308         UvElement *element;
309
310         for(i = 0; i <  state->element_map->totalIslands; i++){
311                 if(island_stitch_data[i].addedForPreview){
312                         int numOfIslandUVs = 0, j;
313
314                         /* check to avoid divide by 0 */
315                         if(island_stitch_data[i].num_rot_elements>0){
316                                 island_stitch_data[i].rotation /= island_stitch_data[i].num_rot_elements;
317                                 island_stitch_data[i].medianPoint[0] /= island_stitch_data[i].numOfElements;
318                                 island_stitch_data[i].medianPoint[1] /= island_stitch_data[i].numOfElements;
319                         }
320                         island_stitch_data[i].translation[0] /= island_stitch_data[i].numOfElements;
321                         island_stitch_data[i].translation[1] /= island_stitch_data[i].numOfElements;
322                         numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
323                         element = &state->element_map->buf[state->element_map->islandIndices[i]];
324                         for(j = 0; j < numOfIslandUVs; j++, element++){
325                                 /* stitchable uvs have already been processed, don't process */
326                                 if(!(element->flag & STITCH_PROCESSED)){
327                                         MLoopUV *luv;
328                                         BMLoop *l;
329
330                                         l = element->l;
331                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
332
333                                         if(final){
334
335                                                 stitch_uv_rotate(island_stitch_data[i].rotation, island_stitch_data[i].medianPoint, luv->uv);
336
337                                                 add_v2_v2(luv->uv, island_stitch_data[i].translation);
338                                         }
339
340                                         else {
341                                                 int face_preview_pos = preview_position[BM_elem_index_get(element->face)].data_position;
342
343                                                 stitch_uv_rotate(island_stitch_data[i].rotation, island_stitch_data[i].medianPoint,
344                                                                 preview->preview_polys + face_preview_pos + 2*element->tfindex);
345
346                                                 add_v2_v2(preview->preview_polys + face_preview_pos + 2*element->tfindex,
347                                                                 island_stitch_data[i].translation);
348                                         }
349                                 }
350                                 /* cleanup */
351                                 element->flag &= STITCH_SELECTED;
352                         }
353                 }
354         }
355 }
356
357
358
359 static void stitch_island_calculate_edge_rotation(UvEdge *edge, StitchState *state, UVVertAverage *uv_average, unsigned int *uvfinal_map, IslandStitchData *island_stitch_data)
360 {
361         UvElement *element1, *element2;
362         float uv1[2], uv2[2];
363         float edgecos, edgesin;
364         int index1, index2;
365         float rotation;
366         MLoopUV *luv1, *luv2;
367         BMLoop *l1, *l2;
368
369         element1 = state->uvs[edge->uv1];
370         element2 = state->uvs[edge->uv2];
371
372         l1 = element1->l;
373         luv1 = CustomData_bmesh_get(&state->em->bm->ldata, l1->head.data, CD_MLOOPUV);
374         l2 = element2->l;
375         luv2 = CustomData_bmesh_get(&state->em->bm->ldata, l2->head.data, CD_MLOOPUV);
376
377         index1 = uvfinal_map[element1 - state->element_map->buf];
378         index2 = uvfinal_map[element2 - state->element_map->buf];
379
380         /* the idea here is to take the directions of the edges and find the rotation between final and initial
381         * direction. This, using inner and outer vector products, gives the angle. Directions are differences so... */
382         uv1[0] = luv2->uv[0] - luv1->uv[0];
383         uv1[1] = luv2->uv[1] - luv1->uv[1];
384
385         uv2[0] = uv_average[index2].uv[0] - uv_average[index1].uv[0];
386         uv2[1] = uv_average[index2].uv[1] - uv_average[index1].uv[1];
387
388         normalize_v2(uv1);
389         normalize_v2(uv2);
390
391         edgecos = uv1[0]*uv2[0] + uv1[1]*uv2[1];
392         edgesin = uv1[0]*uv2[1] - uv2[0]*uv1[1];
393
394         rotation = (edgesin > 0)? acos(MAX2(-1.0, MIN2(1.0, edgecos))): -acos(MAX2(-1.0, MIN2(1.0, edgecos)));
395
396         island_stitch_data[element1->island].num_rot_elements++;
397         island_stitch_data[element1->island].rotation += rotation;
398 }
399
400
401 static void stitch_island_calculate_vert_rotation(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data)
402 {
403         float edgecos = 1, edgesin = 0;
404         int index;
405         UvElement *element_iter;
406         float rotation = 0;
407         BMLoop *l;
408
409         if(element->island == state->static_island && !state->midpoints)
410                 return;
411
412         l = element->l;
413
414         index = BM_elem_index_get(l->v);
415
416         element_iter = state->element_map->vert[index];
417
418         for(; element_iter; element_iter = element_iter->next){
419                 if(element_iter->separate && stitch_check_uvs_state_stitchable(element, element_iter, state)){
420                         int index_tmp1, index_tmp2;
421                         float normal[2];
422                         /* easily possible*/
423
424                         index_tmp1 = element_iter - state->element_map->buf;
425                         index_tmp1 = state->map[index_tmp1];
426                         index_tmp2 = element - state->element_map->buf;
427                         index_tmp2 = state->map[index_tmp2];
428
429                         negate_v2_v2(normal, state->normals + index_tmp2*2);
430                         edgecos = dot_v2v2(normal, state->normals + index_tmp1*2);
431                         edgesin = cross_v2v2(normal, state->normals + index_tmp1*2);
432                         rotation += (edgesin > 0)? acos(edgecos): -acos(edgecos);
433                 }
434         }
435
436         if(state->midpoints)
437                 rotation /= 2.0;
438         island_stitch_data[element->island].num_rot_elements++;
439         island_stitch_data[element->island].rotation += rotation;
440 }
441
442
443 static void stitch_state_delete(StitchState *stitch_state)
444 {
445         if(stitch_state){
446                 if(stitch_state->element_map){
447                         EDBM_free_uv_element_map(stitch_state->element_map);
448                 }
449                 if(stitch_state->uvs){
450                         MEM_freeN(stitch_state->uvs);
451                 }
452                 if(stitch_state->selection_stack){
453                         MEM_freeN(stitch_state->selection_stack);
454                 }
455                 if(stitch_state->tris_per_island){
456                         MEM_freeN(stitch_state->tris_per_island);
457                 }
458                 if(stitch_state->map){
459                         MEM_freeN(stitch_state->map);
460                 }
461                 if(stitch_state->normals){
462                         MEM_freeN(stitch_state->normals);
463                 }
464                 if(stitch_state->edges){
465                         MEM_freeN(stitch_state->edges);
466                 }
467                 MEM_freeN(stitch_state);
468         }
469 }
470
471
472
473 /* checks for remote uvs that may be stitched with a certain uv, flags them if stitchable. */
474 static void determine_uv_stitchability(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data){
475         int vert_index;
476         UvElement *element_iter;
477         BMLoop *l;
478
479         l = element->l;
480
481         vert_index = BM_elem_index_get(l->v);
482         element_iter = state->element_map->vert[vert_index];
483
484         for(; element_iter; element_iter = element_iter->next){
485                 if(element_iter->separate){
486                         if(element_iter == element){
487                                 continue;
488                         }
489                         if(stitch_check_uvs_stitchable(element, element_iter, state)){
490                                 island_stitch_data[element_iter->island].stitchableCandidate = 1;
491                                 island_stitch_data[element->island].stitchableCandidate = 1;
492                                 element->flag |= STITCH_STITCHABLE_CANDIDATE;
493                         }
494                 }
495         }
496 }
497
498
499 /* set preview buffer position of UV face in editface->tmp.l */
500 static void stitch_set_face_preview_buffer_position(BMFace *efa, StitchPreviewer *preview, PreviewPosition *preview_position)
501 {
502         int index = BM_elem_index_get(efa);
503
504         if(preview_position[index].data_position == STITCH_NO_PREVIEW)
505         {
506                 preview_position[index].data_position = preview->preview_uvs*2;
507                 preview_position[index].polycount_position = preview->num_polys++;
508                 preview->preview_uvs += efa->len;
509         }
510 }
511
512
513 /* setup face preview for all coincident uvs and their faces */
514 static void stitch_setup_face_preview_for_uv_group(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
515                 PreviewPosition *preview_position){
516         StitchPreviewer *preview = uv_get_stitch_previewer();
517
518         /* static island does not change so returning immediately */
519         if(state->snap_islands && !state->midpoints && state->static_island == element->island)
520                 return;
521
522         if(state->snap_islands){
523                 island_stitch_data[element->island].addedForPreview = 1;
524         }
525
526         do{
527                 stitch_set_face_preview_buffer_position(element->face, preview, preview_position);
528                 element = element->next;
529         }while(element && !element->separate);
530 }
531
532
533 /* checks if uvs are indeed stitchable and registers so that they can be shown in preview */
534 static void stitch_validate_stichability (UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
535                 PreviewPosition *preview_position){
536         UvElement *element_iter;
537         StitchPreviewer *preview;
538         int vert_index;
539         BMLoop *l;
540
541         l = element->l;
542
543         vert_index = BM_elem_index_get(l->v);
544
545         preview = uv_get_stitch_previewer();
546         element_iter = state->element_map->vert[vert_index];
547
548         for(; element_iter; element_iter = element_iter->next){
549                 if(element_iter->separate){
550                         if(element_iter == element)
551                                 continue;
552                         if(stitch_check_uvs_state_stitchable(element, element_iter, state)){
553                                 if((element_iter->island == state->static_island) || (element->island == state->static_island)){
554                                         element->flag |= STITCH_STITCHABLE;
555                                         preview->num_stitchable++;
556                                         stitch_setup_face_preview_for_uv_group(element, state, island_stitch_data, preview_position);
557                                         return;
558                                 }
559                         }
560                 }
561         }
562
563         /* this can happen if the uvs to be stitched are not on a stitchable island */
564         if(!(element->flag & STITCH_STITCHABLE)){
565                 preview->num_unstitchable++;
566         }
567 }
568
569 /* main processing function. It calculates preview and final positions. */
570 static int stitch_process_data(StitchState *state, Scene *scene, int final)
571 {
572         int i;
573         StitchPreviewer *preview;
574         IslandStitchData *island_stitch_data = NULL;
575         int previous_island = state->static_island;
576         BMFace *efa;
577         BMIter iter;
578         UVVertAverage *final_position;
579         char stitch_midpoints = state->midpoints;
580         /* used to map uv indices to uvaverage indices for selection */
581         unsigned int *uvfinal_map;
582         /* per face preview position in preview buffer */
583         PreviewPosition *preview_position;
584
585         /* cleanup previous preview */
586         stitch_preview_delete();
587         preview = stitch_preview_init();
588         if(preview == NULL)
589                 return 0;
590
591         preview_position = MEM_mallocN(state->em->bm->totface*sizeof(*preview_position), "stitch_face_preview_position");
592         /* each face holds its position in the preview buffer in tmp. -1 is uninitialized */
593         for(i = 0; i < state->em->bm->totface; i++){
594                 preview_position[i].data_position = STITCH_NO_PREVIEW;
595         }
596
597         island_stitch_data = MEM_callocN(sizeof(*island_stitch_data)*state->element_map->totalIslands, "stitch_island_data");
598         if(!island_stitch_data){
599                 return 0;
600         }
601
602         /* store indices to editVerts and Faces. May be unneeded but ensuring anyway */
603         BM_mesh_elem_index_ensure(state->em->bm, BM_VERT | BM_FACE);
604
605         /*****************************************
606          *  First determine stitchability of uvs *
607          *****************************************/
608
609         for(i = 0; i < state->selection_size; i++){
610                 UvElement *element = state->selection_stack[i];
611                 determine_uv_stitchability(element, state, island_stitch_data);
612         }
613
614         /* set static island to one that is added for preview */
615         state->static_island %= state->element_map->totalIslands;
616         while(!(island_stitch_data[state->static_island].stitchableCandidate)){
617                 state->static_island++;
618                 state->static_island %= state->element_map->totalIslands;
619                 /* this is entirely possible if for example limit stitching with no stitchable verts or no selection */
620                 if(state->static_island == previous_island)
621                         break;
622         }
623
624         for(i = 0; i < state->selection_size; i++){
625                 UvElement *element = state->selection_stack[i];
626                 if(element->flag & STITCH_STITCHABLE_CANDIDATE){
627                         element->flag &= ~STITCH_STITCHABLE_CANDIDATE;
628                         stitch_validate_stichability(element, state, island_stitch_data, preview_position);
629                 }else{
630                         /* add to preview for unstitchable */
631                         preview->num_unstitchable++;
632                 }
633         }
634
635         /*****************************************
636          *  Setup preview for stitchable islands *
637          *****************************************/
638         if(state->snap_islands){
639                 for(i = 0; i <  state->element_map->totalIslands; i++){
640                         if(island_stitch_data[i].addedForPreview){
641                                 int numOfIslandUVs = 0, j;
642                                 UvElement *element;
643                                 numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
644                                 element = &state->element_map->buf[state->element_map->islandIndices[i]];
645                                 for(j = 0; j < numOfIslandUVs; j++, element++){
646                                         stitch_set_face_preview_buffer_position(element->face, preview, preview_position);
647                                 }
648                         }
649                 }
650         }
651
652         /*********************************************************************
653          * Setup the preview buffers and fill them with the appropriate data *
654          *********************************************************************/
655         if(!final){
656                 BMIter liter;
657                 BMLoop *l;
658                 MLoopUV *luv;
659                 unsigned int buffer_index = 0;
660                 int stitchBufferIndex = 0, unstitchBufferIndex = 0;
661                 /* initialize the preview buffers */
662                 preview->preview_polys = (float *)MEM_mallocN(preview->preview_uvs*sizeof(float)*2, "tri_uv_stitch_prev");
663                 preview->uvs_per_polygon = MEM_mallocN(preview->num_polys*sizeof(*preview->uvs_per_polygon), "tri_uv_stitch_prev");
664                 preview->preview_stitchable = (float *)MEM_mallocN(preview->num_stitchable*sizeof(float)*2, "stitch_preview_stichable_data");
665                 preview->preview_unstitchable = (float *)MEM_mallocN(preview->num_unstitchable*sizeof(float)*2, "stitch_preview_unstichable_data");
666
667                 preview->static_tris = (float *)MEM_mallocN(state->tris_per_island[state->static_island]*sizeof(float)*6, "static_island_preview_tris");
668
669                 preview->num_static_tris = state->tris_per_island[state->static_island];
670                 /* will cause cancel and freeing of all data structures so OK */
671                 if(!preview->preview_polys || !preview->preview_stitchable || !preview->preview_unstitchable){
672                         return 0;
673                 }
674
675                 /* copy data from MTFaces to the preview display buffers */
676                 BM_ITER(efa, &iter, state->em->bm, BM_FACES_OF_MESH, NULL) {
677                         /* just to test if face was added for processing. uvs of inselected vertices will return NULL */
678                         UvElement *element = ED_get_uv_element(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
679
680                         if(element){
681                                 int numoftris = efa->len - 2;
682                                 int index = BM_elem_index_get(efa);
683                                 int face_preview_pos = preview_position[index].data_position;
684                                 if(face_preview_pos != STITCH_NO_PREVIEW){
685                                         preview->uvs_per_polygon[preview_position[index].polycount_position] = efa->len;
686                                         BM_ITER_INDEX(l, &liter, state->em->bm, BM_LOOPS_OF_FACE, efa, i) {
687                                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
688                                                 copy_v2_v2(preview->preview_polys + face_preview_pos + i*2, luv->uv);
689                                         }
690                                 }
691
692                                 if(element->island == state->static_island){
693                                         BMLoop *fl = BM_FACE_FIRST_LOOP(efa);
694                                         MLoopUV *fuv = CustomData_bmesh_get(&state->em->bm->ldata, fl->head.data, CD_MLOOPUV);
695
696                                         BM_ITER_INDEX(l, &liter, state->em->bm, BM_LOOPS_OF_FACE, efa, i) {
697                                                 if(i < numoftris){
698                                                         /* using next since the first uv is already accounted for */
699                                                         BMLoop *lnext = l->next;
700                                                         MLoopUV *luvnext = CustomData_bmesh_get(&state->em->bm->ldata, lnext->next->head.data, CD_MLOOPUV);;
701                                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, lnext->head.data, CD_MLOOPUV);
702
703                                                         memcpy(preview->static_tris + buffer_index, fuv->uv, 2*sizeof(float));
704                                                         memcpy(preview->static_tris + buffer_index + 2, luv->uv, 2*sizeof(float));
705                                                         memcpy(preview->static_tris + buffer_index + 4, luvnext->uv, 2*sizeof(float));
706                                                         buffer_index += 6;
707                                                 }else break;
708                                         }
709                                 }
710                         }
711                 }
712
713                 /* fill the appropriate preview buffers */
714                 for(i = 0; i < state->total_separate_uvs; i++){
715                         UvElement *element = (UvElement *)state->uvs[i];
716                         if(element->flag & STITCH_STITCHABLE){
717                                 l = element->l;
718                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
719
720                                 copy_v2_v2(&preview->preview_stitchable[stitchBufferIndex*2], luv->uv);
721
722                                 stitchBufferIndex++;
723                         }
724                         else if(element->flag & STITCH_SELECTED){
725                                 l = element->l;
726                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
727
728                                 copy_v2_v2(&preview->preview_unstitchable[unstitchBufferIndex*2], luv->uv);
729                                 unstitchBufferIndex++;
730                         }
731                 }
732         }
733
734         /******************************************************
735          * Here we calculate the final coordinates of the uvs *
736          ******************************************************/
737
738         final_position = MEM_callocN(state->selection_size*sizeof(*final_position), "stitch_uv_average");
739         uvfinal_map = MEM_mallocN(state->element_map->totalUVs*sizeof(*uvfinal_map), "stitch_uv_final_map");
740
741         /* first pass, calculate final position for stitchable uvs of the static island */
742         for(i = 0; i < state->selection_size; i++){
743                 UvElement *element = state->selection_stack[i];
744                 if(element->flag & STITCH_STITCHABLE){
745                         BMLoop *l;
746                         MLoopUV *luv;
747                         UvElement *element_iter;
748
749                         l = element->l;
750                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
751
752
753                         uvfinal_map[element - state->element_map->buf] = i;
754
755                         copy_v2_v2(final_position[i].uv, luv->uv);
756                         final_position[i].count = 1;
757
758                         if(state->snap_islands && element->island == state->static_island && !stitch_midpoints)
759                                 continue;
760
761                         element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
762
763                         for(;element_iter; element_iter = element_iter->next){
764                                 if(element_iter->separate){
765                                         if(stitch_check_uvs_state_stitchable(element, element_iter, state)){
766                                                 l = element_iter->l;
767                                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
768                                                 if(stitch_midpoints){
769                                                         add_v2_v2(final_position[i].uv, luv->uv);
770                                                         final_position[i].count++;
771                                                 }else if(element_iter->island == state->static_island){
772                                                         /* if multiple uvs on the static island exist,
773                                                          * last checked remains. to disambiguate we need to limit or use
774                                                          * edge stitch */
775                                                         copy_v2_v2(final_position[i].uv, luv->uv);
776                                                 }
777                                         }
778                                 }
779                         }
780                 }
781                 if(stitch_midpoints){
782                         final_position[i].uv[0] /= final_position[i].count;
783                         final_position[i].uv[1] /= final_position[i].count;
784                 }
785         }
786
787         /* second pass, calculate island rotation and translation before modifying any uvs */
788         if(state->snap_islands){
789                 for(i = 0; i < state->selection_size; i++){
790                         UvElement *element = state->selection_stack[i];
791                         if(element->flag & STITCH_STITCHABLE){
792                                 BMLoop *l;
793                                 MLoopUV *luv;
794
795                                 l = element->l;
796                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
797
798                                 /* accumulate each islands' translation from stitchable elements. it is important to do here
799                                  * because in final pass MTFaces get modified and result is zero. */
800                                 island_stitch_data[element->island].translation[0] += final_position[i].uv[0] - luv->uv[0];
801                                 island_stitch_data[element->island].translation[1] += final_position[i].uv[1] - luv->uv[1];
802                                 island_stitch_data[element->island].medianPoint[0] += luv->uv[0];
803                                 island_stitch_data[element->island].medianPoint[1] += luv->uv[1];
804                                 island_stitch_data[element->island].numOfElements++;
805                         }
806                 }
807
808                 /* only calculate rotation when an edge has been fully selected */
809                 for(i = 0; i < state->total_boundary_edges; i++){
810                         UvEdge *edge = state->edges+i;
811                         if((state->uvs[edge->uv1]->flag & STITCH_STITCHABLE) && (state->uvs[edge->uv2]->flag & STITCH_STITCHABLE)){
812                                 stitch_island_calculate_edge_rotation(edge, state, final_position, uvfinal_map, island_stitch_data);
813                                 island_stitch_data[state->uvs[edge->uv1]->island].use_edge_rotation = 1;
814                         }
815                 }
816
817                 for(i = 0; i < state->selection_size; i++){
818                         UvElement *element = state->selection_stack[i];
819                         if(!island_stitch_data[element->island].use_edge_rotation){
820                                 if(element->flag & STITCH_STITCHABLE){
821                                         stitch_island_calculate_vert_rotation(element, state, island_stitch_data);
822                                 }
823                         }
824                 }
825
826         }
827
828         /* third pass, propagate changes to coincident uvs */
829         for(i = 0; i < state->selection_size; i++){
830                 UvElement *element = state->selection_stack[i];
831                 if(element->flag & STITCH_STITCHABLE){
832                         UvElement *element_iter = element;
833                         /* propagate to coincident uvs */
834                         do{
835                                 BMLoop *l;
836                                 MLoopUV *luv;
837
838                                 l = element_iter->l;
839                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
840
841                                 element_iter->flag |= STITCH_PROCESSED;
842                                 /* either flush to preview or to the MTFace, if final */
843                                 if(final){
844                                         copy_v2_v2(luv->uv, final_position[i].uv);
845
846                                         uvedit_uv_select(state->em, scene, l);
847                                 }else {
848                                         int face_preview_pos = preview_position[BM_elem_index_get(element_iter->face)].data_position;
849                                         if(face_preview_pos != STITCH_NO_PREVIEW){
850                                                 copy_v2_v2(preview->preview_polys + face_preview_pos + 2*element_iter->tfindex,
851                                                                 final_position[i].uv);
852                                         }
853                                 }
854
855                                 /* end of calculations, keep only the selection flag */
856                                 if( (!state->snap_islands) || ((!stitch_midpoints) && (element_iter->island == state->static_island))) {
857                                         element_iter->flag &= STITCH_SELECTED;
858                                 }
859
860                                 element_iter = element_iter->next;
861                         }while(element_iter && !element_iter->separate);
862                 }
863         }
864
865         /* final pass, calculate Island translation/rotation if needed */
866         if(state->snap_islands){
867                 stitch_calculate_island_snapping(state, preview_position, preview, island_stitch_data, final);
868         }
869
870         MEM_freeN(final_position);
871         MEM_freeN(uvfinal_map);
872         MEM_freeN(island_stitch_data);
873         MEM_freeN(preview_position);
874
875         return 1;
876 }
877
878 /* Stitch hash initialisation functions */
879 static unsigned int     uv_edge_hash(const void *key){
880         UvEdge *edge = (UvEdge *)key;
881         return
882                 BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv2)) +
883                 BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv1));
884 }
885
886 static int uv_edge_compare(const void *a, const void *b){
887         UvEdge *edge1 = (UvEdge *)a;
888         UvEdge *edge2 = (UvEdge *)b;
889
890         if((edge1->uv1 == edge2->uv1) && (edge1->uv2 == edge2->uv2)){
891                 return 0;
892         }
893         return 1;
894 }
895
896
897 /* Select all common uvs */
898 static void stitch_select_uv(UvElement *element, StitchState *state, int always_select)
899 {
900         BMLoop *l;
901         UvElement *element_iter;
902         UvElement **selection_stack = state->selection_stack;
903
904         l = element->l;
905
906         element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
907         /* first deselect all common uvs */
908         for(; element_iter; element_iter = element_iter->next){
909                 if(element_iter->separate){
910                         /* only separators go to selection */
911                         if(element_iter->flag & STITCH_SELECTED){
912                                 int i;
913                                 if(always_select)
914                                         continue;
915
916                                 element_iter->flag &= ~STITCH_SELECTED;
917                                 for(i = 0; i < state->selection_size; i++){
918                                         if(selection_stack[i] == element_iter){
919                                                 (state->selection_size)--;
920                                                 selection_stack[i] = selection_stack[state->selection_size];
921                                                 break;
922                                         }
923                                 }
924                         }else{
925                                 element_iter->flag |= STITCH_SELECTED;
926                                 selection_stack[state->selection_size++] = element_iter;
927                         }
928                 }
929         }
930 }
931
932 static void stitch_calculate_edge_normal(BMEditMesh *em, UvEdge *edge, float *normal)
933 {
934         BMLoop *l1 = edge->element->l;
935         BMLoop *l2 = l1->next;
936         MLoopUV *luv1, *luv2;
937         float tangent[2];
938
939         luv1 = CustomData_bmesh_get(&em->bm->ldata, l1->head.data, CD_MLOOPUV);
940         luv2 = CustomData_bmesh_get(&em->bm->ldata, l2->head.data, CD_MLOOPUV);
941
942         sub_v2_v2v2(tangent, luv2->uv,  luv1->uv);
943
944         normal[0] = tangent[1];
945         normal[1] = -tangent[0];
946
947         normalize_v2(normal);
948 }
949
950 static int stitch_init(bContext *C, wmOperator *op)
951 {
952         /* for fast edge lookup... */
953         GHash *edgeHash;
954         /* ...and actual edge storage */
955         UvEdge *edges;
956         int total_edges;
957         /* maps uvelements to their first coincident uv */
958         int *map;
959         int counter = 0, i;
960         BMFace *efa;
961         BMLoop *l;
962         BMIter iter, liter;
963         BMEditMesh *em;
964         GHashIterator* ghi;
965         UvEdge *all_edges;
966         StitchState *state = MEM_mallocN(sizeof(StitchState), "stitch state");
967         Scene *scene = CTX_data_scene(C);
968         ToolSettings *ts = scene->toolsettings;
969
970         Object *obedit = CTX_data_edit_object(C);
971
972         op->customdata = state;
973
974         if(!state)
975                 return 0;
976
977         /* initialize state */
978         state->use_limit = RNA_boolean_get(op->ptr, "use_limit");
979         state->limit_dist = RNA_float_get(op->ptr, "limit");
980         state->em = em = ((Mesh *)obedit->data)->edit_btmesh;
981         state->snap_islands = RNA_boolean_get(op->ptr, "snap_islands");
982         state->static_island = RNA_int_get(op->ptr, "static_island");
983         state->midpoints = RNA_boolean_get(op->ptr, "midpoint_snap");
984         /* in uv synch selection, all uv's are visible */
985         if(ts->uv_flag & UV_SYNC_SELECTION){
986                 state->element_map = EDBM_make_uv_element_map(state->em, 0, 1);
987         }else{
988                 state->element_map = EDBM_make_uv_element_map(state->em, 1, 1);
989         }
990         if(!state->element_map){
991                 stitch_state_delete(state);
992                 return 0;
993         }
994
995         /* Entirely possible if redoing last operator that static island is bigger than total number of islands.
996          * This ensures we get no hang in the island checking code in stitch_process_data. */
997         state->static_island %= state->element_map->totalIslands;
998
999         /* Count 'unique' uvs */
1000         for(i = 0; i < state->element_map->totalUVs; i++){
1001                 if(state->element_map->buf[i].separate){
1002                         counter++;
1003                 }
1004         }
1005
1006         /* Allocate the unique uv buffers */
1007         state->uvs = MEM_mallocN(sizeof(*state->uvs)*counter, "uv_stitch_unique_uvs");
1008         /* internal uvs need no normals but it is hard and slow to keep a map of
1009          * normals only for boundary uvs, so allocating for all uvs */
1010         state->normals = MEM_callocN(sizeof(*state->normals)*counter*2, "uv_stitch_normals");
1011         state->total_separate_uvs = counter;
1012         /* we can at most have totalUVs edges or uvs selected. Actually they are less, considering we store only
1013          * unique uvs for processing but I am accounting for all bizarre cases, especially for edges, this way */
1014         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack)*counter, "uv_stitch_selection_stack");
1015         state->map = map = MEM_mallocN(sizeof(*map)*state->element_map->totalUVs, "uv_stitch_unique_map");
1016         /* Allocate the edge stack */
1017         edgeHash = BLI_ghash_new(uv_edge_hash, uv_edge_compare, "stitch_edge_hash");
1018         all_edges = MEM_mallocN(sizeof(*all_edges)*state->element_map->totalUVs, "stitch_all_edges");
1019
1020         if(!state->selection_stack || !state->uvs || !map || !edgeHash || !all_edges){
1021                 stitch_state_delete(state);
1022                 return 0;
1023         }
1024
1025         /* So that we can use this as index for the UvElements */
1026         counter = -1;
1027         /* initialize the unique UVs and map */
1028         for(i = 0; i < em->bm->totvert; i++){
1029                 UvElement *element = state->element_map->vert[i];
1030                 for(; element; element = element->next){
1031                         if(element->separate){
1032                                 counter++;
1033                                 state->uvs[counter] = element;
1034                         }
1035                         /* pointer arithmetic to the rescue, as always :)*/
1036                         map[element - state->element_map->buf] = counter;
1037                 }
1038         }
1039
1040         counter = 0;
1041         /* Now, on to generate our uv connectivity data */
1042         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1043                 if (!(ts->uv_flag & UV_SYNC_SELECTION) && ((BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) || !BM_elem_flag_test(efa, BM_ELEM_SELECT)))
1044                         continue;
1045
1046                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1047                         UvElement *element = ED_get_uv_element(state->element_map, efa, l);
1048                         int offset1, itmp1 = element - state->element_map->buf;
1049                         int offset2, itmp2 = ED_get_uv_element(state->element_map, efa, l->next) - state->element_map->buf;
1050
1051                         offset1 = map[itmp1];
1052                         offset2 = map[itmp2];
1053
1054                         all_edges[counter].flag = 0;
1055                         all_edges[counter].element = element;
1056                         /* using an order policy, sort uvs according to address space. This avoids
1057                          * Having two different UvEdges with the same uvs on different positions  */
1058                         if(offset1 < offset2){
1059                                 all_edges[counter].uv1 = offset1;
1060                                 all_edges[counter].uv2 = offset2;
1061                         }
1062                         else{
1063                                 all_edges[counter].uv1 = offset2;
1064                                 all_edges[counter].uv2 = offset1;
1065                         }
1066
1067                         if(BLI_ghash_haskey(edgeHash, &all_edges[counter])){
1068                                 char *flag = BLI_ghash_lookup(edgeHash, &all_edges[counter]);
1069                                 *flag = 0;
1070                         }
1071                         else{
1072                                 BLI_ghash_insert(edgeHash, &all_edges[counter], &(all_edges[counter].flag));
1073                                 all_edges[counter].flag = STITCH_BOUNDARY;
1074                         }
1075                         counter++;
1076                 }
1077         }
1078
1079
1080         ghi = BLI_ghashIterator_new(edgeHash);
1081         total_edges = 0;
1082         /* fill the edges with data */
1083         for(; !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)){
1084                 UvEdge *edge = ((UvEdge *)BLI_ghashIterator_getKey(ghi));
1085                 if(edge->flag & STITCH_BOUNDARY){
1086                         total_edges++;
1087                 }
1088         }
1089         state->edges = edges = MEM_mallocN(sizeof(*edges)*total_edges, "stitch_edges");
1090         if(!ghi || !edges){
1091                 MEM_freeN(all_edges);
1092                 stitch_state_delete(state);
1093                 return 0;
1094         }
1095
1096         state->total_boundary_edges = total_edges;
1097
1098         /* fill the edges with data */
1099         for(i = 0, BLI_ghashIterator_init(ghi, edgeHash); !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)){
1100                 UvEdge *edge = ((UvEdge *)BLI_ghashIterator_getKey(ghi));
1101                 if(edge->flag & STITCH_BOUNDARY){
1102                         edges[i++] = *((UvEdge *)BLI_ghashIterator_getKey(ghi));
1103                 }
1104         }
1105
1106         /* cleanup temporary stuff */
1107         BLI_ghashIterator_free(ghi);
1108         MEM_freeN(all_edges);
1109
1110         /* refill hash with new pointers to cleanup duplicates */
1111         BLI_ghash_free(edgeHash, NULL, NULL);
1112
1113         /***** calculate 2D normals for boundary uvs *****/
1114
1115         /* we use boundary edges to calculate 2D normals.
1116          * to disambiguate the direction of the normal, we also need
1117          * a point "inside" the island, that can be provided by
1118          * the opposite uv for a quad, or the next uv for a triangle. */
1119
1120         for(i = 0; i < total_edges; i++){
1121                 float normal[2];
1122                 stitch_calculate_edge_normal(em, edges + i, normal);
1123
1124                 add_v2_v2(state->normals + edges[i].uv1*2, normal);
1125                 add_v2_v2(state->normals + edges[i].uv2*2, normal);
1126
1127                 normalize_v2(state->normals + edges[i].uv1*2);
1128                 normalize_v2(state->normals + edges[i].uv2*2);
1129         }
1130
1131
1132         /***** fill selection stack *******/
1133
1134         state->selection_size = 0;
1135
1136         /* Load old selection if redoing operator with different settings */
1137         if(RNA_struct_property_is_set(op->ptr, "selection")){
1138                 int faceIndex, elementIndex;
1139                 UvElement *element;
1140
1141                 EDBM_init_index_arrays(em, 0, 0, 1);
1142
1143                 RNA_BEGIN(op->ptr, itemptr, "selection") {
1144                         faceIndex = RNA_int_get(&itemptr, "face_index");
1145                         elementIndex = RNA_int_get(&itemptr, "element_index");
1146                         efa = EDBM_get_face_for_index(em, faceIndex);
1147                         element = ED_get_uv_element(state->element_map, efa, BM_iter_at_index(NULL, BM_LOOPS_OF_FACE, efa, elementIndex));
1148                         stitch_select_uv(element, state, 1);
1149                 }
1150                 RNA_END;
1151
1152                 EDBM_free_index_arrays(em);
1153                 /* Clear the selection */
1154                 RNA_collection_clear(op->ptr, "selection");
1155
1156         } else {
1157                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1158                         i = 0;
1159                         BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1160                                 if(uvedit_uv_selected(em, scene, l)){
1161                                         UvElement *element = ED_get_uv_element(state->element_map, efa, l);
1162                                         stitch_select_uv(element, state, 1);
1163                                 }
1164                                 i++;
1165                         }
1166                 }
1167         }
1168
1169         /***** initialise static island preview data *****/
1170
1171         state->tris_per_island = MEM_mallocN(sizeof(*state->tris_per_island)*state->element_map->totalIslands,
1172                         "stitch island tris");
1173         for(i = 0; i < state->element_map->totalIslands; i++){
1174                 state->tris_per_island[i] = 0;
1175         }
1176
1177         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1178                 UvElement *element = ED_get_uv_element(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
1179
1180                 if(element){
1181                         state->tris_per_island[element->island] += (efa->len > 2)? efa->len-2 : 0;
1182                 }
1183         }
1184
1185         if(!stitch_process_data(state, scene, 0)){
1186                 stitch_state_delete(state);
1187                 return 0;
1188         }
1189
1190         stitch_update_header(state, C);
1191         return 1;
1192 }
1193
1194 static int stitch_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1195 {
1196         Object *obedit = CTX_data_edit_object(C);
1197         if(!stitch_init(C, op))
1198                 return OPERATOR_CANCELLED;
1199
1200         WM_event_add_modal_handler(C, op);
1201         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1202         return OPERATOR_RUNNING_MODAL;
1203 }
1204
1205 static void stitch_exit(bContext *C, wmOperator *op, int finished)
1206 {
1207         StitchState *stitch_state;
1208         Scene *scene;
1209         SpaceImage *sima;
1210         ScrArea *sa= CTX_wm_area(C);
1211         Object *obedit;
1212
1213         scene= CTX_data_scene(C);
1214         obedit= CTX_data_edit_object(C);
1215         sima= CTX_wm_space_image(C);
1216
1217         stitch_state = (StitchState *)op->customdata;
1218
1219         if(finished){
1220                 int i;
1221
1222                 RNA_float_set(op->ptr, "limit", stitch_state->limit_dist);
1223                 RNA_boolean_set(op->ptr, "use_limit", stitch_state->use_limit);
1224                 RNA_boolean_set(op->ptr, "snap_islands", stitch_state->snap_islands);
1225                 RNA_int_set(op->ptr, "static_island", stitch_state->static_island);
1226                 RNA_boolean_set(op->ptr, "midpoint_snap", stitch_state->midpoints);
1227
1228                 /* Store selection for re-execution of stitch */
1229                 for(i = 0; i < stitch_state->selection_size; i++){
1230                         PointerRNA itemptr;
1231                         UvElement *element = stitch_state->selection_stack[i];
1232
1233                         RNA_collection_add(op->ptr, "selection", &itemptr);
1234
1235                         RNA_int_set(&itemptr, "face_index", BM_elem_index_get(element->face));
1236
1237                         RNA_int_set(&itemptr, "element_index", element->tfindex);
1238                 }
1239
1240
1241                 uvedit_live_unwrap_update(sima, scene, obedit);
1242         }
1243
1244         if(sa)
1245                 ED_area_headerprint(sa, NULL);
1246
1247         DAG_id_tag_update(obedit->data, 0);
1248         WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data);
1249
1250         stitch_state_delete(stitch_state);
1251         op->customdata = NULL;
1252
1253         stitch_preview_delete();
1254 }
1255
1256
1257 static int stitch_cancel(bContext *C, wmOperator *op)
1258 {
1259         stitch_exit(C, op, 0);
1260         return OPERATOR_CANCELLED;
1261 }
1262
1263
1264 static int stitch_exec(bContext *C, wmOperator *op)
1265 {
1266         Scene *scene = CTX_data_scene(C);
1267
1268         if(!stitch_init(C, op))
1269                 return OPERATOR_CANCELLED;
1270         if(stitch_process_data((StitchState *)op->customdata, scene, 1)){
1271                 stitch_exit(C, op, 1);
1272                 return OPERATOR_FINISHED;
1273         }else {
1274                 return stitch_cancel(C, op);
1275         }
1276 }
1277
1278 static void stitch_select(bContext *C, Scene *scene, wmEvent *event, StitchState *stitch_state){
1279         /* add uv under mouse to processed uv's */
1280         float co[2];
1281         NearestHit hit;
1282         ARegion *ar= CTX_wm_region(C);
1283         Image *ima= CTX_data_edit_image(C);
1284
1285         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
1286         uv_find_nearest_vert(scene, ima, stitch_state->em, co, NULL, &hit);
1287
1288         if(hit.efa)
1289         {
1290                 /* Add vertex to selection, deselect all common uv's of vert other
1291                  * than selected and update the preview. This behavior was decided so that
1292                  * you can do stuff like deselect the opposite stitchable vertex and the initial still gets deselected */
1293
1294                 /* This works due to setting of tmp in find nearest uv vert */
1295                 UvElement *element = ED_get_uv_element(stitch_state->element_map, hit.efa, hit.l);
1296                 stitch_select_uv(element, stitch_state, 0);
1297
1298         }
1299 }
1300
1301 static int stitch_modal(bContext *C, wmOperator *op, wmEvent *event)
1302 {
1303         StitchState *stitch_state;
1304         Scene *scene = CTX_data_scene(C);
1305
1306         stitch_state = (StitchState *)op->customdata;
1307
1308         switch(event->type){
1309                 case MIDDLEMOUSE:
1310                         return OPERATOR_PASS_THROUGH;
1311
1312                 /* Cancel */
1313                 case ESCKEY:
1314                         return stitch_cancel(C, op);
1315
1316
1317                 case LEFTMOUSE:
1318                         if(event->shift && (U.flag & USER_LMOUSESELECT)){
1319                                 if(event->val == KM_RELEASE){
1320                                         stitch_select(C, scene, event, stitch_state);
1321
1322                                         if(!stitch_process_data(stitch_state, scene, 0)){
1323                                                 return stitch_cancel(C, op);
1324                                         }
1325                                 }
1326                                 break;
1327                         }
1328                 case PADENTER:
1329                 case RETKEY:
1330                         if(stitch_process_data(stitch_state, scene, 1)){
1331                                 stitch_exit(C, op, 1);
1332                                 return OPERATOR_FINISHED;
1333                         }
1334                         else {
1335                                 return stitch_cancel(C, op);
1336                         }
1337
1338                 /* Increase limit */
1339                 case PADPLUSKEY:
1340                 case WHEELUPMOUSE:
1341                         if(event->alt){
1342                                 stitch_state->limit_dist += 0.01;
1343                                 if(!stitch_process_data(stitch_state, scene, 0)){
1344                                         return stitch_cancel(C, op);
1345                                 }
1346                                 break;
1347                         }
1348                         else{
1349                                 return OPERATOR_PASS_THROUGH;
1350                         }
1351                 /* Decrease limit */
1352                 case PADMINUS:
1353                 case WHEELDOWNMOUSE:
1354                         if(event->alt){
1355                                 stitch_state->limit_dist -= 0.01;
1356                                 stitch_state->limit_dist = MAX2(0.01, stitch_state->limit_dist);
1357                                 if(!stitch_process_data(stitch_state, scene, 0)){
1358                                         return stitch_cancel(C, op);
1359                                 }
1360                                 break;
1361                         }else{
1362                                 return OPERATOR_PASS_THROUGH;
1363                         }
1364
1365                 /* Use Limit (Default off)*/
1366                 case LKEY:
1367                         if(event->val == KM_PRESS){
1368                                 stitch_state->use_limit = !stitch_state->use_limit;
1369                                 if(!stitch_process_data(stitch_state, scene, 0)){
1370                                         return stitch_cancel(C, op);
1371                                 }
1372                                 break;
1373                         }
1374                         return OPERATOR_RUNNING_MODAL;
1375
1376                 case IKEY:
1377                         if(event->val == KM_PRESS){
1378                                 stitch_state->static_island++;
1379                                 stitch_state->static_island %= stitch_state->element_map->totalIslands;
1380
1381                                 if(!stitch_process_data(stitch_state, scene, 0)){
1382                                         return stitch_cancel(C, op);
1383                                 }
1384                                 break;
1385                         }
1386                         return OPERATOR_RUNNING_MODAL;
1387
1388                 case MKEY:
1389                         if(event->val == KM_PRESS){
1390                                 stitch_state->midpoints = !stitch_state->midpoints;
1391                                 if(!stitch_process_data(stitch_state, scene, 0)){
1392                                         return stitch_cancel(C, op);
1393                                 }
1394                         }
1395                         break;
1396
1397                 /* Select geometry*/
1398                 case RIGHTMOUSE:
1399                         if(!event->shift){
1400                                         return stitch_cancel(C, op);
1401                         }
1402                         if(event->val == KM_RELEASE && !(U.flag & USER_LMOUSESELECT)){
1403                                 stitch_select(C, scene, event, stitch_state);
1404
1405                                 if(!stitch_process_data(stitch_state, scene, 0)){
1406                                         return stitch_cancel(C, op);
1407                                 }
1408                                 break;
1409                         }
1410                         return OPERATOR_RUNNING_MODAL;
1411
1412                 /* snap islands on/off */
1413                 case SKEY:
1414                         if(event->val == KM_PRESS){
1415                                 stitch_state->snap_islands = !stitch_state->snap_islands;
1416                                 if(!stitch_process_data(stitch_state, scene, 0)){
1417                                         return stitch_cancel(C, op);
1418                                 }
1419                                 break;
1420                         } else
1421                         return OPERATOR_RUNNING_MODAL;
1422
1423                 default:
1424                         return OPERATOR_RUNNING_MODAL;
1425         }
1426
1427         /* if updated settings, renew feedback message */
1428         stitch_update_header(stitch_state, C);
1429         ED_region_tag_redraw(CTX_wm_region(C));
1430         return OPERATOR_RUNNING_MODAL;
1431 }
1432
1433 void UV_OT_stitch(wmOperatorType *ot)
1434 {
1435         PropertyRNA *prop;
1436
1437         /* identifiers */
1438         ot->name = "Stitch";
1439         ot->description = "Stitch selected UV vertices by proximity";
1440         ot->idname = "UV_OT_stitch";
1441         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1442         
1443         /* api callbacks */
1444         ot->invoke = stitch_invoke;
1445         ot->modal = stitch_modal;
1446         ot->exec = stitch_exec;
1447         ot->cancel = stitch_cancel;
1448         ot->poll= ED_operator_uvedit;
1449
1450         /* properties */
1451         RNA_def_boolean(ot->srna, "use_limit", 0, "Use Limit", "Stitch UVs within a specified limit distance");
1452         RNA_def_boolean(ot->srna, "snap_islands", 1, "Snap Islands",
1453                                   "Snap islands together (on edge stitch mode, rotates the islands too)");
1454
1455         RNA_def_float(ot->srna, "limit", 0.01f, 0.0f, FLT_MAX, "Limit",
1456                                 "Limit distance in normalized coordinates", 0.0, FLT_MAX);
1457         RNA_def_int(ot->srna, "static_island", 0, 0, INT_MAX, "Static Island",
1458                               "Island that stays in place when stitching islands", 0, INT_MAX);
1459         RNA_def_boolean(ot->srna, "midpoint_snap", 0, "Snap At Midpoint",
1460                                   "UVs are stitched at midpoint instead of at static island");
1461         prop = RNA_def_collection_runtime(ot->srna, "selection", &RNA_SelectedUvElement, "Selection", "");
1462         /* Selection should not be editable or viewed in toolbar */
1463         RNA_def_property_flag(prop, PROP_HIDDEN);
1464 }