7e30c8b5b23dc244d5b103cdc9605197597da482
[blender.git] / source / blender / editors / sculpt_paint / sculpt_uv.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) Blender Foundation, 2002-2009
19  * All rights reserved.
20  *
21  * Contributor(s): Antony Riakiotakis
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * UV Sculpt tools
26  *
27  */
28
29 /** \file blender/editors/sculpt_paint/sculpt_uv.c
30  *  \ingroup edsculpt
31  */
32
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_utildefines.h"
37 #include "BLI_math.h"
38 #include "BLI_ghash.h"
39
40 #include "DNA_object_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_brush_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BKE_brush.h"
46 #include "BKE_colortools.h"
47 #include "BKE_context.h"
48 #include "BKE_customdata.h"
49 #include "BKE_depsgraph.h"
50 #include "BKE_editmesh.h"
51 #include "BKE_main.h"
52 #include "BKE_mesh_mapping.h"
53 #include "BKE_paint.h"
54
55 #include "ED_screen.h"
56 #include "ED_image.h"
57 #include "ED_mesh.h"
58
59 #include "WM_api.h"
60 #include "WM_types.h"
61
62 #include "RNA_access.h"
63 #include "RNA_define.h"
64
65 #include "paint_intern.h"
66 #include "uvedit_intern.h"
67
68 #include "BIF_gl.h"
69 #include "BIF_glutil.h"
70
71 #include "UI_view2d.h"
72
73 #define MARK_BOUNDARY   1
74
75 typedef struct UvAdjacencyElement {
76         /* pointer to original uvelement */
77         UvElement *element;
78         /* uv pointer for convenience. Caution, this points to the original UVs! */
79         float *uv;
80         /* general use flag (Used to check if Element is boundary here) */
81         char flag;
82 } UvAdjacencyElement;
83
84 typedef struct UvEdge {
85         unsigned int uv1;
86         unsigned int uv2;
87         /* general use flag (Used to check if edge is boundary here, and propagates to adjacency elements) */
88         char flag;
89 } UvEdge;
90
91 typedef struct UVInitialStrokeElement {
92         /* index to unique uv */
93         int uv;
94
95         /* strength of brush on initial position */
96         float strength;
97
98         /* initial uv position */
99         float initial_uv[2];
100 } UVInitialStrokeElement;
101
102 typedef struct UVInitialStroke {
103         /* Initial Selection,for grab brushes for instance */
104         UVInitialStrokeElement *initialSelection;
105
106         /* total initially selected UVs*/
107         int totalInitialSelected;
108
109         /* initial mouse coordinates */
110         float init_coord[2];
111 } UVInitialStroke;
112
113
114 /* custom data for uv smoothing brush */
115 typedef struct UvSculptData {
116         /* Contains the first of each set of coincident uvs.
117          * These will be used to perform smoothing on and propagate the changes
118          * to their coincident uvs */
119         UvAdjacencyElement *uv;
120
121         /* ...Is what it says */
122         int totalUniqueUvs;
123
124         /* Edges used for adjacency info, used with laplacian smoothing */
125         UvEdge *uvedges;
126
127         /* need I say more? */
128         int totalUvEdges;
129
130         /* data for initial stroke, used by tools like grab */
131         UVInitialStroke *initial_stroke;
132
133         /* timer to be used for airbrush-type brush */
134         wmTimer *timer;
135
136         /* to determine quickly adjacent uvs */
137         UvElementMap *elementMap;
138
139         /* uvsmooth Paint for fast reference */
140         Paint *uvsculpt;
141
142         /* tool to use. duplicating here to change if modifier keys are pressed */
143         char tool;
144
145         /* store invert flag here */
146         char invert;
147 } UvSculptData;
148
149
150 static Brush *uv_sculpt_brush(bContext *C)
151 {
152         Scene *scene = CTX_data_scene(C);
153         ToolSettings *settings = scene->toolsettings;
154
155         if (!settings->uvsculpt)
156                 return NULL;
157         return BKE_paint_brush(&settings->uvsculpt->paint);
158 }
159
160
161 static bool uv_sculpt_brush_poll_do(bContext *C, const bool check_region)
162 {
163         BMEditMesh *em;
164         int ret;
165         Object *obedit = CTX_data_edit_object(C);
166         SpaceImage *sima = CTX_wm_space_image(C);
167         Scene *scene = CTX_data_scene(C);
168         ToolSettings *toolsettings = scene->toolsettings;
169
170         if (!uv_sculpt_brush(C) || !obedit || obedit->type != OB_MESH ||
171             !sima || ED_space_image_show_render(sima) || (sima->mode == SI_MODE_PAINT))
172         {
173                 return 0;
174         }
175
176         em = BKE_editmesh_from_object(obedit);
177         ret = EDBM_uv_check(em);
178
179         if (ret) {
180                 ARegion *ar = CTX_wm_region(C);
181                 if ((!toolsettings->use_uv_sculpt) || (check_region && ar && (ar->regiontype != RGN_TYPE_WINDOW))) {
182                         ret = 0;
183                 }
184         }
185
186         return ret;
187 }
188
189 static bool uv_sculpt_brush_poll(bContext *C)
190 {
191         return uv_sculpt_brush_poll_do(C, true);
192 }
193
194 static void brush_drawcursor_uvsculpt(bContext *C, int x, int y, void *UNUSED(customdata))
195 {
196 #define PX_SIZE_FADE_MAX 12.0f
197 #define PX_SIZE_FADE_MIN 4.0f
198
199         Scene *scene = CTX_data_scene(C);
200         //Brush *brush = image_paint_brush(C);
201         Paint *paint = BKE_paint_get_active_from_context(C);
202         Brush *brush = BKE_paint_brush(paint);
203
204         if (paint && brush && paint->flags & PAINT_SHOW_BRUSH) {
205                 const float size = (float)BKE_brush_size_get(scene, brush);
206                 float alpha = 0.5f;
207
208                 /* fade out the brush (cheap trick to work around brush interfering with sampling [#])*/
209                 if (size < PX_SIZE_FADE_MIN) {
210                         return;
211                 }
212                 else if (size < PX_SIZE_FADE_MAX) {
213                         alpha *= (size - PX_SIZE_FADE_MIN) / (PX_SIZE_FADE_MAX - PX_SIZE_FADE_MIN);
214                 }
215
216                 glPushMatrix();
217
218                 glTranslatef((float)x, (float)y, 0.0f);
219
220                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], alpha);
221                 glEnable(GL_LINE_SMOOTH);
222                 glEnable(GL_BLEND);
223                 glutil_draw_lined_arc(0, (float)(M_PI * 2.0), size, 40);
224                 glDisable(GL_BLEND);
225                 glDisable(GL_LINE_SMOOTH);
226
227                 glPopMatrix();
228         }
229 #undef PX_SIZE_FADE_MAX
230 #undef PX_SIZE_FADE_MIN
231 }
232
233
234 void ED_space_image_uv_sculpt_update(Main *bmain, wmWindowManager *wm, Scene *scene)
235 {
236         ToolSettings *settings = scene->toolsettings;
237         if (settings->use_uv_sculpt) {
238                 if (!settings->uvsculpt) {
239                         settings->uvsculpt = MEM_callocN(sizeof(*settings->uvsculpt), "UV Smooth paint");
240                         settings->uv_sculpt_tool = UV_SCULPT_TOOL_GRAB;
241                         settings->uv_sculpt_settings = UV_SCULPT_LOCK_BORDERS | UV_SCULPT_ALL_ISLANDS;
242                         settings->uv_relax_method = UV_SCULPT_TOOL_RELAX_LAPLACIAN;
243                         /* Uv sculpting does not include explicit brush view control yet, always enable */
244                         settings->uvsculpt->paint.flags |= PAINT_SHOW_BRUSH;
245                 }
246
247                 BKE_paint_init(bmain, scene, ePaintSculptUV, PAINT_CURSOR_SCULPT);
248
249                 settings->uvsculpt->paint.paint_cursor = WM_paint_cursor_activate(
250                         wm, uv_sculpt_brush_poll,
251                         brush_drawcursor_uvsculpt, NULL);
252         }
253         else {
254                 if (settings->uvsculpt) {
255                         WM_paint_cursor_end(wm, settings->uvsculpt->paint.paint_cursor);
256                         settings->uvsculpt->paint.paint_cursor = NULL;
257                 }
258         }
259 }
260
261 bool uv_sculpt_poll(bContext *C)
262 {
263         return uv_sculpt_brush_poll_do(C, true);
264 }
265
266 bool uv_sculpt_keymap_poll(bContext *C)
267 {
268         return uv_sculpt_brush_poll_do(C, false);
269 }
270
271 /*********** Improved Laplacian Relaxation Operator ************************/
272 /* original code by Raul Fernandez Hernandez "farsthary"                   *
273  * adapted to uv smoothing by Antony Riakiatakis                           *
274  ***************************************************************************/
275
276 typedef struct Temp_UvData {
277         float sum_co[2], p[2], b[2], sum_b[2];
278         int ncounter;
279 } Temp_UVData;
280
281
282
283 static void HC_relaxation_iteration_uv(BMEditMesh *em, UvSculptData *sculptdata, float mouse_coord[2],
284                                        float alpha, float radius, float aspectRatio)
285 {
286         Temp_UVData *tmp_uvdata;
287         float diff[2];
288         int i;
289         float radius_root = sqrtf(radius);
290         Brush *brush = BKE_paint_brush(sculptdata->uvsculpt);
291
292         tmp_uvdata = (Temp_UVData *)MEM_callocN(sculptdata->totalUniqueUvs * sizeof(Temp_UVData), "Temporal data");
293
294         /* counting neighbors */
295         for (i = 0; i < sculptdata->totalUvEdges; i++) {
296                 UvEdge *tmpedge = sculptdata->uvedges + i;
297                 tmp_uvdata[tmpedge->uv1].ncounter++;
298                 tmp_uvdata[tmpedge->uv2].ncounter++;
299
300                 add_v2_v2(tmp_uvdata[tmpedge->uv2].sum_co, sculptdata->uv[tmpedge->uv1].uv);
301                 add_v2_v2(tmp_uvdata[tmpedge->uv1].sum_co, sculptdata->uv[tmpedge->uv2].uv);
302         }
303
304         for (i = 0; i < sculptdata->totalUniqueUvs; i++) {
305                 copy_v2_v2(diff, tmp_uvdata[i].sum_co);
306                 mul_v2_fl(diff, 1.f / tmp_uvdata[i].ncounter);
307                 copy_v2_v2(tmp_uvdata[i].p, diff);
308
309                 tmp_uvdata[i].b[0] = diff[0] - sculptdata->uv[i].uv[0];
310                 tmp_uvdata[i].b[1] = diff[1] - sculptdata->uv[i].uv[1];
311         }
312
313         for (i = 0; i < sculptdata->totalUvEdges; i++) {
314                 UvEdge *tmpedge = sculptdata->uvedges + i;
315                 add_v2_v2(tmp_uvdata[tmpedge->uv1].sum_b, tmp_uvdata[tmpedge->uv2].b);
316                 add_v2_v2(tmp_uvdata[tmpedge->uv2].sum_b, tmp_uvdata[tmpedge->uv1].b);
317         }
318
319         for (i = 0; i < sculptdata->totalUniqueUvs; i++) {
320                 float dist;
321                 /* This is supposed to happen only if "Pin Edges" is on, since we have initialization on stroke start
322                  * If ever uv brushes get their own mode we should check for toolsettings option too */
323                 if ((sculptdata->uv[i].flag & MARK_BOUNDARY)) {
324                         continue;
325                 }
326
327                 sub_v2_v2v2(diff, sculptdata->uv[i].uv, mouse_coord);
328                 diff[1] /= aspectRatio;
329                 if ((dist = dot_v2v2(diff, diff)) <= radius) {
330                         UvElement *element;
331                         float strength;
332                         strength = alpha * BKE_brush_curve_strength_clamped(brush, sqrtf(dist), radius_root);
333
334                         sculptdata->uv[i].uv[0] = (1.0f - strength) * sculptdata->uv[i].uv[0] + strength * (tmp_uvdata[i].p[0] - 0.5f * (tmp_uvdata[i].b[0] + tmp_uvdata[i].sum_b[0] / tmp_uvdata[i].ncounter));
335                         sculptdata->uv[i].uv[1] = (1.0f - strength) * sculptdata->uv[i].uv[1] + strength * (tmp_uvdata[i].p[1] - 0.5f * (tmp_uvdata[i].b[1] + tmp_uvdata[i].sum_b[1] / tmp_uvdata[i].ncounter));
336
337                         for (element = sculptdata->uv[i].element; element; element = element->next) {
338                                 MLoopUV *luv;
339                                 BMLoop *l;
340
341                                 if (element->separate && element != sculptdata->uv[i].element)
342                                         break;
343
344                                 l = element->l;
345                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
346                                 copy_v2_v2(luv->uv, sculptdata->uv[i].uv);
347                         }
348                 }
349         }
350
351         MEM_freeN(tmp_uvdata);
352
353         return;
354 }
355
356 static void laplacian_relaxation_iteration_uv(BMEditMesh *em, UvSculptData *sculptdata, float mouse_coord[2], float alpha, float radius, float aspectRatio)
357 {
358         Temp_UVData *tmp_uvdata;
359         float diff[2];
360         int i;
361         float radius_root = sqrtf(radius);
362         Brush *brush = BKE_paint_brush(sculptdata->uvsculpt);
363
364         tmp_uvdata = (Temp_UVData *)MEM_callocN(sculptdata->totalUniqueUvs * sizeof(Temp_UVData), "Temporal data");
365
366         /* counting neighbors */
367         for (i = 0; i < sculptdata->totalUvEdges; i++) {
368                 UvEdge *tmpedge = sculptdata->uvedges + i;
369                 tmp_uvdata[tmpedge->uv1].ncounter++;
370                 tmp_uvdata[tmpedge->uv2].ncounter++;
371
372                 add_v2_v2(tmp_uvdata[tmpedge->uv2].sum_co, sculptdata->uv[tmpedge->uv1].uv);
373                 add_v2_v2(tmp_uvdata[tmpedge->uv1].sum_co, sculptdata->uv[tmpedge->uv2].uv);
374         }
375
376         /* Original Lacplacian algorithm included removal of normal component of translation. here it is not
377          * needed since we translate along the UV plane always.*/
378         for (i = 0; i < sculptdata->totalUniqueUvs; i++) {
379                 copy_v2_v2(tmp_uvdata[i].p, tmp_uvdata[i].sum_co);
380                 mul_v2_fl(tmp_uvdata[i].p, 1.f / tmp_uvdata[i].ncounter);
381         }
382
383         for (i = 0; i < sculptdata->totalUniqueUvs; i++) {
384                 float dist;
385                 /* This is supposed to happen only if "Pin Edges" is on, since we have initialization on stroke start
386                  * If ever uv brushes get their own mode we should check for toolsettings option too */
387                 if ((sculptdata->uv[i].flag & MARK_BOUNDARY)) {
388                         continue;
389                 }
390
391                 sub_v2_v2v2(diff, sculptdata->uv[i].uv, mouse_coord);
392                 diff[1] /= aspectRatio;
393                 if ((dist = dot_v2v2(diff, diff)) <= radius) {
394                         UvElement *element;
395                         float strength;
396                         strength = alpha * BKE_brush_curve_strength_clamped(brush, sqrtf(dist), radius_root);
397
398                         sculptdata->uv[i].uv[0] = (1.0f - strength) * sculptdata->uv[i].uv[0] + strength * tmp_uvdata[i].p[0];
399                         sculptdata->uv[i].uv[1] = (1.0f - strength) * sculptdata->uv[i].uv[1] + strength * tmp_uvdata[i].p[1];
400
401                         for (element = sculptdata->uv[i].element; element; element = element->next) {
402                                 MLoopUV *luv;
403                                 BMLoop *l;
404
405                                 if (element->separate && element != sculptdata->uv[i].element)
406                                         break;
407
408                                 l = element->l;
409                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
410                                 copy_v2_v2(luv->uv, sculptdata->uv[i].uv);
411                         }
412                 }
413         }
414
415         MEM_freeN(tmp_uvdata);
416
417         return;
418 }
419
420
421 static void uv_sculpt_stroke_apply(bContext *C, wmOperator *op, const wmEvent *event, Object *obedit)
422 {
423         float co[2], radius, radius_root;
424         Scene *scene = CTX_data_scene(C);
425         ARegion *ar = CTX_wm_region(C);
426         BMEditMesh *em = BKE_editmesh_from_object(obedit);
427         unsigned int tool;
428         UvSculptData *sculptdata = (UvSculptData *)op->customdata;
429         SpaceImage *sima;
430         int invert;
431         int width, height;
432         float aspectRatio;
433         float alpha, zoomx, zoomy;
434         Brush *brush = BKE_paint_brush(sculptdata->uvsculpt);
435         ToolSettings *toolsettings = CTX_data_tool_settings(C);
436         tool = sculptdata->tool;
437         invert = sculptdata->invert ? -1 : 1;
438         alpha = BKE_brush_alpha_get(scene, brush);
439         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
440
441         sima = CTX_wm_space_image(C);
442         ED_space_image_get_size(sima, &width, &height);
443         ED_space_image_get_zoom(sima, ar, &zoomx, &zoomy);
444
445         radius = BKE_brush_size_get(scene, brush) / (width * zoomx);
446         aspectRatio = width / (float)height;
447
448         /* We will compare squares to save some computation */
449         radius = radius * radius;
450         radius_root = sqrtf(radius);
451
452         /*
453          * Pinch Tool
454          */
455         if (tool == UV_SCULPT_TOOL_PINCH) {
456                 int i;
457                 alpha *= invert;
458                 for (i = 0; i < sculptdata->totalUniqueUvs; i++) {
459                         float dist, diff[2];
460                         /* This is supposed to happen only if "Lock Borders" is on, since we have initialization on stroke start
461                          * If ever uv brushes get their own mode we should check for toolsettings option too */
462                         if (sculptdata->uv[i].flag & MARK_BOUNDARY) {
463                                 continue;
464                         }
465
466                         sub_v2_v2v2(diff, sculptdata->uv[i].uv, co);
467                         diff[1] /= aspectRatio;
468                         if ((dist = dot_v2v2(diff, diff)) <= radius) {
469                                 UvElement *element;
470                                 float strength;
471                                 strength = alpha * BKE_brush_curve_strength_clamped(brush, sqrtf(dist), radius_root);
472                                 normalize_v2(diff);
473
474                                 sculptdata->uv[i].uv[0] -= strength * diff[0] * 0.001f;
475                                 sculptdata->uv[i].uv[1] -= strength * diff[1] * 0.001f;
476
477                                 for (element = sculptdata->uv[i].element; element; element = element->next) {
478                                         MLoopUV *luv;
479                                         BMLoop *l;
480
481                                         if (element->separate && element != sculptdata->uv[i].element)
482                                                 break;
483
484                                         l = element->l;
485                                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
486                                         copy_v2_v2(luv->uv, sculptdata->uv[i].uv);
487                                 }
488                         }
489                 }
490         }
491
492         /*
493          * Smooth Tool
494          */
495         else if (tool == UV_SCULPT_TOOL_RELAX) {
496                 unsigned int method = toolsettings->uv_relax_method;
497                 if (method == UV_SCULPT_TOOL_RELAX_HC) {
498                         HC_relaxation_iteration_uv(em, sculptdata, co, alpha, radius, aspectRatio);
499                 }
500                 else {
501                         laplacian_relaxation_iteration_uv(em, sculptdata, co, alpha, radius, aspectRatio);
502                 }
503         }
504
505         /*
506          * Grab Tool
507          */
508         else if (tool == UV_SCULPT_TOOL_GRAB) {
509                 int i;
510                 float diff[2];
511                 sub_v2_v2v2(diff, co, sculptdata->initial_stroke->init_coord);
512
513                 for (i = 0; i < sculptdata->initial_stroke->totalInitialSelected; i++) {
514                         UvElement *element;
515                         int uvindex = sculptdata->initial_stroke->initialSelection[i].uv;
516                         float strength = sculptdata->initial_stroke->initialSelection[i].strength;
517                         sculptdata->uv[uvindex].uv[0] = sculptdata->initial_stroke->initialSelection[i].initial_uv[0] + strength * diff[0];
518                         sculptdata->uv[uvindex].uv[1] = sculptdata->initial_stroke->initialSelection[i].initial_uv[1] + strength * diff[1];
519
520                         for (element = sculptdata->uv[uvindex].element; element; element = element->next) {
521                                 MLoopUV *luv;
522                                 BMLoop *l;
523
524                                 if (element->separate && element != sculptdata->uv[uvindex].element)
525                                         break;
526
527                                 l = element->l;
528                                 luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
529                                 copy_v2_v2(luv->uv, sculptdata->uv[uvindex].uv);
530                         }
531                 }
532         }
533 }
534
535
536 static void uv_sculpt_stroke_exit(bContext *C, wmOperator *op)
537 {
538         UvSculptData *data = op->customdata;
539         if (data->timer) {
540                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), data->timer);
541         }
542         if (data->elementMap) {
543                 BM_uv_element_map_free(data->elementMap);
544         }
545         if (data->uv) {
546                 MEM_freeN(data->uv);
547         }
548         if (data->uvedges) {
549                 MEM_freeN(data->uvedges);
550         }
551         if (data->initial_stroke) {
552                 if (data->initial_stroke->initialSelection) {
553                         MEM_freeN(data->initial_stroke->initialSelection);
554                 }
555                 MEM_freeN(data->initial_stroke);
556         }
557
558         MEM_freeN(data);
559         op->customdata = NULL;
560 }
561
562 static int uv_element_offset_from_face_get(UvElementMap *map, BMFace *efa, BMLoop *l, int island_index, const bool doIslands)
563 {
564         UvElement *element = BM_uv_element_get(map, efa, l);
565         if (!element || (doIslands && element->island != island_index)) {
566                 return -1;
567         }
568         return element - map->buf;
569 }
570
571
572 static unsigned int uv_edge_hash(const void *key)
573 {
574         const UvEdge *edge = key;
575         return (BLI_ghashutil_uinthash(edge->uv2) +
576                 BLI_ghashutil_uinthash(edge->uv1));
577 }
578
579 static bool uv_edge_compare(const void *a, const void *b)
580 {
581         const UvEdge *edge1 = a;
582         const UvEdge *edge2 = b;
583
584         if ((edge1->uv1 == edge2->uv1) && (edge1->uv2 == edge2->uv2)) {
585                 return 0;
586         }
587         return 1;
588 }
589
590
591 static UvSculptData *uv_sculpt_stroke_init(bContext *C, wmOperator *op, const wmEvent *event)
592 {
593         Scene *scene = CTX_data_scene(C);
594         Object *obedit = CTX_data_edit_object(C);
595         ToolSettings *ts = scene->toolsettings;
596         UvSculptData *data = MEM_callocN(sizeof(*data), "UV Smooth Brush Data");
597         BMEditMesh *em = BKE_editmesh_from_object(obedit);
598         BMesh *bm = em->bm;
599
600         op->customdata = data;
601
602         curvemapping_initialize(ts->uvsculpt->paint.brush->curve);
603
604         if (data) {
605                 int counter = 0, i;
606                 ARegion *ar = CTX_wm_region(C);
607                 float co[2];
608                 BMFace *efa;
609                 MLoopUV *luv;
610                 BMLoop *l;
611                 BMIter iter, liter;
612
613                 UvEdge *edges;
614                 GHash *edgeHash;
615                 GHashIterator gh_iter;
616
617                 bool do_island_optimization = !(ts->uv_sculpt_settings & UV_SCULPT_ALL_ISLANDS);
618                 int island_index = 0;
619                 /* Holds, for each UvElement in elementMap, a pointer to its unique uv.*/
620                 int *uniqueUv;
621                 data->tool = (RNA_enum_get(op->ptr, "mode") == BRUSH_STROKE_SMOOTH) ? UV_SCULPT_TOOL_RELAX : ts->uv_sculpt_tool;
622                 data->invert = (RNA_enum_get(op->ptr, "mode") == BRUSH_STROKE_INVERT) ? 1 : 0;
623
624                 data->uvsculpt = &ts->uvsculpt->paint;
625
626                 if (do_island_optimization) {
627                         /* We will need island information */
628                         if (ts->uv_flag & UV_SYNC_SELECTION) {
629                                 data->elementMap = BM_uv_element_map_create(bm, false, true, true);
630                         }
631                         else {
632                                 data->elementMap = BM_uv_element_map_create(bm, true, true, true);
633                         }
634                 }
635                 else {
636                         if (ts->uv_flag & UV_SYNC_SELECTION) {
637                                 data->elementMap = BM_uv_element_map_create(bm, false, true, false);
638                         }
639                         else {
640                                 data->elementMap = BM_uv_element_map_create(bm, true, true, false);
641                         }
642                 }
643
644                 if (!data->elementMap) {
645                         uv_sculpt_stroke_exit(C, op);
646                         return NULL;
647                 }
648
649                 /* Mouse coordinates, useful for some functions like grab and sculpt all islands */
650                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
651
652                 /* we need to find the active island here */
653                 if (do_island_optimization) {
654                         UvElement *element;
655                         UvNearestHit hit = UV_NEAREST_HIT_INIT;
656                         Image *ima = CTX_data_edit_image(C);
657                         uv_find_nearest_vert(scene, ima, em, co, 0.0f, &hit);
658
659                         element = BM_uv_element_get(data->elementMap, hit.efa, hit.l);
660                         island_index = element->island;
661                 }
662
663
664                 /* Count 'unique' uvs */
665                 for (i = 0; i < data->elementMap->totalUVs; i++) {
666                         if (data->elementMap->buf[i].separate &&
667                             (!do_island_optimization || data->elementMap->buf[i].island == island_index))
668                         {
669                                 counter++;
670                         }
671                 }
672
673                 /* Allocate the unique uv buffers */
674                 data->uv = MEM_mallocN(sizeof(*data->uv) * counter, "uv_brush_unique_uvs");
675                 uniqueUv = MEM_mallocN(sizeof(*uniqueUv) * data->elementMap->totalUVs, "uv_brush_unique_uv_map");
676                 edgeHash = BLI_ghash_new(uv_edge_hash, uv_edge_compare, "uv_brush_edge_hash");
677                 /* we have at most totalUVs edges */
678                 edges = MEM_mallocN(sizeof(*edges) * data->elementMap->totalUVs, "uv_brush_all_edges");
679                 if (!data->uv || !uniqueUv || !edgeHash || !edges) {
680                         if (edges) {
681                                 MEM_freeN(edges);
682                         }
683                         if (uniqueUv) {
684                                 MEM_freeN(uniqueUv);
685                         }
686                         if (edgeHash) {
687                                 BLI_ghash_free(edgeHash, NULL, NULL);
688                         }
689                         uv_sculpt_stroke_exit(C, op);
690                         return NULL;
691                 }
692
693                 data->totalUniqueUvs = counter;
694                 /* So that we can use this as index for the UvElements */
695                 counter = -1;
696                 /* initialize the unique UVs */
697                 for (i = 0; i < bm->totvert; i++) {
698                         UvElement *element = data->elementMap->vert[i];
699                         for (; element; element = element->next) {
700                                 if (element->separate) {
701                                         if (do_island_optimization && (element->island != island_index)) {
702                                                 /* skip this uv if not on the active island */
703                                                 for (; element->next && !(element->next->separate); element = element->next)
704                                                         ;
705                                                 continue;
706                                         }
707
708                                         l = element->l;
709                                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
710
711                                         counter++;
712                                         data->uv[counter].element = element;
713                                         data->uv[counter].flag = 0;
714                                         data->uv[counter].uv = luv->uv;
715                                 }
716                                 /* pointer arithmetic to the rescue, as always :)*/
717                                 uniqueUv[element - data->elementMap->buf] = counter;
718                         }
719                 }
720
721
722                 /* Now, on to generate our uv connectivity data */
723                 counter = 0;
724                 BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
725                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
726                                 int offset1, itmp1 = uv_element_offset_from_face_get(data->elementMap, efa, l, island_index, do_island_optimization);
727                                 int offset2, itmp2 = uv_element_offset_from_face_get(data->elementMap, efa, l->next, island_index, do_island_optimization);
728                                 char *flag;
729
730                                 /* Skip edge if not found(unlikely) or not on valid island */
731                                 if (itmp1 == -1 || itmp2 == -1)
732                                         continue;
733
734                                 offset1 = uniqueUv[itmp1];
735                                 offset2 = uniqueUv[itmp2];
736
737                                 edges[counter].flag = 0;
738                                 /* using an order policy, sort uvs according to address space. This avoids
739                                  * Having two different UvEdges with the same uvs on different positions  */
740                                 if (offset1 < offset2) {
741                                         edges[counter].uv1 = offset1;
742                                         edges[counter].uv2 = offset2;
743                                 }
744                                 else {
745                                         edges[counter].uv1 = offset2;
746                                         edges[counter].uv2 = offset1;
747                                 }
748                                 /* Hack! Set the value of the key to its flag. Now we can set the flag when an edge exists twice :) */
749                                 flag = BLI_ghash_lookup(edgeHash, &edges[counter]);
750                                 if (flag) {
751                                         *flag = 1;
752                                 }
753                                 else {
754                                         /* Hack mentioned */
755                                         BLI_ghash_insert(edgeHash, &edges[counter], &edges[counter].flag);
756                                 }
757                                 counter++;
758                         }
759                 }
760
761                 MEM_freeN(uniqueUv);
762
763                 /* Allocate connectivity data, we allocate edges once */
764                 data->uvedges = MEM_mallocN(sizeof(*data->uvedges) * BLI_ghash_len(edgeHash), "uv_brush_edge_connectivity_data");
765                 if (!data->uvedges) {
766                         BLI_ghash_free(edgeHash, NULL, NULL);
767                         MEM_freeN(edges);
768                         uv_sculpt_stroke_exit(C, op);
769                         return NULL;
770                 }
771
772                 /* fill the edges with data */
773                 i = 0;
774                 GHASH_ITER (gh_iter, edgeHash) {
775                         data->uvedges[i++] = *((UvEdge *)BLI_ghashIterator_getKey(&gh_iter));
776                 }
777                 data->totalUvEdges = BLI_ghash_len(edgeHash);
778
779                 /* cleanup temporary stuff */
780                 BLI_ghash_free(edgeHash, NULL, NULL);
781                 MEM_freeN(edges);
782
783                 /* transfer boundary edge property to uvs */
784                 if (ts->uv_sculpt_settings & UV_SCULPT_LOCK_BORDERS) {
785                         for (i = 0; i < data->totalUvEdges; i++) {
786                                 if (!data->uvedges[i].flag) {
787                                         data->uv[data->uvedges[i].uv1].flag |= MARK_BOUNDARY;
788                                         data->uv[data->uvedges[i].uv2].flag |= MARK_BOUNDARY;
789                                 }
790                         }
791                 }
792
793                 /* Allocate initial selection for grab tool */
794                 if (data->tool == UV_SCULPT_TOOL_GRAB) {
795                         float radius, radius_root;
796                         UvSculptData *sculptdata = (UvSculptData *)op->customdata;
797                         SpaceImage *sima;
798                         int width, height;
799                         float aspectRatio;
800                         float alpha, zoomx, zoomy;
801                         Brush *brush = BKE_paint_brush(sculptdata->uvsculpt);
802
803                         alpha = BKE_brush_alpha_get(scene, brush);
804
805                         radius = BKE_brush_size_get(scene, brush);
806                         sima = CTX_wm_space_image(C);
807                         ED_space_image_get_size(sima, &width, &height);
808                         ED_space_image_get_zoom(sima, ar, &zoomx, &zoomy);
809
810                         aspectRatio = width / (float)height;
811                         radius /= (width * zoomx);
812                         radius = radius * radius;
813                         radius_root = sqrtf(radius);
814
815                         /* Allocate selection stack */
816                         data->initial_stroke = MEM_mallocN(sizeof(*data->initial_stroke), "uv_sculpt_initial_stroke");
817                         if (!data->initial_stroke) {
818                                 uv_sculpt_stroke_exit(C, op);
819                         }
820                         data->initial_stroke->initialSelection = MEM_mallocN(sizeof(*data->initial_stroke->initialSelection) * data->totalUniqueUvs, "uv_sculpt_initial_selection");
821                         if (!data->initial_stroke->initialSelection) {
822                                 uv_sculpt_stroke_exit(C, op);
823                         }
824
825                         copy_v2_v2(data->initial_stroke->init_coord, co);
826
827                         counter = 0;
828
829                         for (i = 0; i < data->totalUniqueUvs; i++) {
830                                 float dist, diff[2];
831                                 if (data->uv[i].flag & MARK_BOUNDARY) {
832                                         continue;
833                                 }
834
835                                 sub_v2_v2v2(diff, data->uv[i].uv, co);
836                                 diff[1] /= aspectRatio;
837                                 if ((dist = dot_v2v2(diff, diff)) <= radius) {
838                                         float strength;
839                                         strength = alpha * BKE_brush_curve_strength_clamped(brush, sqrtf(dist), radius_root);
840
841                                         data->initial_stroke->initialSelection[counter].uv = i;
842                                         data->initial_stroke->initialSelection[counter].strength = strength;
843                                         copy_v2_v2(data->initial_stroke->initialSelection[counter].initial_uv, data->uv[i].uv);
844                                         counter++;
845                                 }
846                         }
847
848                         data->initial_stroke->totalInitialSelected = counter;
849                 }
850         }
851
852         return op->customdata;
853 }
854
855 static int uv_sculpt_stroke_invoke(bContext *C, wmOperator *op, const wmEvent *event)
856 {
857         UvSculptData *data;
858         Object *obedit = CTX_data_edit_object(C);
859
860         if (!(data = uv_sculpt_stroke_init(C, op, event))) {
861                 return OPERATOR_CANCELLED;
862         }
863
864         uv_sculpt_stroke_apply(C, op, event, obedit);
865
866         data->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.001f);
867
868         if (!data->timer) {
869                 uv_sculpt_stroke_exit(C, op);
870                 return OPERATOR_CANCELLED;
871         }
872         WM_event_add_modal_handler(C, op);
873
874         return OPERATOR_RUNNING_MODAL;
875 }
876
877
878 static int uv_sculpt_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
879 {
880         UvSculptData *data = (UvSculptData *)op->customdata;
881         Object *obedit = CTX_data_edit_object(C);
882
883         switch (event->type) {
884                 case LEFTMOUSE:
885                 case MIDDLEMOUSE:
886                 case RIGHTMOUSE:
887                         uv_sculpt_stroke_exit(C, op);
888                         return OPERATOR_FINISHED;
889
890                 case MOUSEMOVE:
891                 case INBETWEEN_MOUSEMOVE:
892                         uv_sculpt_stroke_apply(C, op, event, obedit);
893                         break;
894                 case TIMER:
895                         if (event->customdata == data->timer)
896                                 uv_sculpt_stroke_apply(C, op, event, obedit);
897                         break;
898                 default:
899                         return OPERATOR_RUNNING_MODAL;
900         }
901
902         ED_region_tag_redraw(CTX_wm_region(C));
903         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
904         DAG_id_tag_update(obedit->data, 0);
905         return OPERATOR_RUNNING_MODAL;
906 }
907
908 void SCULPT_OT_uv_sculpt_stroke(wmOperatorType *ot)
909 {
910         static const EnumPropertyItem stroke_mode_items[] = {
911                 {BRUSH_STROKE_NORMAL, "NORMAL", 0, "Normal", "Apply brush normally"},
912                 {BRUSH_STROKE_INVERT, "INVERT", 0, "Invert", "Invert action of brush for duration of stroke"},
913                 {BRUSH_STROKE_SMOOTH, "RELAX", 0, "Relax", "Switch brush to relax mode for duration of stroke"},
914                 {0}
915         };
916
917         /* identifiers */
918         ot->name = "Sculpt UVs";
919         ot->description = "Sculpt UVs using a brush";
920         ot->idname = "SCULPT_OT_uv_sculpt_stroke";
921
922         /* api callbacks */
923         ot->invoke = uv_sculpt_stroke_invoke;
924         ot->modal = uv_sculpt_stroke_modal;
925         ot->poll = uv_sculpt_poll;
926
927         /* flags */
928         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
929
930         /* props */
931         RNA_def_enum(ot->srna, "mode", stroke_mode_items, BRUSH_STROKE_NORMAL, "Mode", "Stroke Mode");
932 }