code cleanup: use const events for modal and invoke operators.
[blender.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_smart_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_utildefines.h"
45 #include "BLI_ghash.h"
46 #include "BLI_math.h"
47 #include "BLI_math_vector.h"
48 #include "BLI_string.h"
49
50 #include "BIF_gl.h"
51
52 #include "BKE_context.h"
53 #include "BKE_customdata.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_mesh.h"
56 #include "BKE_tessmesh.h"
57
58 #include "ED_mesh.h"
59 #include "ED_uvedit.h"
60 #include "ED_screen.h"
61 #include "ED_space_api.h"
62
63 #include "RNA_access.h"
64 #include "RNA_define.h"
65
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "UI_view2d.h"
70 #include "UI_resources.h"
71
72 #include "uvedit_intern.h"
73
74 /* ********************** smart stitch operator *********************** */
75
76 /* object that stores display data for previewing before confirming stitching */
77 typedef struct StitchPreviewer {
78         /* here we'll store the preview triangle indices of the mesh */
79         float *preview_polys;
80         /* uvs per polygon. */
81         unsigned int *uvs_per_polygon;
82         /*number of preview polygons */
83         unsigned int num_polys;
84         /* preview data. These will be either the previewed vertices or edges depending on stitch mode settings */
85         float *preview_stitchable;
86         float *preview_unstitchable;
87         /* here we'll store the number of elements to be drawn */
88         unsigned int num_stitchable;
89         unsigned int num_unstitchable;
90         unsigned int preview_uvs;
91         /* ...and here we'll store the static island triangles*/
92         float *static_tris;
93         unsigned int num_static_tris;
94 } StitchPreviewer;
95
96
97 struct IslandStitchData;
98
99 /* 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
100  * elements of the island except from the stitchable */
101 typedef struct IslandStitchData {
102         /* rotation can be used only for edges, for vertices there is no such notion */
103         float rotation;
104         float rotation_neg;
105         float translation[2];
106         /* Used for rotation, the island will rotate around this point */
107         float medianPoint[2];
108         int numOfElements;
109         int num_rot_elements;
110         int num_rot_elements_neg;
111         /* flag to remember if island has been added for preview */
112         char addedForPreview;
113         /* flag an island to be considered for determining static island */
114         char stitchableCandidate;
115         /* if edge rotation is used, flag so that vertex rotation is not used */
116         char use_edge_rotation;
117 } IslandStitchData;
118
119 /* just for averaging UVs */
120 typedef struct UVVertAverage {
121         float uv[2];
122         unsigned short count;
123 } UVVertAverage;
124
125 typedef struct UvEdge {
126         /* index to uv buffer */
127         unsigned int uv1;
128         unsigned int uv2;
129         /* general use flag (Used to check if edge is boundary here, and propagates to adjacency elements) */
130         unsigned char flag;
131         /* element that guarantees element->face has the edge on element->tfindex and element->tfindex+1 is the second uv */
132         UvElement *element;
133         /* next uv edge with the same exact vertices as this one.. Calculated at startup to save time */
134         struct UvEdge *next;
135         /* point to first of common edges. Needed for iteration */
136         struct UvEdge *first;
137 } UvEdge;
138
139
140 /* stitch state object */
141 typedef struct StitchState {
142         float aspect;
143         /* use limit flag */
144         char use_limit;
145         /* limit to operator, same as original operator */
146         float limit_dist;
147         /* snap uv islands together during stitching */
148         char snap_islands;
149         /* stich at midpoints or at islands */
150         char midpoints;
151         /* editmesh, cached for use in modal handler */
152         BMEditMesh *em;
153         /* clear seams of stitched edges after stitch */
154         char clear_seams;
155         /* element map for getting info about uv connectivity */
156         UvElementMap *element_map;
157         /* edge container */
158         UvEdge *uvedges;
159         /* container of first of a group of coincident uvs, these will be operated upon */
160         UvElement **uvs;
161         /* maps uvelements to their first coincident uv */
162         int *map;
163         /* 2D normals per uv to calculate rotation for snapping */
164         float *normals;
165         /* edge storage */
166         UvEdge *edges;
167         /* hash for quick lookup of edges */
168         GHash *edge_hash;
169
170         /* count of separate uvs and edges */
171         int total_separate_edges;
172         int total_separate_uvs;
173         /* hold selection related information */
174         void **selection_stack;
175         int selection_size;
176         /* island that stays in place */
177         int static_island;
178         /* store number of primitives per face so that we can allocate the active island buffer later */
179         unsigned int *tris_per_island;
180
181         /* vert or edge mode used for stitching */
182         char mode;
183         /* handle for drawing */
184         void *draw_handle;
185         /* preview data */
186         StitchPreviewer *stitch_preview;
187 } StitchState;
188
189 typedef struct PreviewPosition {
190         int data_position;
191         int polycount_position;
192 } PreviewPosition;
193 /*
194  * defines for UvElement/UcEdge flags
195  */
196 #define STITCH_SELECTED 1
197 #define STITCH_STITCHABLE 2
198 #define STITCH_PROCESSED 4
199 #define STITCH_BOUNDARY 8
200 #define STITCH_STITCHABLE_CANDIDATE 16
201
202 #define STITCH_NO_PREVIEW -1
203
204 enum StitchModes {
205         STITCH_VERT,
206         STITCH_EDGE
207 };
208
209 /* constructor */
210 static StitchPreviewer *stitch_preview_init(void)
211 {
212         StitchPreviewer *stitch_preview;
213
214         stitch_preview = MEM_mallocN(sizeof(StitchPreviewer), "stitch_previewer");
215         stitch_preview->preview_polys = NULL;
216         stitch_preview->preview_stitchable = NULL;
217         stitch_preview->preview_unstitchable = NULL;
218         stitch_preview->uvs_per_polygon = NULL;
219
220         stitch_preview->preview_uvs = 0;
221         stitch_preview->num_polys = 0;
222         stitch_preview->num_stitchable = 0;
223         stitch_preview->num_unstitchable = 0;
224
225         stitch_preview->static_tris = NULL;
226
227         stitch_preview->num_static_tris = 0;
228
229         return stitch_preview;
230 }
231
232 /* destructor...yeah this should be C++ :) */
233 static void stitch_preview_delete(StitchPreviewer *stitch_preview)
234 {
235         if (stitch_preview) {
236                 if (stitch_preview->preview_polys) {
237                         MEM_freeN(stitch_preview->preview_polys);
238                         stitch_preview->preview_polys = NULL;
239                 }
240                 if (stitch_preview->uvs_per_polygon) {
241                         MEM_freeN(stitch_preview->uvs_per_polygon);
242                         stitch_preview->uvs_per_polygon = NULL;
243                 }
244                 if (stitch_preview->preview_stitchable) {
245                         MEM_freeN(stitch_preview->preview_stitchable);
246                         stitch_preview->preview_stitchable = NULL;
247                 }
248                 if (stitch_preview->preview_unstitchable) {
249                         MEM_freeN(stitch_preview->preview_unstitchable);
250                         stitch_preview->preview_unstitchable = NULL;
251                 }
252                 if (stitch_preview->static_tris) {
253                         MEM_freeN(stitch_preview->static_tris);
254                         stitch_preview->static_tris = NULL;
255                 }
256                 MEM_freeN(stitch_preview);
257         }
258 }
259
260 #define HEADER_LENGTH 256
261
262 /* This function updates the header of the UV editor when the stitch tool updates its settings */
263 static void stitch_update_header(StitchState *state, bContext *C)
264 {
265         static char str[] = "Mode(TAB) %s, (S)nap %s, (M)idpoints %s, (L)imit %.2f (Alt Wheel adjust) %s, Switch (I)sland, shift select vertices";
266
267         char msg[HEADER_LENGTH];
268         ScrArea *sa = CTX_wm_area(C);
269
270         if (sa) {
271                 BLI_snprintf(msg, HEADER_LENGTH, str,
272                              state->mode == STITCH_VERT ? "Vertex" : "Edge",
273                              state->snap_islands ? "On" : "Off",
274                              state->midpoints    ? "On" : "Off",
275                              state->limit_dist,
276                              state->use_limit    ? "On" : "Off");
277
278                 ED_area_headerprint(sa, msg);
279         }
280 }
281
282 static int getNumOfIslandUvs(UvElementMap *elementMap, int island)
283 {
284         if (island == elementMap->totalIslands - 1) {
285                 return elementMap->totalUVs - elementMap->islandIndices[island];
286         }
287         else {
288                 return elementMap->islandIndices[island + 1] - elementMap->islandIndices[island];
289         }
290 }
291
292 static void stitch_uv_rotate(float mat[2][2], float medianPoint[2], float uv[2], float aspect)
293 {
294         float uv_rotation_result[2];
295
296         uv[1] /= aspect;
297
298         sub_v2_v2(uv, medianPoint);
299         mul_v2_m2v2(uv_rotation_result, mat, uv);
300         add_v2_v2v2(uv, uv_rotation_result, medianPoint);
301
302         uv[1] *= aspect;
303 }
304
305 /* check if two uvelements are stitchable. This should only operate on -different- separate UvElements */
306 static int stitch_check_uvs_stitchable(UvElement *element, UvElement *element_iter, StitchState *state)
307 {
308         float limit;
309
310         if (element_iter == element) {
311                 return 0;
312         }
313
314         limit = state->limit_dist;
315
316         if (state->use_limit) {
317                 MLoopUV *luv, *luv_iter;
318                 BMLoop *l;
319
320
321                 l = element->l;
322                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
323                 l = element_iter->l;
324                 luv_iter = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
325
326                 if (fabsf(luv->uv[0] - luv_iter->uv[0]) < limit &&
327                     fabsf(luv->uv[1] - luv_iter->uv[1]) < limit)
328                 {
329                         return 1;
330                 }
331                 else {
332                         return 0;
333                 }
334         }
335         else {
336                 return 1;
337         }
338 }
339
340 static int stitch_check_edges_stitchable(UvEdge *edge, UvEdge *edge_iter, StitchState *state)
341 {
342         float limit;
343
344         if (edge_iter == edge) {
345                 return 0;
346         }
347
348         limit = state->limit_dist;
349
350         if (state->use_limit) {
351                 BMLoop *l;
352                 MLoopUV *luv_orig1, *luv_iter1;
353                 MLoopUV *luv_orig2, *luv_iter2;
354
355                 l = state->uvs[edge->uv1]->l;
356                 luv_orig1 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
357                 l = state->uvs[edge_iter->uv1]->l;
358                 luv_iter1 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
359
360                 l = state->uvs[edge->uv2]->l;
361                 luv_orig2 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
362                 l = state->uvs[edge_iter->uv2]->l;
363                 luv_iter2 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
364
365                 if (fabsf(luv_orig1->uv[0] - luv_iter1->uv[0]) < limit &&
366                     fabsf(luv_orig1->uv[1] - luv_iter1->uv[1]) < limit &&
367                     fabsf(luv_orig2->uv[0] - luv_iter2->uv[0]) < limit &&
368                     fabsf(luv_orig2->uv[1] - luv_iter2->uv[1]) < limit)
369                 {
370                         return 1;
371                 }
372                 else {
373                         return 0;
374                 }
375         }
376         else {
377                 return 1;
378         }
379 }
380
381 static int stitch_check_uvs_state_stitchable(UvElement *element, UvElement *element_iter, StitchState *state)
382 {
383         if ((state->snap_islands && element->island == element_iter->island) ||
384             (!state->midpoints && element->island == element_iter->island))
385         {
386                 return 0;
387         }
388
389         return stitch_check_uvs_stitchable(element, element_iter, state);
390 }
391
392
393 static int stitch_check_edges_state_stitchable(UvEdge *edge, UvEdge *edge_iter, StitchState *state)
394 {
395         if ((state->snap_islands && edge->element->island == edge_iter->element->island) ||
396             (!state->midpoints && edge->element->island == edge_iter->element->island))
397         {
398                 return 0;
399         }
400
401         return stitch_check_edges_stitchable(edge, edge_iter, state);
402 }
403
404 /* calculate snapping for islands */
405 static void stitch_calculate_island_snapping(StitchState *state, PreviewPosition *preview_position, StitchPreviewer *preview, IslandStitchData *island_stitch_data, int final)
406 {
407         int i;
408         UvElement *element;
409
410         for (i = 0; i < state->element_map->totalIslands; i++) {
411                 if (island_stitch_data[i].addedForPreview) {
412                         int numOfIslandUVs = 0, j;
413                         int totelem = island_stitch_data[i].num_rot_elements_neg + island_stitch_data[i].num_rot_elements;
414                         float rotation;
415                         float rotation_mat[2][2];
416
417                         /* check to avoid divide by 0 */
418                         if (island_stitch_data[i].num_rot_elements > 1)
419                                 island_stitch_data[i].rotation /= island_stitch_data[i].num_rot_elements;
420
421                         if (island_stitch_data[i].num_rot_elements_neg > 1)
422                                 island_stitch_data[i].rotation_neg /= island_stitch_data[i].num_rot_elements_neg;
423
424                         if (island_stitch_data[i].numOfElements > 1) {
425                                 island_stitch_data[i].medianPoint[0] /= island_stitch_data[i].numOfElements;
426                                 island_stitch_data[i].medianPoint[1] /= island_stitch_data[i].numOfElements;
427
428                                 island_stitch_data[i].translation[0] /= island_stitch_data[i].numOfElements;
429                                 island_stitch_data[i].translation[1] /= island_stitch_data[i].numOfElements;
430                         }
431
432                         island_stitch_data[i].medianPoint[1] /= state->aspect;
433                         if ((island_stitch_data[i].rotation + island_stitch_data[i].rotation_neg < (float)M_PI_2) ||
434                             island_stitch_data[i].num_rot_elements == 0 || island_stitch_data[i].num_rot_elements_neg == 0)
435                         {
436                                 rotation = (island_stitch_data[i].rotation * island_stitch_data[i].num_rot_elements -
437                                             island_stitch_data[i].rotation_neg *
438                                             island_stitch_data[i].num_rot_elements_neg) / totelem;
439                         }
440                         else {
441                                 rotation = (island_stitch_data[i].rotation * island_stitch_data[i].num_rot_elements +
442                                             (2.0f * (float)M_PI - island_stitch_data[i].rotation_neg) *
443                                             island_stitch_data[i].num_rot_elements_neg) / totelem;
444                         }
445
446                         rotate_m2(rotation_mat, rotation);
447                         numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
448                         element = &state->element_map->buf[state->element_map->islandIndices[i]];
449                         for (j = 0; j < numOfIslandUVs; j++, element++) {
450                                 /* stitchable uvs have already been processed, don't process */
451                                 if (!(element->flag & STITCH_PROCESSED)) {
452                                         MLoopUV *luv;
453                                         BMLoop *l;
454
455                                         l = element->l;
456                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
457
458                                         if (final) {
459
460                                                 stitch_uv_rotate(rotation_mat, island_stitch_data[i].medianPoint, luv->uv, state->aspect);
461
462                                                 add_v2_v2(luv->uv, island_stitch_data[i].translation);
463                                         }
464
465                                         else {
466
467                                                 int face_preview_pos = preview_position[BM_elem_index_get(element->l->f)].data_position;
468
469                                                 stitch_uv_rotate(rotation_mat, island_stitch_data[i].medianPoint,
470                                                                  preview->preview_polys + face_preview_pos + 2 * element->tfindex, state->aspect);
471
472                                                 add_v2_v2(preview->preview_polys + face_preview_pos + 2 * element->tfindex,
473                                                           island_stitch_data[i].translation);
474                                         }
475                                 }
476                                 /* cleanup */
477                                 element->flag &= STITCH_SELECTED;
478                         }
479                 }
480         }
481 }
482
483
484
485 static void stitch_island_calculate_edge_rotation(UvEdge *edge, StitchState *state, UVVertAverage *uv_average, unsigned int *uvfinal_map, IslandStitchData *island_stitch_data)
486 {
487         UvElement *element1, *element2;
488         float uv1[2], uv2[2];
489         float edgecos, edgesin;
490         int index1, index2;
491         float rotation;
492         MLoopUV *luv1, *luv2;
493
494         element1 = state->uvs[edge->uv1];
495         element2 = state->uvs[edge->uv2];
496
497         luv1 = CustomData_bmesh_get(&state->em->bm->ldata, element1->l->head.data, CD_MLOOPUV);
498         luv2 = CustomData_bmesh_get(&state->em->bm->ldata, element2->l->head.data, CD_MLOOPUV);
499
500         if (state->mode == STITCH_VERT) {
501                 index1 = uvfinal_map[element1 - state->element_map->buf];
502                 index2 = uvfinal_map[element2 - state->element_map->buf];
503         }
504         else {
505                 index1 = edge->uv1;
506                 index2 = edge->uv2;
507         }
508         /* the idea here is to take the directions of the edges and find the rotation between final and initial
509          * direction. This, using inner and outer vector products, gives the angle. Directions are differences so... */
510         uv1[0] = luv2->uv[0] - luv1->uv[0];
511         uv1[1] = luv2->uv[1] - luv1->uv[1];
512
513         uv1[1] /= state->aspect;
514
515         uv2[0] = uv_average[index2].uv[0] - uv_average[index1].uv[0];
516         uv2[1] = uv_average[index2].uv[1] - uv_average[index1].uv[1];
517
518         uv2[1] /= state->aspect;
519
520         normalize_v2(uv1);
521         normalize_v2(uv2);
522
523         edgecos = dot_v2v2(uv1, uv2);
524         edgesin = cross_v2v2(uv1, uv2);
525         rotation = acosf(max_ff(-1.0f, min_ff(1.0f, edgecos)));
526
527         if (edgesin > 0.0f) {
528                 island_stitch_data[element1->island].num_rot_elements++;
529                 island_stitch_data[element1->island].rotation += rotation;
530         }
531         else {
532                 island_stitch_data[element1->island].num_rot_elements_neg++;
533                 island_stitch_data[element1->island].rotation_neg += rotation;
534         }
535 }
536
537
538 static void stitch_island_calculate_vert_rotation(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data)
539 {
540         float edgecos = 1.0f, edgesin = 0.0f;
541         int index;
542         UvElement *element_iter;
543         float rotation = 0, rotation_neg = 0;
544         int rot_elem = 0, rot_elem_neg = 0;
545         BMLoop *l;
546
547         if (element->island == state->static_island && !state->midpoints)
548                 return;
549
550         l = element->l;
551
552         index = BM_elem_index_get(l->v);
553
554         element_iter = state->element_map->vert[index];
555
556         for (; element_iter; element_iter = element_iter->next) {
557                 if (element_iter->separate && stitch_check_uvs_state_stitchable(element, element_iter, state)) {
558                         int index_tmp1, index_tmp2;
559                         float normal[2];
560
561                         /* only calculate rotation against static island uv verts */
562                         if (!state->midpoints && element_iter->island != state->static_island)
563                                 continue;
564
565                         index_tmp1 = element_iter - state->element_map->buf;
566                         index_tmp1 = state->map[index_tmp1];
567                         index_tmp2 = element - state->element_map->buf;
568                         index_tmp2 = state->map[index_tmp2];
569
570                         negate_v2_v2(normal, state->normals + index_tmp2 * 2);
571                         edgecos = dot_v2v2(normal, state->normals + index_tmp1 * 2);
572                         edgesin = cross_v2v2(normal, state->normals + index_tmp1 * 2);
573                         if (edgesin > 0.0f) {
574                             rotation += acosf(max_ff(-1.0f, min_ff(1.0f, edgecos)));
575                                 rot_elem++;
576                         }
577                         else {
578                             rotation_neg += acosf(max_ff(-1.0f, min_ff(1.0f, edgecos)));
579                                 rot_elem_neg++;
580                         }
581                 }
582         }
583
584         if (state->midpoints) {
585                 rotation /= 2.0f;
586                 rotation_neg /= 2.0f;
587         }
588         island_stitch_data[element->island].num_rot_elements += rot_elem;
589         island_stitch_data[element->island].rotation += rotation;
590         island_stitch_data[element->island].num_rot_elements_neg += rot_elem_neg;
591         island_stitch_data[element->island].rotation_neg += rotation_neg;
592 }
593
594
595 static void state_delete(StitchState *state)
596 {
597         if (state) {
598                 if (state->element_map) {
599                         EDBM_uv_element_map_free(state->element_map);
600                 }
601                 if (state->uvs) {
602                         MEM_freeN(state->uvs);
603                 }
604                 if (state->selection_stack) {
605                         MEM_freeN(state->selection_stack);
606                 }
607                 if (state->tris_per_island) {
608                         MEM_freeN(state->tris_per_island);
609                 }
610                 if (state->map) {
611                         MEM_freeN(state->map);
612                 }
613                 if (state->normals) {
614                         MEM_freeN(state->normals);
615                 }
616                 if (state->edges) {
617                         MEM_freeN(state->edges);
618                 }
619                 if (state->stitch_preview) {
620                         stitch_preview_delete(state->stitch_preview);
621                 }
622                 if (state->edge_hash) {
623                         BLI_ghash_free(state->edge_hash, NULL, NULL);
624                 }
625                 MEM_freeN(state);
626         }
627 }
628
629 static void stitch_uv_edge_generate_linked_edges(GHash *edge_hash, StitchState *state)
630 {
631         UvEdge *edges = state->edges;
632         int *map = state->map;
633         UvElementMap *element_map = state->element_map;
634         UvElement *first_element = element_map->buf;
635         int i;
636
637         for (i = 0; i < state->total_separate_edges; i++) {
638                 UvEdge *edge = edges + i;
639
640                 if (edge->first)
641                         continue;
642
643                 /* only boundary edges can be stitched. Yes. Sorry about that :p */
644                 if (edge->flag & STITCH_BOUNDARY) {
645                         UvElement *element1 = state->uvs[edge->uv1];
646                         UvElement *element2 = state->uvs[edge->uv2];
647
648                         /* Now iterate through all faces and try to find edges sharing the same vertices */
649                         UvElement *iter1 = element_map->vert[BM_elem_index_get(element1->l->v)];
650                         UvEdge *last_set = edge;
651                         int elemindex2 = BM_elem_index_get(element2->l->v);
652
653                         edge->first = edge;
654
655                         for (; iter1; iter1 = iter1->next) {
656                                 UvElement *iter2 = NULL;
657
658                                 /* check to see if other vertex of edge belongs to same vertex as */
659                                 if (BM_elem_index_get(iter1->l->next->v) == elemindex2)
660                                         iter2 = ED_uv_element_get(element_map, iter1->l->f, iter1->l->next);
661                                 else if (BM_elem_index_get(iter1->l->prev->v) == elemindex2)
662                                         iter2 = ED_uv_element_get(element_map, iter1->l->f, iter1->l->prev);
663
664                                 if (iter2) {
665                                         int index1 = map[iter1 - first_element];
666                                         int index2 = map[iter2 - first_element];
667
668                                         /* make certain we do not have the same edge! */
669                                         if (state->uvs[index2] != element2 && state->uvs[index1] != element1) {
670                                                 UvEdge edgetmp;
671                                                 UvEdge *edge2;
672
673
674                                                 /* make sure the indices are well behaved */
675                                                 if (index1 < index2) {
676                                                         edgetmp.uv1 = index1;
677                                                         edgetmp.uv2 = index2;
678                                                 }
679                                                 else {
680                                                         edgetmp.uv1 = index2;
681                                                         edgetmp.uv2 = index1;
682                                                 }
683
684                                                 /* get the edge from the hash */
685                                                 edge2 = BLI_ghash_lookup(edge_hash, &edgetmp);
686
687                                                 /* here I am taking care of non manifold case, assuming more than two matching edges.
688                                                  * I am not too sure we want this though */
689                                                 last_set->next = edge2;
690                                                 last_set = edge2;
691                                                 /* set first, similarly to uv elements. Now we can iterate among common edges easily */
692                                                 edge2->first = edge;
693                                         }
694                                 }
695                         }
696                 }
697                 else {
698                         /* so stitchability code works */
699                         edge->first = edge;
700                 }
701         }
702 }
703
704
705 /* checks for remote uvs that may be stitched with a certain uv, flags them if stitchable. */
706 static void determine_uv_stitchability(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data)
707 {
708         int vert_index;
709         UvElement *element_iter;
710         BMLoop *l;
711
712         l = element->l;
713
714         vert_index = BM_elem_index_get(l->v);
715         element_iter = state->element_map->vert[vert_index];
716
717         for (; element_iter; element_iter = element_iter->next) {
718                 if (element_iter->separate) {
719                         if (stitch_check_uvs_stitchable(element, element_iter, state)) {
720                                 island_stitch_data[element_iter->island].stitchableCandidate = 1;
721                                 island_stitch_data[element->island].stitchableCandidate = 1;
722                                 element->flag |= STITCH_STITCHABLE_CANDIDATE;
723                         }
724                 }
725         }
726 }
727
728 static void determine_uv_edge_stitchability(UvEdge *edge, StitchState *state, IslandStitchData *island_stitch_data)
729 {
730         UvEdge *edge_iter = edge->first;
731
732         for (; edge_iter; edge_iter = edge_iter->next) {
733                 if (stitch_check_edges_stitchable(edge, edge_iter, state)) {
734                         island_stitch_data[edge_iter->element->island].stitchableCandidate = 1;
735                         island_stitch_data[edge->element->island].stitchableCandidate = 1;
736                         edge->flag |= STITCH_STITCHABLE_CANDIDATE;
737                 }
738         }
739 }
740
741
742 /* set preview buffer position of UV face in editface->tmp.l */
743 static void stitch_set_face_preview_buffer_position(BMFace *efa, StitchPreviewer *preview, PreviewPosition *preview_position)
744 {
745         int index = BM_elem_index_get(efa);
746
747         if (preview_position[index].data_position == STITCH_NO_PREVIEW) {
748                 preview_position[index].data_position = preview->preview_uvs * 2;
749                 preview_position[index].polycount_position = preview->num_polys++;
750                 preview->preview_uvs += efa->len;
751         }
752 }
753
754
755 /* setup face preview for all coincident uvs and their faces */
756 static void stitch_setup_face_preview_for_uv_group(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
757                                                    PreviewPosition *preview_position) {
758         StitchPreviewer *preview = state->stitch_preview;
759
760         /* static island does not change so returning immediately */
761         if (state->snap_islands && !state->midpoints && state->static_island == element->island)
762                 return;
763
764         if (state->snap_islands) {
765                 island_stitch_data[element->island].addedForPreview = 1;
766         }
767
768         do {
769                 stitch_set_face_preview_buffer_position(element->l->f, preview, preview_position);
770                 element = element->next;
771         } while (element && !element->separate);
772 }
773
774
775 /* checks if uvs are indeed stitchable and registers so that they can be shown in preview */
776 static void stitch_validate_uv_stichability(UvElement *element, StitchState *state, IslandStitchData *island_stitch_data,
777                                          PreviewPosition *preview_position) {
778         UvElement *element_iter;
779         StitchPreviewer *preview = state->stitch_preview;
780         int vert_index;
781         BMLoop *l;
782
783         l = element->l;
784
785         vert_index = BM_elem_index_get(l->v);
786
787         element_iter = state->element_map->vert[vert_index];
788
789         for (; element_iter; element_iter = element_iter->next) {
790                 if (element_iter->separate) {
791                         if (element_iter == element)
792                                 continue;
793                         if (stitch_check_uvs_state_stitchable(element, element_iter, state)) {
794                                 if ((element_iter->island == state->static_island) || (element->island == state->static_island)) {
795                                         element->flag |= STITCH_STITCHABLE;
796                                         preview->num_stitchable++;
797                                         stitch_setup_face_preview_for_uv_group(element, state, island_stitch_data, preview_position);
798                                         return;
799                                 }
800                         }
801                 }
802         }
803
804         /* this can happen if the uvs to be stitched are not on a stitchable island */
805         if (!(element->flag & STITCH_STITCHABLE)) {
806                 preview->num_unstitchable++;
807         }
808 }
809
810
811 static void stitch_validate_edge_stichability(UvEdge *edge, StitchState *state, IslandStitchData *island_stitch_data,
812                                               PreviewPosition *preview_position) {
813         UvEdge *edge_iter = edge->first;
814         StitchPreviewer *preview = state->stitch_preview;
815
816         for (; edge_iter; edge_iter = edge_iter->next) {
817                 if (edge_iter == edge)
818                         continue;
819                 if (stitch_check_edges_state_stitchable(edge, edge_iter, state)) {
820                         if ((edge_iter->element->island == state->static_island) || (edge->element->island == state->static_island)) {
821                                 edge->flag |= STITCH_STITCHABLE;
822                                 preview->num_stitchable++;
823                                 stitch_setup_face_preview_for_uv_group(state->uvs[edge->uv1], state, island_stitch_data, preview_position);
824                                 stitch_setup_face_preview_for_uv_group(state->uvs[edge->uv2], state, island_stitch_data, preview_position);
825                                 return;
826                         }
827                 }
828         }
829
830         /* this can happen if the uvs to be stitched are not on a stitchable island */
831         if (!(edge->flag & STITCH_STITCHABLE)) {
832                 preview->num_unstitchable++;
833         }
834 }
835
836
837 static void stitch_propagate_uv_final_position(UvElement *element, int index, PreviewPosition *preview_position, UVVertAverage *final_position, StitchState *state, char final, Scene *scene)
838 {
839         StitchPreviewer *preview = state->stitch_preview;
840
841         if (element->flag & STITCH_STITCHABLE) {
842                 UvElement *element_iter = element;
843                 /* propagate to coincident uvs */
844                 do {
845                         BMLoop *l;
846                         MLoopUV *luv;
847
848                         l = element_iter->l;
849                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
850
851                         element_iter->flag |= STITCH_PROCESSED;
852                         /* either flush to preview or to the MTFace, if final */
853                         if (final) {
854                                 copy_v2_v2(luv->uv, final_position[index].uv);
855
856                                 uvedit_uv_select_enable(state->em, scene, l, FALSE);
857                         }
858                         else {
859                                 int face_preview_pos = preview_position[BM_elem_index_get(element_iter->l->f)].data_position;
860                                 if (face_preview_pos != STITCH_NO_PREVIEW) {
861                                         copy_v2_v2(preview->preview_polys + face_preview_pos + 2 * element_iter->tfindex,
862                                                    final_position[index].uv);
863                                 }
864                         }
865
866                         /* end of calculations, keep only the selection flag */
867                         if ( (!state->snap_islands) || ((!state->midpoints) && (element_iter->island == state->static_island))) {
868                                 element_iter->flag &= STITCH_SELECTED;
869                         }
870
871                         element_iter = element_iter->next;
872                 } while (element_iter && !element_iter->separate);
873         }
874 }
875
876 /* main processing function. It calculates preview and final positions. */
877 static int stitch_process_data(StitchState *state, Scene *scene, int final)
878 {
879         int i;
880         StitchPreviewer *preview;
881         IslandStitchData *island_stitch_data = NULL;
882         int previous_island = state->static_island;
883         BMFace *efa;
884         BMIter iter;
885         UVVertAverage *final_position = NULL;
886
887         char stitch_midpoints = state->midpoints;
888         /* used to map uv indices to uvaverage indices for selection */
889         unsigned int *uvfinal_map = NULL;
890         /* per face preview position in preview buffer */
891         PreviewPosition *preview_position = NULL;
892
893         /* cleanup previous preview */
894         stitch_preview_delete(state->stitch_preview);
895         preview = state->stitch_preview = stitch_preview_init();
896         if (preview == NULL)
897                 return 0;
898
899         preview_position = MEM_mallocN(state->em->bm->totface * sizeof(*preview_position), "stitch_face_preview_position");
900         /* each face holds its position in the preview buffer in tmp. -1 is uninitialized */
901         for (i = 0; i < state->em->bm->totface; i++) {
902                 preview_position[i].data_position = STITCH_NO_PREVIEW;
903         }
904
905         island_stitch_data = MEM_callocN(sizeof(*island_stitch_data) * state->element_map->totalIslands, "stitch_island_data");
906         if (!island_stitch_data) {
907                 return 0;
908         }
909
910         /* store indices to editVerts and Faces. May be unneeded but ensuring anyway */
911         BM_mesh_elem_index_ensure(state->em->bm, BM_VERT | BM_FACE);
912
913         /*****************************************
914          *  First determine stitchability of uvs *
915          *****************************************/
916
917         for (i = 0; i < state->selection_size; i++) {
918                 if (state->mode == STITCH_VERT) {
919                         UvElement *element = (UvElement *)state->selection_stack[i];
920                         determine_uv_stitchability(element, state, island_stitch_data);
921                 }
922                 else {
923                         UvEdge *edge = (UvEdge *)state->selection_stack[i];
924                         determine_uv_edge_stitchability(edge, state, island_stitch_data);
925                 }
926         }
927
928         /* set static island to one that is added for preview */
929         state->static_island %= state->element_map->totalIslands;
930         while (!(island_stitch_data[state->static_island].stitchableCandidate)) {
931                 state->static_island++;
932                 state->static_island %= state->element_map->totalIslands;
933                 /* this is entirely possible if for example limit stitching with no stitchable verts or no selection */
934                 if (state->static_island == previous_island)
935                         break;
936         }
937
938         for (i = 0; i < state->selection_size; i++) {
939                 if (state->mode == STITCH_VERT) {
940                         UvElement *element = (UvElement *)state->selection_stack[i];
941                         if (element->flag & STITCH_STITCHABLE_CANDIDATE) {
942                                 element->flag &= ~STITCH_STITCHABLE_CANDIDATE;
943                                 stitch_validate_uv_stichability(element, state, island_stitch_data, preview_position);
944                         }
945                         else {
946                                 /* add to preview for unstitchable */
947                                 preview->num_unstitchable++;
948                         }
949                 }
950                 else {
951                         UvEdge *edge = (UvEdge *)state->selection_stack[i];
952                         if (edge->flag & STITCH_STITCHABLE_CANDIDATE) {
953                                 edge->flag &= ~STITCH_STITCHABLE_CANDIDATE;
954                                 stitch_validate_edge_stichability(edge, state, island_stitch_data, preview_position);
955                         }
956                         else {
957                                 preview->num_unstitchable++;
958                         }
959                 }
960         }
961
962         /*****************************************
963          *  Setup preview for stitchable islands *
964          *****************************************/
965         if (state->snap_islands) {
966                 for (i = 0; i < state->element_map->totalIslands; i++) {
967                         if (island_stitch_data[i].addedForPreview) {
968                                 int numOfIslandUVs = 0, j;
969                                 UvElement *element;
970                                 numOfIslandUVs = getNumOfIslandUvs(state->element_map, i);
971                                 element = &state->element_map->buf[state->element_map->islandIndices[i]];
972                                 for (j = 0; j < numOfIslandUVs; j++, element++) {
973                                         stitch_set_face_preview_buffer_position(element->l->f, preview, preview_position);
974                                 }
975                         }
976                 }
977         }
978
979         /*********************************************************************
980          * Setup the preview buffers and fill them with the appropriate data *
981          *********************************************************************/
982         if (!final) {
983                 BMIter liter;
984                 BMLoop *l;
985                 MLoopUV *luv;
986                 unsigned int buffer_index = 0;
987                 int stitchBufferIndex = 0, unstitchBufferIndex = 0;
988                 int preview_size = (state->mode == STITCH_VERT) ? 2 : 4;
989                 /* initialize the preview buffers */
990                 preview->preview_polys = (float *)MEM_mallocN(preview->preview_uvs * sizeof(float) * 2, "tri_uv_stitch_prev");
991                 preview->uvs_per_polygon = MEM_mallocN(preview->num_polys * sizeof(*preview->uvs_per_polygon), "tri_uv_stitch_prev");
992                 preview->preview_stitchable = (float *)MEM_mallocN(preview->num_stitchable * sizeof(float) * preview_size, "stitch_preview_stichable_data");
993                 preview->preview_unstitchable = (float *)MEM_mallocN(preview->num_unstitchable * sizeof(float) * preview_size, "stitch_preview_unstichable_data");
994
995                 preview->static_tris = (float *)MEM_mallocN(state->tris_per_island[state->static_island] * sizeof(float) * 6, "static_island_preview_tris");
996
997                 preview->num_static_tris = state->tris_per_island[state->static_island];
998                 /* will cause cancel and freeing of all data structures so OK */
999                 if (!preview->preview_polys || !preview->preview_stitchable || !preview->preview_unstitchable) {
1000                         return 0;
1001                 }
1002
1003                 /* copy data from MLoopUVs to the preview display buffers */
1004                 BM_ITER_MESH (efa, &iter, state->em->bm, BM_FACES_OF_MESH) {
1005                         /* just to test if face was added for processing. uvs of inselected vertices will return NULL */
1006                         UvElement *element = ED_uv_element_get(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
1007
1008                         if (element) {
1009                                 int numoftris = efa->len - 2;
1010                                 int index = BM_elem_index_get(efa);
1011                                 int face_preview_pos = preview_position[index].data_position;
1012                                 if (face_preview_pos != STITCH_NO_PREVIEW) {
1013                                         preview->uvs_per_polygon[preview_position[index].polycount_position] = efa->len;
1014                                         BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1015                                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1016                                                 copy_v2_v2(preview->preview_polys + face_preview_pos + i * 2, luv->uv);
1017                                         }
1018                                 }
1019
1020                                 if (element->island == state->static_island) {
1021                                         BMLoop *fl = BM_FACE_FIRST_LOOP(efa);
1022                                         MLoopUV *fuv = CustomData_bmesh_get(&state->em->bm->ldata, fl->head.data, CD_MLOOPUV);
1023
1024                                         BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1025                                                 if (i < numoftris) {
1026                                                         /* using next since the first uv is already accounted for */
1027                                                         BMLoop *lnext = l->next;
1028                                                         MLoopUV *luvnext = CustomData_bmesh_get(&state->em->bm->ldata, lnext->next->head.data, CD_MLOOPUV);
1029                                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, lnext->head.data, CD_MLOOPUV);
1030
1031                                                         memcpy(preview->static_tris + buffer_index, fuv->uv, 2 * sizeof(float));
1032                                                         memcpy(preview->static_tris + buffer_index + 2, luv->uv, 2 * sizeof(float));
1033                                                         memcpy(preview->static_tris + buffer_index + 4, luvnext->uv, 2 * sizeof(float));
1034                                                         buffer_index += 6;
1035                                                 }
1036                                                 else {
1037                                                         break;
1038                                                 }
1039                                         }
1040                                 }
1041                         }
1042                 }
1043
1044                 /* fill the appropriate preview buffers */
1045                 if (state->mode == STITCH_VERT) {
1046                         for (i = 0; i < state->total_separate_uvs; i++) {
1047                                 UvElement *element = (UvElement *)state->uvs[i];
1048                                 if (element->flag & STITCH_STITCHABLE) {
1049                                         l = element->l;
1050                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1051
1052                                         copy_v2_v2(&preview->preview_stitchable[stitchBufferIndex * 2], luv->uv);
1053
1054                                         stitchBufferIndex++;
1055                                 }
1056                                 else if (element->flag & STITCH_SELECTED) {
1057                                         l = element->l;
1058                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1059
1060                                         copy_v2_v2(&preview->preview_unstitchable[unstitchBufferIndex * 2], luv->uv);
1061                                         unstitchBufferIndex++;
1062                                 }
1063                         }
1064                 }
1065                 else {
1066                         for (i = 0; i < state->total_separate_edges; i++) {
1067                                 UvEdge *edge = state->edges + i;
1068                                 UvElement *element1 = state->uvs[edge->uv1];
1069                                 UvElement *element2 = state->uvs[edge->uv2];
1070
1071                                 if (edge->flag & STITCH_STITCHABLE) {
1072                                         l = element1->l;
1073                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1074                                         copy_v2_v2(&preview->preview_stitchable[stitchBufferIndex * 4], luv->uv);
1075
1076                                         l = element2->l;
1077                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1078                                         copy_v2_v2(&preview->preview_stitchable[stitchBufferIndex * 4 + 2], luv->uv);
1079
1080                                         stitchBufferIndex++;
1081                                         BLI_assert(stitchBufferIndex <= preview->num_stitchable);
1082                                 }
1083                                 else if (edge->flag & STITCH_SELECTED) {
1084                                         l = element1->l;
1085                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1086                                         copy_v2_v2(&preview->preview_unstitchable[unstitchBufferIndex * 4], luv->uv);
1087
1088                                         l = element2->l;
1089                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1090                                         copy_v2_v2(&preview->preview_unstitchable[unstitchBufferIndex * 4 + 2], luv->uv);
1091
1092                                         unstitchBufferIndex++;
1093                                         BLI_assert(unstitchBufferIndex <= preview->num_unstitchable);
1094                                 }
1095                         }
1096                 }
1097         }
1098
1099         /******************************************************
1100          * Here we calculate the final coordinates of the uvs *
1101          ******************************************************/
1102
1103         if (state->mode == STITCH_VERT) {
1104                 final_position = MEM_callocN(state->selection_size * sizeof(*final_position), "stitch_uv_average");
1105                 uvfinal_map = MEM_mallocN(state->element_map->totalUVs * sizeof(*uvfinal_map), "stitch_uv_final_map");
1106         }
1107         else {
1108                 final_position = MEM_callocN(state->total_separate_uvs * sizeof(*final_position), "stitch_uv_average");
1109         }
1110
1111         /* first pass, calculate final position for stitchable uvs of the static island */
1112         for (i = 0; i < state->selection_size; i++) {
1113                 if (state->mode == STITCH_VERT) {
1114                         UvElement *element = state->selection_stack[i];
1115
1116                         if (element->flag & STITCH_STITCHABLE) {
1117                                 BMLoop *l;
1118                                 MLoopUV *luv;
1119                                 UvElement *element_iter;
1120
1121                                 l = element->l;
1122                                 luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1123
1124                                 uvfinal_map[element - state->element_map->buf] = i;
1125
1126                                 copy_v2_v2(final_position[i].uv, luv->uv);
1127                                 final_position[i].count = 1;
1128
1129                                 if (state->snap_islands && element->island == state->static_island && !stitch_midpoints)
1130                                         continue;
1131
1132                                 element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
1133
1134                                 for ( ; element_iter; element_iter = element_iter->next) {
1135                                         if (element_iter->separate) {
1136                                                 if (stitch_check_uvs_state_stitchable(element, element_iter, state)) {
1137                                                         l = element_iter->l;
1138                                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1139                                                         if (stitch_midpoints) {
1140                                                                 add_v2_v2(final_position[i].uv, luv->uv);
1141                                                                 final_position[i].count++;
1142                                                         }
1143                                                         else if (element_iter->island == state->static_island) {
1144                                                                 /* if multiple uvs on the static island exist,
1145                                                                  * last checked remains. to disambiguate we need to limit or use
1146                                                                  * edge stitch */
1147                                                                 copy_v2_v2(final_position[i].uv, luv->uv);
1148                                                         }
1149                                                 }
1150                                         }
1151                                 }
1152                         }
1153                         if (stitch_midpoints) {
1154                                 final_position[i].uv[0] /= final_position[i].count;
1155                                 final_position[i].uv[1] /= final_position[i].count;
1156                         }
1157                 }
1158                 else {
1159                         UvEdge *edge = state->selection_stack[i];
1160
1161                         if (edge->flag & STITCH_STITCHABLE) {
1162                                 MLoopUV *luv2, *luv1;
1163                                 BMLoop *l;
1164                                 UvEdge *edge_iter;
1165
1166                                 l = state->uvs[edge->uv1]->l;
1167                                 luv1 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1168                                 l = state->uvs[edge->uv2]->l;
1169                                 luv2 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1170
1171                                 copy_v2_v2(final_position[edge->uv1].uv, luv1->uv);
1172                                 copy_v2_v2(final_position[edge->uv2].uv, luv2->uv);
1173                                 final_position[edge->uv1].count = 1;
1174                                 final_position[edge->uv2].count = 1;
1175
1176                                 state->uvs[edge->uv1]->flag |= STITCH_STITCHABLE;
1177                                 state->uvs[edge->uv2]->flag |= STITCH_STITCHABLE;
1178
1179                                 if (state->snap_islands && edge->element->island == state->static_island && !stitch_midpoints)
1180                                         continue;
1181
1182                                 for (edge_iter = edge->first; edge_iter; edge_iter = edge_iter->next) {
1183                                         if (stitch_check_edges_state_stitchable (edge, edge_iter, state)) {
1184                                                 l = state->uvs[edge_iter->uv1]->l;
1185                                                 luv1 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1186                                                 l = state->uvs[edge_iter->uv2]->l;
1187                                                 luv2 = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1188
1189                                                 if (stitch_midpoints) {
1190                                                         add_v2_v2(final_position[edge->uv1].uv, luv1->uv);
1191                                                         final_position[edge->uv1].count++;
1192                                                         add_v2_v2(final_position[edge->uv2].uv, luv2->uv);
1193                                                         final_position[edge->uv2].count++;
1194                                                 }
1195                                                 else if (edge_iter->element->island == state->static_island) {
1196                                                         copy_v2_v2(final_position[edge->uv1].uv, luv1->uv);
1197                                                         copy_v2_v2(final_position[edge->uv2].uv, luv2->uv);
1198                                                 }
1199                                         }
1200                                 }
1201                         }
1202                 }
1203         }
1204
1205         /* take mean position here. For edge case, this can't be done inside the loop for shared uvverts */
1206         if (state->mode == STITCH_EDGE && stitch_midpoints) {
1207                 for (i = 0; i < state->total_separate_uvs; i++) {
1208                         final_position[i].uv[0] /= final_position[i].count;
1209                         final_position[i].uv[1] /= final_position[i].count;
1210                 }
1211         }
1212
1213         /* second pass, calculate island rotation and translation before modifying any uvs */
1214         if (state->snap_islands) {
1215                 if (state->mode == STITCH_VERT) {
1216                         for (i = 0; i < state->selection_size; i++) {
1217                                 UvElement *element = state->selection_stack[i];
1218
1219                                 if (element->flag & STITCH_STITCHABLE) {
1220                                         BMLoop *l;
1221                                         MLoopUV *luv;
1222
1223                                         l = element->l;
1224                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1225
1226                                         /* accumulate each islands' translation from stitchable elements. it is important to do here
1227                                          * because in final pass MTFaces get modified and result is zero. */
1228                                         island_stitch_data[element->island].translation[0] += final_position[i].uv[0] - luv->uv[0];
1229                                         island_stitch_data[element->island].translation[1] += final_position[i].uv[1] - luv->uv[1];
1230                                         island_stitch_data[element->island].medianPoint[0] += luv->uv[0];
1231                                         island_stitch_data[element->island].medianPoint[1] += luv->uv[1];
1232                                         island_stitch_data[element->island].numOfElements++;
1233                                 }
1234                         }
1235
1236                         /* only calculate rotation when an edge has been fully selected */
1237                         for (i = 0; i < state->total_separate_edges; i++) {
1238                                 UvEdge *edge = state->edges + i;
1239                                 if ((edge->flag & STITCH_BOUNDARY) && (state->uvs[edge->uv1]->flag & STITCH_STITCHABLE) && (state->uvs[edge->uv2]->flag & STITCH_STITCHABLE)) {
1240                                         stitch_island_calculate_edge_rotation(edge, state, final_position, uvfinal_map, island_stitch_data);
1241                                         island_stitch_data[state->uvs[edge->uv1]->island].use_edge_rotation = TRUE;
1242                                 }
1243                         }
1244
1245                         /* clear seams of stitched edges */
1246                         if (final && state->clear_seams) {
1247                                 for (i = 0; i < state->total_separate_edges; i++) {
1248                                         UvEdge *edge = state->edges + i;
1249                                         if ((state->uvs[edge->uv1]->flag & STITCH_STITCHABLE) && (state->uvs[edge->uv2]->flag & STITCH_STITCHABLE))
1250                                                 BM_elem_flag_disable(edge->element->l->e, BM_ELEM_SEAM);
1251                                 }
1252                         }
1253
1254                         for (i = 0; i < state->selection_size; i++) {
1255                                 UvElement *element = state->selection_stack[i];
1256                                 if (!island_stitch_data[element->island].use_edge_rotation) {
1257                                         if (element->flag & STITCH_STITCHABLE) {
1258                                                 stitch_island_calculate_vert_rotation(element, state, island_stitch_data);
1259                                         }
1260                                 }
1261                         }
1262                 }
1263                 else {
1264                         for (i = 0; i < state->total_separate_uvs; i++) {
1265                                 UvElement *element = state->uvs[i];
1266
1267                                 if (element->flag & STITCH_STITCHABLE) {
1268                                         BMLoop *l;
1269                                         MLoopUV *luv;
1270
1271                                         l = element->l;
1272                                         luv = CustomData_bmesh_get(&state->em->bm->ldata, l->head.data, CD_MLOOPUV);
1273
1274                                         /* accumulate each islands' translation from stitchable elements. it is important to do here
1275                                          * because in final pass MTFaces get modified and result is zero. */
1276                                         island_stitch_data[element->island].translation[0] += final_position[i].uv[0] - luv->uv[0];
1277                                         island_stitch_data[element->island].translation[1] += final_position[i].uv[1] - luv->uv[1];
1278                                         island_stitch_data[element->island].medianPoint[0] += luv->uv[0];
1279                                         island_stitch_data[element->island].medianPoint[1] += luv->uv[1];
1280                                         island_stitch_data[element->island].numOfElements++;
1281                                 }
1282                         }
1283
1284                         for (i = 0; i < state->selection_size; i++) {
1285                                 UvEdge *edge = state->selection_stack[i];
1286
1287                                 if (edge->flag & STITCH_STITCHABLE) {
1288                                         stitch_island_calculate_edge_rotation(edge, state, final_position, NULL, island_stitch_data);
1289                                         island_stitch_data[state->uvs[edge->uv1]->island].use_edge_rotation = TRUE;
1290                                 }
1291                         }
1292
1293                         /* clear seams of stitched edges */
1294                         if (final && state->clear_seams) {
1295                                 for (i = 0; i < state->selection_size; i++) {
1296                                         UvEdge *edge = state->selection_stack[i];
1297                                         if (edge->flag & STITCH_STITCHABLE) {
1298                                                 BM_elem_flag_disable(edge->element->l->e, BM_ELEM_SEAM);
1299                                         }
1300                                 }
1301                         }
1302                 }
1303         }
1304
1305         /* third pass, propagate changes to coincident uvs */
1306         for (i = 0; i < state->selection_size; i++) {
1307                 if (state->mode == STITCH_VERT) {
1308                         UvElement *element = state->selection_stack[i];
1309
1310                         stitch_propagate_uv_final_position (element, i, preview_position, final_position, state, final, scene);
1311                 }
1312                 else {
1313                         UvEdge *edge = state->selection_stack[i];
1314
1315                         stitch_propagate_uv_final_position (state->uvs[edge->uv1], edge->uv1, preview_position, final_position, state, final, scene);
1316                         stitch_propagate_uv_final_position (state->uvs[edge->uv2], edge->uv2, preview_position, final_position, state, final, scene);
1317
1318                         edge->flag &= (STITCH_SELECTED | STITCH_BOUNDARY);
1319                 }
1320         }
1321
1322         /* final pass, calculate Island translation/rotation if needed */
1323         if (state->snap_islands) {
1324                 stitch_calculate_island_snapping(state, preview_position, preview, island_stitch_data, final);
1325         }
1326
1327         MEM_freeN(final_position);
1328         if (state->mode == STITCH_VERT) {
1329                 MEM_freeN(uvfinal_map);
1330         }
1331         MEM_freeN(island_stitch_data);
1332         MEM_freeN(preview_position);
1333
1334         return 1;
1335 }
1336
1337 /* Stitch hash initialization functions */
1338 static unsigned int uv_edge_hash(const void *key)
1339 {
1340         UvEdge *edge = (UvEdge *)key;
1341         return
1342                 BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv2)) +
1343                 BLI_ghashutil_inthash(SET_INT_IN_POINTER(edge->uv1));
1344 }
1345
1346 static int uv_edge_compare(const void *a, const void *b)
1347 {
1348         UvEdge *edge1 = (UvEdge *)a;
1349         UvEdge *edge2 = (UvEdge *)b;
1350
1351         if ((edge1->uv1 == edge2->uv1) && (edge1->uv2 == edge2->uv2)) {
1352                 return 0;
1353         }
1354         return 1;
1355 }
1356
1357 /* select all common edges */
1358 static void stitch_select_edge(UvEdge *edge, StitchState *state, int always_select)
1359 {
1360         UvEdge *eiter;
1361         UvEdge **selection_stack = (UvEdge **)state->selection_stack;
1362
1363         for (eiter = edge->first; eiter; eiter = eiter->next) {
1364                 if (eiter->flag & STITCH_SELECTED) {
1365                         int i;
1366                         if (always_select)
1367                                 continue;
1368
1369                         eiter->flag &= ~STITCH_SELECTED;
1370                         for (i = 0; i < state->selection_size; i++) {
1371                                 if (selection_stack[i] == eiter) {
1372                                         (state->selection_size)--;
1373                                         selection_stack[i] = selection_stack[state->selection_size];
1374                                         break;
1375                                 }
1376                         }
1377                 }
1378                 else {
1379                         eiter->flag |= STITCH_SELECTED;
1380                         selection_stack[state->selection_size++] = eiter;
1381                 }
1382         }
1383 }
1384
1385
1386 /* Select all common uvs */
1387 static void stitch_select_uv(UvElement *element, StitchState *state, int always_select)
1388 {
1389         BMLoop *l;
1390         UvElement *element_iter;
1391         UvElement **selection_stack = (UvElement **)state->selection_stack;
1392
1393         l = element->l;
1394
1395         element_iter = state->element_map->vert[BM_elem_index_get(l->v)];
1396         /* first deselect all common uvs */
1397         for (; element_iter; element_iter = element_iter->next) {
1398                 if (element_iter->separate) {
1399                         /* only separators go to selection */
1400                         if (element_iter->flag & STITCH_SELECTED) {
1401                                 int i;
1402                                 if (always_select)
1403                                         continue;
1404
1405                                 element_iter->flag &= ~STITCH_SELECTED;
1406                                 for (i = 0; i < state->selection_size; i++) {
1407                                         if (selection_stack[i] == element_iter) {
1408                                                 (state->selection_size)--;
1409                                                 selection_stack[i] = selection_stack[state->selection_size];
1410                                                 break;
1411                                         }
1412                                 }
1413                         }
1414                         else {
1415                                 element_iter->flag |= STITCH_SELECTED;
1416                                 selection_stack[state->selection_size++] = element_iter;
1417                         }
1418                 }
1419         }
1420 }
1421
1422 static void stitch_switch_selection_mode(StitchState *state)
1423 {
1424         void **old_selection_stack = state->selection_stack;
1425         int old_selection_size = state->selection_size;
1426         state->selection_size = 0;
1427
1428         if (state->mode == STITCH_VERT) {
1429                 int i;
1430                 state->selection_stack = MEM_mallocN(state->total_separate_edges * sizeof(*state->selection_stack),
1431                                                      "stitch_new_edge_selection_stack");
1432
1433                 /* check if both elements of an edge are selected */
1434                 for (i = 0; i < state->total_separate_edges; i++) {
1435                         UvEdge *edge = state->edges + i;
1436                         UvElement *element1 = state->uvs[edge->uv1];
1437                         UvElement *element2 = state->uvs[edge->uv2];
1438
1439                         if ((element1->flag & STITCH_SELECTED) && (element2->flag & STITCH_SELECTED))
1440                                 stitch_select_edge(edge, state, TRUE);
1441                 }
1442
1443                 /* unselect selected uvelements */
1444                 for (i = 0; i < old_selection_size; i++) {
1445                         UvElement *element = old_selection_stack[i];
1446
1447                         element->flag &= ~STITCH_SELECTED;
1448                 }
1449                 state->mode = STITCH_EDGE;
1450         }
1451         else {
1452                 int i;
1453                 state->selection_stack = MEM_mallocN(state->total_separate_uvs * sizeof(*state->selection_stack),
1454                                                      "stitch_new_vert_selection_stack");
1455
1456                 for (i = 0; i < old_selection_size; i++) {
1457                         UvEdge *edge = old_selection_stack[i];
1458                         UvElement *element1 = state->uvs[edge->uv1];
1459                         UvElement *element2 = state->uvs[edge->uv2];
1460
1461                         stitch_select_uv(element1, state, TRUE);
1462                         stitch_select_uv(element2, state, TRUE);
1463
1464                         edge->flag &= ~STITCH_SELECTED;
1465                 }
1466                 state->mode = STITCH_VERT;
1467         }
1468         MEM_freeN(old_selection_stack);
1469 }
1470
1471 static void stitch_calculate_edge_normal(BMEditMesh *em, UvEdge *edge, float *normal, float aspect)
1472 {
1473         BMLoop *l1 = edge->element->l;
1474         MLoopUV *luv1, *luv2;
1475         float tangent[2];
1476
1477         luv1 = CustomData_bmesh_get(&em->bm->ldata, l1->head.data, CD_MLOOPUV);
1478         luv2 = CustomData_bmesh_get(&em->bm->ldata, l1->next->head.data, CD_MLOOPUV);
1479
1480         sub_v2_v2v2(tangent, luv2->uv,  luv1->uv);
1481
1482         tangent[1] /= aspect;
1483
1484         normal[0] = tangent[1];
1485         normal[1] = -tangent[0];
1486
1487         normalize_v2(normal);
1488 }
1489
1490 static void stitch_draw(const bContext *UNUSED(C), ARegion *UNUSED(ar), void *arg)
1491 {
1492         int i, index = 0;
1493         float pointsize = UI_GetThemeValuef(TH_VERTEX_SIZE);
1494         StitchState *state = (StitchState *)arg;
1495         StitchPreviewer *stitch_preview = state->stitch_preview;
1496
1497         glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
1498         glEnableClientState(GL_VERTEX_ARRAY);
1499
1500         glPointSize(pointsize * 2.0f);
1501
1502         glEnable(GL_BLEND);
1503
1504         UI_ThemeColor4(TH_STITCH_PREVIEW_ACTIVE);
1505         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1506         glVertexPointer(2, GL_FLOAT, 0, stitch_preview->static_tris);
1507         glDrawArrays(GL_TRIANGLES, 0, stitch_preview->num_static_tris * 3);
1508
1509         glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_polys);
1510         for (i = 0; i < stitch_preview->num_polys; i++) {
1511                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1512                 UI_ThemeColor4(TH_STITCH_PREVIEW_FACE);
1513                 glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
1514                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1515                 UI_ThemeColor4(TH_STITCH_PREVIEW_EDGE);
1516                 glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
1517                 #if 0
1518                 glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
1519                 UI_ThemeColor4(TH_STITCH_PREVIEW_VERT);
1520                 glDrawArrays(GL_POLYGON, index, stitch_preview->uvs_per_polygon[i]);
1521                 #endif
1522
1523                 index += stitch_preview->uvs_per_polygon[i];
1524         }
1525         glDisable(GL_BLEND);
1526
1527         /* draw vert preview */
1528         if (state->mode == STITCH_VERT) {
1529                 UI_ThemeColor4(TH_STITCH_PREVIEW_STITCHABLE);
1530                 glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_stitchable);
1531                 glDrawArrays(GL_POINTS, 0, stitch_preview->num_stitchable);
1532
1533                 UI_ThemeColor4(TH_STITCH_PREVIEW_UNSTITCHABLE);
1534                 glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_unstitchable);
1535                 glDrawArrays(GL_POINTS, 0, stitch_preview->num_unstitchable);
1536         }
1537         else {
1538                 UI_ThemeColor4(TH_STITCH_PREVIEW_STITCHABLE);
1539                 glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_stitchable);
1540                 glDrawArrays(GL_LINES, 0, 2 * stitch_preview->num_stitchable);
1541
1542                 UI_ThemeColor4(TH_STITCH_PREVIEW_UNSTITCHABLE);
1543                 glVertexPointer(2, GL_FLOAT, 0, stitch_preview->preview_unstitchable);
1544                 glDrawArrays(GL_LINES, 0, 2 * stitch_preview->num_unstitchable);
1545         }
1546
1547         glPopClientAttrib();
1548         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1549
1550         glPointSize(1.0);
1551 }
1552
1553 static UvEdge *uv_edge_get (BMLoop *l, StitchState *state)
1554 {
1555         UvEdge tmp_edge;
1556
1557         UvElement *element1 = ED_uv_element_get(state->element_map, l->f, l);
1558         UvElement *element2 = ED_uv_element_get(state->element_map, l->f, l->next);
1559
1560         int uv1 = state->map[element1 - state->element_map->buf];
1561         int uv2 = state->map[element2 - state->element_map->buf];
1562
1563         if (uv1 < uv2) {
1564                 tmp_edge.uv1 = uv1;
1565                 tmp_edge.uv2 = uv2;
1566         }
1567         else {
1568                 tmp_edge.uv1 = uv2;
1569                 tmp_edge.uv2 = uv1;
1570         }
1571
1572         return BLI_ghash_lookup(state->edge_hash, &tmp_edge);
1573 }
1574
1575 static int stitch_init(bContext *C, wmOperator *op)
1576 {
1577         /* for fast edge lookup... */
1578         GHash *edge_hash;
1579         /* ...and actual edge storage */
1580         UvEdge *edges;
1581         int total_edges;
1582         /* maps uvelements to their first coincident uv */
1583         int *map;
1584         int counter = 0, i;
1585         BMFace *efa;
1586         BMLoop *l;
1587         BMIter iter, liter;
1588         BMEditMesh *em;
1589         GHashIterator *ghi;
1590         UvEdge *all_edges;
1591         StitchState *state;
1592         Scene *scene = CTX_data_scene(C);
1593         ToolSettings *ts = scene->toolsettings;
1594         ARegion *ar = CTX_wm_region(C);
1595         float aspx, aspy;
1596         Object *obedit = CTX_data_edit_object(C);
1597
1598         if (!ar)
1599                 return 0;
1600
1601         state = MEM_mallocN(sizeof(StitchState), "stitch state");
1602
1603         if (!state)
1604                 return 0;
1605
1606         op->customdata = state;
1607
1608         /* initialize state */
1609         state->use_limit = RNA_boolean_get(op->ptr, "use_limit");
1610         state->limit_dist = RNA_float_get(op->ptr, "limit");
1611         state->em = em = BMEdit_FromObject(obedit);
1612         state->snap_islands = RNA_boolean_get(op->ptr, "snap_islands");
1613         state->static_island = RNA_int_get(op->ptr, "static_island");
1614         state->midpoints = RNA_boolean_get(op->ptr, "midpoint_snap");
1615         state->clear_seams = RNA_boolean_get(op->ptr, "clear_seams");
1616         if (RNA_struct_property_is_set(op->ptr, "mode")) {
1617                 state->mode = RNA_enum_get(op->ptr, "mode");
1618         }
1619         else {
1620                 if (ts->uv_flag & UV_SYNC_SELECTION) {
1621                         if (ts->selectmode & SCE_SELECT_VERTEX)
1622                                 state->mode = STITCH_VERT;
1623                         else
1624                                 state->mode = STITCH_EDGE;
1625                 }
1626                 else {
1627                         if (ts->uv_selectmode & UV_SELECT_VERTEX) {
1628                                 state->mode = STITCH_VERT;
1629                         }
1630                         else {
1631                                 state->mode = STITCH_EDGE;
1632                         }
1633                 }
1634         }
1635
1636         state->draw_handle = ED_region_draw_cb_activate(ar->type, stitch_draw, state, REGION_DRAW_POST_VIEW);
1637         /* in uv synch selection, all uv's are visible */
1638         if (ts->uv_flag & UV_SYNC_SELECTION) {
1639                 state->element_map = EDBM_uv_element_map_create(state->em, FALSE, TRUE);
1640         }
1641         else {
1642                 state->element_map = EDBM_uv_element_map_create(state->em, TRUE, TRUE);
1643         }
1644         if (!state->element_map) {
1645                 state_delete(state);
1646                 return 0;
1647         }
1648
1649         uvedit_get_aspect(scene, obedit, em, &aspx, &aspy);
1650         state->aspect = aspx / aspy;
1651
1652         /* Entirely possible if redoing last operator that static island is bigger than total number of islands.
1653          * This ensures we get no hang in the island checking code in stitch_stitch_process_data. */
1654         state->static_island %= state->element_map->totalIslands;
1655
1656         /* Count 'unique' uvs */
1657         for (i = 0; i < state->element_map->totalUVs; i++) {
1658                 if (state->element_map->buf[i].separate) {
1659                         counter++;
1660                 }
1661         }
1662
1663         /* explicitly set preview to NULL, to avoid deleting an invalid pointer on stitch_process_data */
1664         state->stitch_preview = NULL;
1665         /* Allocate the unique uv buffers */
1666         state->uvs = MEM_mallocN(sizeof(*state->uvs) * counter, "uv_stitch_unique_uvs");
1667         /* internal uvs need no normals but it is hard and slow to keep a map of
1668          * normals only for boundary uvs, so allocating for all uvs */
1669         state->normals = MEM_callocN(sizeof(*state->normals) * counter * 2, "uv_stitch_normals");
1670         state->total_separate_uvs = counter;
1671         state->map = map = MEM_mallocN(sizeof(*map) * state->element_map->totalUVs, "uv_stitch_unique_map");
1672         /* Allocate the edge stack */
1673         edge_hash = BLI_ghash_new(uv_edge_hash, uv_edge_compare, "stitch_edge_hash");
1674         all_edges = MEM_mallocN(sizeof(*all_edges) * state->element_map->totalUVs, "stitch_all_edges");
1675
1676         if (!state->uvs || !map || !edge_hash || !all_edges) {
1677                 state_delete(state);
1678                 return 0;
1679         }
1680
1681         /* So that we can use this as index for the UvElements */
1682         counter = -1;
1683         /* initialize the unique UVs and map */
1684         for (i = 0; i < em->bm->totvert; i++) {
1685                 UvElement *element = state->element_map->vert[i];
1686                 for (; element; element = element->next) {
1687                         if (element->separate) {
1688                                 counter++;
1689                                 state->uvs[counter] = element;
1690                         }
1691                         /* pointer arithmetic to the rescue, as always :)*/
1692                         map[element - state->element_map->buf] = counter;
1693                 }
1694         }
1695
1696         counter = 0;
1697         /* Now, on to generate our uv connectivity data */
1698         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1699                 if (!(ts->uv_flag & UV_SYNC_SELECTION) && ((BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) || !BM_elem_flag_test(efa, BM_ELEM_SELECT)))
1700                         continue;
1701
1702                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1703                         UvElement *element = ED_uv_element_get(state->element_map, efa, l);
1704                         int offset1, itmp1 = element - state->element_map->buf;
1705                         int offset2, itmp2 = ED_uv_element_get(state->element_map, efa, l->next) - state->element_map->buf;
1706
1707                         offset1 = map[itmp1];
1708                         offset2 = map[itmp2];
1709
1710                         all_edges[counter].next = NULL;
1711                         all_edges[counter].first = NULL;
1712                         all_edges[counter].flag = 0;
1713                         all_edges[counter].element = element;
1714                         /* using an order policy, sort uvs according to address space. This avoids
1715                          * Having two different UvEdges with the same uvs on different positions  */
1716                         if (offset1 < offset2) {
1717                                 all_edges[counter].uv1 = offset1;
1718                                 all_edges[counter].uv2 = offset2;
1719                         }
1720                         else {
1721                                 all_edges[counter].uv1 = offset2;
1722                                 all_edges[counter].uv2 = offset1;
1723                         }
1724
1725                         if (BLI_ghash_haskey(edge_hash, &all_edges[counter])) {
1726                                 UvEdge *edge = BLI_ghash_lookup(edge_hash, &all_edges[counter]);
1727                                 edge->flag = 0;
1728                         }
1729                         else {
1730                                 BLI_ghash_insert(edge_hash, &all_edges[counter], &all_edges[counter]);
1731                                 all_edges[counter].flag = STITCH_BOUNDARY;
1732                         }
1733                         counter++;
1734                 }
1735         }
1736
1737
1738         ghi = BLI_ghashIterator_new(edge_hash);
1739         total_edges = BLI_ghash_size(edge_hash);
1740         state->edges = edges = MEM_mallocN(sizeof(*edges) * total_edges, "stitch_edges");
1741
1742         /* I assume any system will be able to at least allocate an iterator :p */
1743         if (!edges) {
1744                 BLI_ghashIterator_free(ghi);
1745                 state_delete(state);
1746                 return 0;
1747         }
1748
1749         state->total_separate_edges = total_edges;
1750
1751         /* fill the edges with data */
1752         for (i = 0, BLI_ghashIterator_init(ghi, edge_hash); BLI_ghashIterator_notDone(ghi); BLI_ghashIterator_step(ghi)) {
1753                 edges[i++] = *((UvEdge *)BLI_ghashIterator_getKey(ghi));
1754         }
1755
1756         /* cleanup temporary stuff */
1757         BLI_ghashIterator_free(ghi);
1758         MEM_freeN(all_edges);
1759
1760         BLI_ghash_free(edge_hash, NULL, NULL);
1761
1762         /* refill an edge hash to create edge connnectivity data */
1763         state->edge_hash = edge_hash = BLI_ghash_new(uv_edge_hash, uv_edge_compare, "stitch_edge_hash");
1764         for (i = 0; i < total_edges; i++) {
1765                 BLI_ghash_insert(edge_hash, edges + i, edges + i);
1766         }
1767         stitch_uv_edge_generate_linked_edges(edge_hash, state);
1768
1769         /***** calculate 2D normals for boundary uvs *****/
1770
1771         /* we use boundary edges to calculate 2D normals.
1772          * to disambiguate the direction of the normal, we also need
1773          * a point "inside" the island, that can be provided by
1774          * the winding of the polygon (assuming counter-clockwise flow). */
1775
1776         for (i = 0; i < total_edges; i++) {
1777                 UvEdge *edge = edges + i;
1778                 float normal[2];
1779                 if (edge->flag & STITCH_BOUNDARY) {
1780                         stitch_calculate_edge_normal(em, edge, normal, state->aspect);
1781
1782                         add_v2_v2(state->normals + edge->uv1 * 2, normal);
1783                         add_v2_v2(state->normals + edge->uv2 * 2, normal);
1784
1785                         normalize_v2(state->normals + edge->uv1 * 2);
1786                         normalize_v2(state->normals + edge->uv2 * 2);
1787                 }
1788         }
1789
1790
1791         /***** fill selection stack *******/
1792
1793         state->selection_size = 0;
1794
1795         /* Load old selection if redoing operator with different settings */
1796         if (RNA_struct_property_is_set(op->ptr, "selection")) {
1797                 int faceIndex, elementIndex;
1798                 UvElement *element;
1799                 enum StitchModes stored_mode = RNA_enum_get(op->ptr, "stored_mode");
1800
1801                 EDBM_index_arrays_ensure(em, BM_FACE);
1802
1803                 if (stored_mode == STITCH_VERT) {
1804                         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack) * state->total_separate_uvs, "uv_stitch_selection_stack");
1805
1806                         RNA_BEGIN (op->ptr, itemptr, "selection")
1807                         {
1808                                 faceIndex = RNA_int_get(&itemptr, "face_index");
1809                                 elementIndex = RNA_int_get(&itemptr, "element_index");
1810                                 efa = EDBM_face_at_index(em, faceIndex);
1811                                 element = ED_uv_element_get(state->element_map, efa, BM_iter_at_index(NULL, BM_LOOPS_OF_FACE, efa, elementIndex));
1812                                 stitch_select_uv(element, state, 1);
1813                         }
1814                         RNA_END;
1815                 }
1816                 else {
1817                         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack) * state->total_separate_edges, "uv_stitch_selection_stack");
1818
1819                         RNA_BEGIN (op->ptr, itemptr, "selection")
1820                         {
1821                                 UvEdge tmp_edge, *edge;
1822                                 int uv1, uv2;
1823                                 faceIndex = RNA_int_get(&itemptr, "face_index");
1824                                 elementIndex = RNA_int_get(&itemptr, "element_index");
1825                                 efa = EDBM_face_at_index(em, faceIndex);
1826                                 element = ED_uv_element_get(state->element_map, efa, BM_iter_at_index(NULL, BM_LOOPS_OF_FACE, efa, elementIndex));
1827                                 uv1 = map[element - state->element_map->buf];
1828
1829                                 element = ED_uv_element_get(state->element_map, efa, BM_iter_at_index(NULL, BM_LOOPS_OF_FACE, efa, (elementIndex + 1) % efa->len));
1830                                 uv2 = map[element - state->element_map->buf];
1831
1832                                 if (uv1 < uv2) {
1833                                         tmp_edge.uv1 = uv1;
1834                                         tmp_edge.uv2 = uv2;
1835                                 }
1836                                 else {
1837                                         tmp_edge.uv1 = uv2;
1838                                         tmp_edge.uv2 = uv1;
1839                                 }
1840
1841                                 edge = BLI_ghash_lookup(edge_hash, &tmp_edge);
1842
1843                                 stitch_select_edge(edge, state, TRUE);
1844                         }
1845                         RNA_END;
1846                 }
1847                 /* if user has switched the operator mode after operation, we need to convert
1848                  * the stored format */
1849                 if (state->mode != stored_mode) {
1850                         state->mode = stored_mode;
1851                         stitch_switch_selection_mode(state);
1852                 }
1853                 /* Clear the selection */
1854                 RNA_collection_clear(op->ptr, "selection");
1855
1856         }
1857         else {
1858                 if (state->mode == STITCH_VERT) {
1859                         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack) * state->total_separate_uvs, "uv_stitch_selection_stack");
1860
1861                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1862                                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1863                                         if (uvedit_uv_select_test(em, scene, l)) {
1864                                                 UvElement *element = ED_uv_element_get(state->element_map, efa, l);
1865                                                 if (element) {
1866                                                         stitch_select_uv(element, state, 1);
1867                                                 }
1868                                         }
1869                                 }
1870                         }
1871                 }
1872                 else {
1873                         state->selection_stack = MEM_mallocN(sizeof(*state->selection_stack) * state->total_separate_edges, "uv_stitch_selection_stack");
1874
1875                         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1876                                 BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
1877                                         if (uvedit_edge_select_test(em, scene, l)) {
1878                                                 UvEdge *edge = uv_edge_get(l, state);
1879                                                 if (edge) {
1880                                                         stitch_select_edge(edge, state, TRUE);
1881                                                 }
1882                                         }
1883                                 }
1884                         }
1885                 }
1886         }
1887
1888         /***** initialize static island preview data *****/
1889
1890         state->tris_per_island = MEM_mallocN(sizeof(*state->tris_per_island) * state->element_map->totalIslands,
1891                                              "stitch island tris");
1892         for (i = 0; i < state->element_map->totalIslands; i++) {
1893                 state->tris_per_island[i] = 0;
1894         }
1895
1896         BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
1897                 UvElement *element = ED_uv_element_get(state->element_map, efa, BM_FACE_FIRST_LOOP(efa));
1898
1899                 if (element) {
1900                         state->tris_per_island[element->island] += (efa->len > 2) ? efa->len - 2 : 0;
1901                 }
1902         }
1903
1904         if (!stitch_process_data(state, scene, FALSE)) {
1905
1906                 state_delete(state);
1907                 return 0;
1908         }
1909
1910         stitch_update_header(state, C);
1911         return 1;
1912 }
1913
1914 static int stitch_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1915 {
1916         Object *obedit = CTX_data_edit_object(C);
1917         if (!stitch_init(C, op))
1918                 return OPERATOR_CANCELLED;
1919
1920         WM_event_add_modal_handler(C, op);
1921         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1922         return OPERATOR_RUNNING_MODAL;
1923 }
1924
1925 static void stitch_exit(bContext *C, wmOperator *op, int finished)
1926 {
1927         StitchState *state;
1928         Scene *scene;
1929         SpaceImage *sima;
1930         ScrArea *sa = CTX_wm_area(C);
1931         Object *obedit;
1932
1933         scene = CTX_data_scene(C);
1934         obedit = CTX_data_edit_object(C);
1935         sima = CTX_wm_space_image(C);
1936
1937         state = (StitchState *)op->customdata;
1938
1939         if (finished) {
1940                 int i;
1941
1942                 RNA_float_set(op->ptr, "limit", state->limit_dist);
1943                 RNA_boolean_set(op->ptr, "use_limit", state->use_limit);
1944                 RNA_boolean_set(op->ptr, "snap_islands", state->snap_islands);
1945                 RNA_int_set(op->ptr, "static_island", state->static_island);
1946                 RNA_boolean_set(op->ptr, "midpoint_snap", state->midpoints);
1947                 RNA_enum_set(op->ptr, "mode", state->mode);
1948                 RNA_enum_set(op->ptr, "stored_mode", state->mode);
1949
1950                 /* Store selection for re-execution of stitch */
1951                 for (i = 0; i < state->selection_size; i++) {
1952                         UvElement *element;
1953                         PointerRNA itemptr;
1954                         if (state->mode == STITCH_VERT) {
1955                                 element = state->selection_stack[i];
1956                         }
1957                         else {
1958                                 element = ((UvEdge *)state->selection_stack[i])->element;
1959                         }
1960                         RNA_collection_add(op->ptr, "selection", &itemptr);
1961
1962                         RNA_int_set(&itemptr, "face_index", BM_elem_index_get(element->l->f));
1963                         RNA_int_set(&itemptr, "element_index", element->tfindex);
1964                 }
1965
1966                 uvedit_live_unwrap_update(sima, scene, obedit);
1967         }
1968
1969         if (sa)
1970                 ED_area_headerprint(sa, NULL);
1971
1972         ED_region_draw_cb_exit(CTX_wm_region(C)->type, state->draw_handle);
1973
1974         DAG_id_tag_update(obedit->data, 0);
1975         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1976
1977         state_delete(state);
1978         op->customdata = NULL;
1979 }
1980
1981
1982 static int stitch_cancel(bContext *C, wmOperator *op)
1983 {
1984         stitch_exit(C, op, 0);
1985         return OPERATOR_CANCELLED;
1986 }
1987
1988
1989 static int stitch_exec(bContext *C, wmOperator *op)
1990 {
1991         Scene *scene = CTX_data_scene(C);
1992
1993         if (!stitch_init(C, op))
1994                 return OPERATOR_CANCELLED;
1995         if (stitch_process_data((StitchState *)op->customdata, scene, 1)) {
1996                 stitch_exit(C, op, 1);
1997                 return OPERATOR_FINISHED;
1998         }
1999         else {
2000                 return stitch_cancel(C, op);
2001         }
2002 }
2003
2004 static void stitch_select(bContext *C, Scene *scene, const wmEvent *event, StitchState *state)
2005 {
2006         /* add uv under mouse to processed uv's */
2007         float co[2];
2008         NearestHit hit;
2009         ARegion *ar = CTX_wm_region(C);
2010         Image *ima = CTX_data_edit_image(C);
2011
2012         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
2013
2014         if (state->mode == STITCH_VERT) {
2015                 uv_find_nearest_vert(scene, ima, state->em, co, NULL, &hit);
2016
2017                 if (hit.efa) {
2018                         /* Add vertex to selection, deselect all common uv's of vert other
2019                          * than selected and update the preview. This behavior was decided so that
2020                          * you can do stuff like deselect the opposite stitchable vertex and the initial still gets deselected */
2021
2022                         /* This works due to setting of tmp in find nearest uv vert */
2023                         UvElement *element = ED_uv_element_get(state->element_map, hit.efa, hit.l);
2024                         stitch_select_uv(element, state, FALSE);
2025
2026                 }
2027         }
2028         else {
2029                 uv_find_nearest_edge(scene, ima, state->em, co, &hit);
2030
2031                 if (hit.efa) {
2032                         UvEdge *edge = uv_edge_get(hit.l, state);
2033                         stitch_select_edge(edge, state, FALSE);
2034                 }
2035         }
2036 }
2037
2038 static int stitch_modal(bContext *C, wmOperator *op, const wmEvent *event)
2039 {
2040         StitchState *state;
2041         Scene *scene = CTX_data_scene(C);
2042
2043         state = (StitchState *)op->customdata;
2044
2045         switch (event->type) {
2046                 case MIDDLEMOUSE:
2047                         return OPERATOR_PASS_THROUGH;
2048
2049                         /* Cancel */
2050                 case ESCKEY:
2051                         return stitch_cancel(C, op);
2052
2053
2054                 case LEFTMOUSE:
2055                         if (event->shift && (U.flag & USER_LMOUSESELECT)) {
2056                                 if (event->val == KM_PRESS) {
2057                                         stitch_select(C, scene, event, state);
2058
2059                                         if (!stitch_process_data(state, scene, FALSE)) {
2060                                                 return stitch_cancel(C, op);
2061                                         }
2062                                 }
2063                                 break;
2064                         }
2065                 case PADENTER:
2066                 case RETKEY:
2067                         if (event->val == KM_PRESS) {
2068                                 if (stitch_process_data(state, scene, TRUE)) {
2069                                         stitch_exit(C, op, 1);
2070                                         return OPERATOR_FINISHED;
2071                                 }
2072                                 else {
2073                                         return stitch_cancel(C, op);
2074                                 }
2075                         }
2076                         else {
2077                                 return OPERATOR_PASS_THROUGH;
2078                         }
2079                         /* Increase limit */
2080                 case PADPLUSKEY:
2081                 case WHEELUPMOUSE:
2082                         if (event->val == KM_PRESS && event->alt) {
2083                                 state->limit_dist += 0.01f;
2084                                 if (!stitch_process_data(state, scene, FALSE)) {
2085                                         return stitch_cancel(C, op);
2086                                 }
2087                                 break;
2088                         }
2089                         else {
2090                                 return OPERATOR_PASS_THROUGH;
2091                         }
2092                         /* Decrease limit */
2093                 case PADMINUS:
2094                 case WHEELDOWNMOUSE:
2095                         if (event->val == KM_PRESS && event->alt) {
2096                                 state->limit_dist -= 0.01f;
2097                                 state->limit_dist = MAX2(0.01f, state->limit_dist);
2098                                 if (!stitch_process_data(state, scene, FALSE)) {
2099                                         return stitch_cancel(C, op);
2100                                 }
2101                                 break;
2102                         }
2103                         else {
2104                                 return OPERATOR_PASS_THROUGH;
2105                         }
2106
2107                         /* Use Limit (Default off)*/
2108                 case LKEY:
2109                         if (event->val == KM_PRESS) {
2110                                 state->use_limit = !state->use_limit;
2111                                 if (!stitch_process_data(state, scene, FALSE)) {
2112                                         return stitch_cancel(C, op);
2113                                 }
2114                                 break;
2115                         }
2116                         return OPERATOR_RUNNING_MODAL;
2117
2118                 case IKEY:
2119                         if (event->val == KM_PRESS) {
2120                                 state->static_island++;
2121                                 state->static_island %= state->element_map->totalIslands;
2122
2123                                 if (!stitch_process_data(state, scene, FALSE)) {
2124                                         return stitch_cancel(C, op);
2125                                 }
2126                                 break;
2127                         }
2128                         return OPERATOR_RUNNING_MODAL;
2129
2130                 case MKEY:
2131                         if (event->val == KM_PRESS) {
2132                                 state->midpoints = !state->midpoints;
2133                                 if (!stitch_process_data(state, scene, FALSE)) {
2134                                         return stitch_cancel(C, op);
2135                                 }
2136                         }
2137                         break;
2138
2139                         /* Select geometry*/
2140                 case RIGHTMOUSE:
2141                         if (!event->shift) {
2142                                 return stitch_cancel(C, op);
2143                         }
2144                         if (event->val == KM_PRESS && !(U.flag & USER_LMOUSESELECT)) {
2145                                 stitch_select(C, scene, event, state);
2146
2147                                 if (!stitch_process_data(state, scene, FALSE)) {
2148                                         return stitch_cancel(C, op);
2149                                 }
2150                                 break;
2151                         }
2152                         return OPERATOR_RUNNING_MODAL;
2153
2154                         /* snap islands on/off */
2155                 case SKEY:
2156                         if (event->val == KM_PRESS) {
2157                                 state->snap_islands = !state->snap_islands;
2158                                 if (!stitch_process_data(state, scene, FALSE)) {
2159                                         return stitch_cancel(C, op);
2160                                 }
2161                                 break;
2162                         }
2163                         else {
2164                                 return OPERATOR_RUNNING_MODAL;
2165                         }
2166
2167                         /* switch between edge/vertex mode */
2168                 case TABKEY:
2169                         if (event->val == KM_PRESS) {
2170                                 stitch_switch_selection_mode(state);
2171
2172                                 if (!stitch_process_data(state, scene, FALSE)) {
2173                                         return stitch_cancel(C, op);
2174                                 }
2175                         }
2176                         break;
2177
2178                 default:
2179                         return OPERATOR_RUNNING_MODAL;
2180         }
2181
2182         /* if updated settings, renew feedback message */
2183         stitch_update_header(state, C);
2184         ED_region_tag_redraw(CTX_wm_region(C));
2185         return OPERATOR_RUNNING_MODAL;
2186 }
2187
2188 void UV_OT_stitch(wmOperatorType *ot)
2189 {
2190         PropertyRNA *prop;
2191
2192         static EnumPropertyItem stitch_modes[] = {
2193             {STITCH_VERT, "VERTEX", 0, "Vertex", ""},
2194             {STITCH_EDGE, "EDGE", 0, "Edge", ""},
2195             {0, NULL, 0, NULL, NULL}
2196         };
2197
2198         /* identifiers */
2199         ot->name = "Stitch";
2200         ot->description = "Stitch selected UV vertices by proximity";
2201         ot->idname = "UV_OT_stitch";
2202         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2203         
2204         /* api callbacks */
2205         ot->invoke = stitch_invoke;
2206         ot->modal = stitch_modal;
2207         ot->exec = stitch_exec;
2208         ot->cancel = stitch_cancel;
2209         ot->poll = ED_operator_uvedit;
2210
2211         /* properties */
2212         RNA_def_boolean(ot->srna, "use_limit", 0, "Use Limit", "Stitch UVs within a specified limit distance");
2213         RNA_def_boolean(ot->srna, "snap_islands", 1, "Snap Islands",
2214                         "Snap islands together (on edge stitch mode, rotates the islands too)");
2215
2216         RNA_def_float(ot->srna, "limit", 0.01f, 0.0f, FLT_MAX, "Limit",
2217                       "Limit distance in normalized coordinates", 0.0, FLT_MAX);
2218         RNA_def_int(ot->srna, "static_island", 0, 0, INT_MAX, "Static Island",
2219                     "Island that stays in place when stitching islands", 0, INT_MAX);
2220         RNA_def_boolean(ot->srna, "midpoint_snap", 0, "Snap At Midpoint",
2221                         "UVs are stitched at midpoint instead of at static island");
2222         RNA_def_boolean(ot->srna, "clear_seams", 1, "Clear Seams",
2223                         "Clear seams of stitched edges");
2224         RNA_def_enum(ot->srna, "mode", stitch_modes, STITCH_VERT, "Operation Mode",
2225                      "Use vertex or edge stitching");
2226         prop =  RNA_def_enum(ot->srna, "stored_mode", stitch_modes, STITCH_VERT, "Stored Operation Mode",
2227                              "Use vertex or edge stitching");
2228         RNA_def_property_flag(prop, PROP_HIDDEN);
2229         prop = RNA_def_collection_runtime(ot->srna, "selection", &RNA_SelectedUvElement, "Selection", "");
2230         /* Selection should not be editable or viewed in toolbar */
2231         RNA_def_property_flag(prop, PROP_HIDDEN);
2232 }