Bevel mod: cleanup flags and extra data.
[blender.git] / source / blender / editors / sculpt_paint / paint_image_2d.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23 //#include <math.h>
24 #include <string.h>
25
26 #include "MEM_guardedalloc.h"
27
28 #include "DNA_brush_types.h"
29 #include "DNA_scene_types.h"
30 #include "DNA_space_types.h"
31 #include "DNA_object_types.h"
32
33
34 #include "BLI_math_color_blend.h"
35 #include "BLI_stack.h"
36 #include "BLI_bitmap.h"
37 #include "BLI_task.h"
38
39 #include "BKE_colorband.h"
40 #include "BKE_context.h"
41 #include "BKE_brush.h"
42 #include "BKE_image.h"
43 #include "BKE_paint.h"
44 #include "BKE_report.h"
45
46 #include "DEG_depsgraph.h"
47
48 #include "ED_paint.h"
49 #include "ED_screen.h"
50
51 #include "IMB_imbuf.h"
52 #include "IMB_imbuf_types.h"
53 #include "IMB_colormanagement.h"
54
55 #include "WM_api.h"
56 #include "WM_types.h"
57
58 #include "UI_view2d.h"
59
60
61 #include "GPU_draw.h"
62
63 #include "paint_intern.h"
64
65 /* Brush Painting for 2D image editor */
66
67 /* Defines and Structs */
68
69 typedef struct BrushPainterCache {
70         bool use_float;              /* need float imbuf? */
71         bool use_color_correction;   /* use color correction for float */
72         bool invert;
73
74         bool is_texbrush;
75         bool is_maskbrush;
76
77         int lastdiameter;
78         float last_tex_rotation;
79         float last_mask_rotation;
80         float last_pressure;
81
82         ImBuf *ibuf;
83         ImBuf *texibuf;
84         unsigned short *curve_mask;
85         unsigned short *tex_mask;
86         unsigned short *tex_mask_old;
87         unsigned int tex_mask_old_w;
88         unsigned int tex_mask_old_h;
89 } BrushPainterCache;
90
91 typedef struct BrushPainter {
92         Scene *scene;
93         Brush *brush;
94
95         float lastpaintpos[2];  /* position of last paint op */
96         float startpaintpos[2]; /* position of first paint */
97
98         short firsttouch;       /* first paint op */
99
100         struct ImagePool *pool; /* image pool */
101         rctf tex_mapping;               /* texture coordinate mapping */
102         rctf mask_mapping;              /* mask texture coordinate mapping */
103
104         BrushPainterCache cache;
105 } BrushPainter;
106
107 typedef struct ImagePaintRegion {
108         int destx, desty;
109         int srcx, srcy;
110         int width, height;
111 } ImagePaintRegion;
112
113 typedef struct ImagePaintState {
114         BrushPainter *painter;
115         SpaceImage *sima;
116         View2D *v2d;
117         Scene *scene;
118         bScreen *screen;
119         struct ImagePool *image_pool;
120
121         Brush *brush;
122         short tool, blend;
123         Image *image;
124         ImBuf *canvas;
125         ImBuf *clonecanvas;
126         const char *warnpackedfile;
127         const char *warnmultifile;
128
129         bool do_masking;
130
131         /* viewport texture paint only, but _not_ project paint */
132         Object *ob;
133         int faceindex;
134         float uv[2];
135         int do_facesel;
136         int symmetry;
137
138         bool need_redraw;
139
140         BlurKernel *blurkernel;
141 } ImagePaintState;
142
143
144 static BrushPainter *brush_painter_2d_new(Scene *scene, Brush *brush, bool invert)
145 {
146         BrushPainter *painter = MEM_callocN(sizeof(BrushPainter), "BrushPainter");
147
148         painter->brush = brush;
149         painter->scene = scene;
150         painter->firsttouch = 1;
151         painter->cache.lastdiameter = -1; /* force ibuf create in refresh */
152         painter->cache.invert = invert;
153
154         return painter;
155 }
156
157
158 static void brush_painter_2d_require_imbuf(BrushPainter *painter, bool use_float, bool use_color_correction)
159 {
160         Brush *brush = painter->brush;
161
162         if ((painter->cache.use_float != use_float)) {
163                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
164                 if (painter->cache.curve_mask) MEM_freeN(painter->cache.curve_mask);
165                 if (painter->cache.tex_mask) MEM_freeN(painter->cache.tex_mask);
166                 if (painter->cache.tex_mask_old) MEM_freeN(painter->cache.tex_mask_old);
167                 painter->cache.ibuf = NULL;
168                 painter->cache.curve_mask = NULL;
169                 painter->cache.tex_mask = NULL;
170                 painter->cache.lastdiameter = -1; /* force ibuf create in refresh */
171         }
172
173         painter->cache.use_float = use_float;
174         painter->cache.use_color_correction = use_float && use_color_correction;
175         painter->cache.is_texbrush = (brush->mtex.tex && brush->imagepaint_tool == PAINT_TOOL_DRAW) ? true : false;
176         painter->cache.is_maskbrush = (brush->mask_mtex.tex) ? true : false;
177 }
178
179 static void brush_painter_2d_free(BrushPainter *painter)
180 {
181         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
182         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
183         if (painter->cache.curve_mask) MEM_freeN(painter->cache.curve_mask);
184         if (painter->cache.tex_mask) MEM_freeN(painter->cache.tex_mask);
185         if (painter->cache.tex_mask_old) MEM_freeN(painter->cache.tex_mask_old);
186         MEM_freeN(painter);
187 }
188
189 static void brush_imbuf_tex_co(rctf *mapping, int x, int y, float texco[3])
190 {
191         texco[0] = mapping->xmin + x * mapping->xmax;
192         texco[1] = mapping->ymin + y * mapping->ymax;
193         texco[2] = 0.0f;
194 }
195
196 /* create a mask with the mask texture */
197 static unsigned short *brush_painter_mask_ibuf_new(BrushPainter *painter, int size)
198 {
199         Scene *scene = painter->scene;
200         Brush *brush = painter->brush;
201         rctf mask_mapping = painter->mask_mapping;
202         struct ImagePool *pool = painter->pool;
203
204         float texco[3];
205         unsigned short *mask, *m;
206         int x, y, thread = 0;
207
208         mask = MEM_mallocN(sizeof(unsigned short) * size * size, "brush_painter_mask");
209         m = mask;
210
211         for (y = 0; y < size; y++) {
212                 for (x = 0; x < size; x++, m++) {
213                         float res;
214                         brush_imbuf_tex_co(&mask_mapping, x, y, texco);
215                         res = BKE_brush_sample_masktex(scene, brush, texco, thread, pool);
216                         *m = (unsigned short)(65535.0f * res);
217                 }
218         }
219
220         return mask;
221 }
222
223 /* update rectangular section of the brush image */
224 static void brush_painter_mask_imbuf_update(
225         BrushPainter *painter, unsigned short *tex_mask_old,
226         int origx, int origy, int w, int h, int xt, int yt, int diameter)
227 {
228         Scene *scene = painter->scene;
229         Brush *brush = painter->brush;
230         rctf tex_mapping = painter->mask_mapping;
231         struct ImagePool *pool = painter->pool;
232         unsigned short res;
233
234         bool use_texture_old = (tex_mask_old != NULL);
235
236         int x, y, thread = 0;
237
238         unsigned short *tex_mask = painter->cache.tex_mask;
239         unsigned short *tex_mask_cur = painter->cache.tex_mask_old;
240
241         /* fill pixels */
242         for (y = origy; y < h; y++) {
243                 for (x = origx; x < w; x++) {
244                         /* sample texture */
245                         float texco[3];
246
247                         /* handle byte pixel */
248                         unsigned short *b = tex_mask + (y * diameter + x);
249                         unsigned short *t = tex_mask_cur + (y * diameter + x);
250
251                         if (!use_texture_old) {
252                                 brush_imbuf_tex_co(&tex_mapping, x, y, texco);
253                                 res = (unsigned short)(65535.0f * BKE_brush_sample_masktex(scene, brush, texco, thread, pool));
254                         }
255
256                         /* read from old texture buffer */
257                         if (use_texture_old) {
258                                 res = *(tex_mask_old + ((y - origy + yt) * painter->cache.tex_mask_old_w + (x - origx + xt)));
259                         }
260
261                         /* write to new texture mask */
262                         *t = res;
263                         /* write to mask image buffer */
264                         *b = res;
265                 }
266         }
267 }
268
269
270 /**
271  * Update the brush mask image by trying to reuse the cached texture result.
272  * This can be considerably faster for brushes that change size due to pressure or
273  * textures that stick to the surface where only part of the pixels are new
274  */
275 static void brush_painter_mask_imbuf_partial_update(BrushPainter *painter, const float pos[2], int diameter)
276 {
277         BrushPainterCache *cache = &painter->cache;
278         unsigned short *tex_mask_old;
279         int destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
280
281         /* create brush image buffer if it didn't exist yet */
282         if (!cache->tex_mask)
283                 cache->tex_mask = MEM_mallocN(sizeof(unsigned short) * diameter * diameter, "brush_painter_mask");
284
285         /* create new texture image buffer with coordinates relative to old */
286         tex_mask_old = cache->tex_mask_old;
287         cache->tex_mask_old = MEM_mallocN(sizeof(unsigned short) * diameter * diameter, "brush_painter_mask");
288
289         if (tex_mask_old) {
290                 ImBuf maskibuf;
291                 ImBuf maskibuf_old;
292                 maskibuf.x = maskibuf.y = diameter;
293                 maskibuf_old.x = cache->tex_mask_old_w;
294                 maskibuf_old.y = cache->tex_mask_old_h;
295
296                 srcx = srcy = 0;
297                 w = cache->tex_mask_old_w;
298                 h = cache->tex_mask_old_h;
299                 destx = (int)floorf(painter->lastpaintpos[0]) - (int)floorf(pos[0])  + (diameter / 2 - w / 2);
300                 desty = (int)floorf(painter->lastpaintpos[1]) - (int)floorf(pos[1])  + (diameter / 2 - h / 2);
301
302                 /* hack, use temporary rects so that clipping works */
303                 IMB_rectclip(&maskibuf, &maskibuf_old, &destx, &desty, &srcx, &srcy, &w, &h);
304         }
305         else {
306                 srcx = srcy = 0;
307                 destx = desty = 0;
308                 w = h = 0;
309         }
310
311         x1 = min_ii(destx, diameter);
312         y1 = min_ii(desty, diameter);
313         x2 = min_ii(destx + w, diameter);
314         y2 = min_ii(desty + h, diameter);
315
316         /* blend existing texture in new position */
317         if ((x1 < x2) && (y1 < y2))
318                 brush_painter_mask_imbuf_update(painter, tex_mask_old, x1, y1, x2, y2, srcx, srcy, diameter);
319
320         if (tex_mask_old)
321                 MEM_freeN(tex_mask_old);
322
323         /* sample texture in new areas */
324         if ((0 < x1) && (0 < diameter))
325                 brush_painter_mask_imbuf_update(painter, NULL, 0, 0, x1, diameter, 0, 0, diameter);
326         if ((x2 < diameter) && (0 < diameter))
327                 brush_painter_mask_imbuf_update(painter, NULL, x2, 0, diameter, diameter, 0, 0, diameter);
328         if ((x1 < x2) && (0 < y1))
329                 brush_painter_mask_imbuf_update(painter, NULL, x1, 0, x2, y1, 0, 0, diameter);
330         if ((x1 < x2) && (y2 < diameter))
331                 brush_painter_mask_imbuf_update(painter, NULL, x1, y2, x2, diameter, 0, 0, diameter);
332
333         /* through with sampling, now update sizes */
334         cache->tex_mask_old_w = diameter;
335         cache->tex_mask_old_h = diameter;
336 }
337
338 /* create a mask with the falloff strength */
339 static unsigned short *brush_painter_curve_mask_new(BrushPainter *painter, int diameter, float radius)
340 {
341         Brush *brush = painter->brush;
342
343         int xoff = -radius;
344         int yoff = -radius;
345
346         unsigned short *mask, *m;
347         int x, y;
348
349         mask = MEM_mallocN(sizeof(unsigned short) * diameter * diameter, "brush_painter_mask");
350         m = mask;
351
352         for (y = 0; y < diameter; y++) {
353                 for (x = 0; x < diameter; x++, m++) {
354                         float xy[2] = {x + xoff, y + yoff};
355                         float len = len_v2(xy);
356
357                         *m = (unsigned short)(65535.0f * BKE_brush_curve_strength_clamped(brush, len, radius));
358                 }
359         }
360
361         return mask;
362 }
363
364
365 /* create imbuf with brush color */
366 static ImBuf *brush_painter_imbuf_new(BrushPainter *painter, int size, float pressure, float distance)
367 {
368         Scene *scene = painter->scene;
369         Brush *brush = painter->brush;
370
371         const char *display_device = scene->display_settings.display_device;
372         struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
373
374         rctf tex_mapping = painter->tex_mapping;
375         struct ImagePool *pool = painter->pool;
376
377         bool use_color_correction = painter->cache.use_color_correction;
378         bool use_float = painter->cache.use_float;
379         bool is_texbrush = painter->cache.is_texbrush;
380
381         int x, y, thread = 0;
382         float brush_rgb[3];
383
384         /* allocate image buffer */
385         ImBuf *ibuf = IMB_allocImBuf(size, size, 32, (use_float) ? IB_rectfloat : IB_rect);
386
387         /* get brush color */
388         if (brush->imagepaint_tool == PAINT_TOOL_DRAW) {
389                 paint_brush_color_get(scene, brush, use_color_correction, painter->cache.invert, distance, pressure, brush_rgb, display);
390         }
391         else {
392                 brush_rgb[0] = 1.0f;
393                 brush_rgb[1] = 1.0f;
394                 brush_rgb[2] = 1.0f;
395         }
396
397         /* fill image buffer */
398         for (y = 0; y < size; y++) {
399                 for (x = 0; x < size; x++) {
400                         /* sample texture and multiply with brush color */
401                         float texco[3], rgba[4];
402
403                         if (is_texbrush) {
404                                 brush_imbuf_tex_co(&tex_mapping, x, y, texco);
405                                 BKE_brush_sample_tex_3d(scene, brush, texco, rgba, thread, pool);
406                                 /* TODO(sergey): Support texture paint color space. */
407                                 if (!use_float) {
408                                         IMB_colormanagement_scene_linear_to_display_v3(rgba, display);
409                                 }
410                                 mul_v3_v3(rgba, brush_rgb);
411                         }
412                         else {
413                                 copy_v3_v3(rgba, brush_rgb);
414                                 rgba[3] = 1.0f;
415                         }
416
417                         if (use_float) {
418                                 /* write to float pixel */
419                                 float *dstf = ibuf->rect_float + (y * size + x) * 4;
420                                 mul_v3_v3fl(dstf, rgba, rgba[3]); /* premultiply */
421                                 dstf[3] = rgba[3];
422                         }
423                         else {
424                                 /* write to byte pixel */
425                                 unsigned char *dst = (unsigned char *)ibuf->rect + (y * size + x) * 4;
426
427                                 rgb_float_to_uchar(dst, rgba);
428                                 dst[3] = unit_float_to_uchar_clamp(rgba[3]);
429                         }
430                 }
431         }
432
433         return ibuf;
434 }
435
436 /* update rectangular section of the brush image */
437 static void brush_painter_imbuf_update(
438         BrushPainter *painter, ImBuf *oldtexibuf,
439         int origx, int origy, int w, int h, int xt, int yt)
440 {
441         Scene *scene = painter->scene;
442         Brush *brush = painter->brush;
443
444         const char *display_device = scene->display_settings.display_device;
445         struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
446
447         rctf tex_mapping = painter->tex_mapping;
448         struct ImagePool *pool = painter->pool;
449
450         bool use_color_correction = painter->cache.use_color_correction;
451         bool use_float = painter->cache.use_float;
452         bool is_texbrush = painter->cache.is_texbrush;
453         bool use_texture_old = (oldtexibuf != NULL);
454
455         int x, y, thread = 0;
456         float brush_rgb[3];
457
458         ImBuf *ibuf = painter->cache.ibuf;
459         ImBuf *texibuf = painter->cache.texibuf;
460
461         /* get brush color */
462         if (brush->imagepaint_tool == PAINT_TOOL_DRAW) {
463                 paint_brush_color_get(scene, brush, use_color_correction, painter->cache.invert, 0.0, 1.0, brush_rgb, display);
464         }
465         else {
466                 brush_rgb[0] = 1.0f;
467                 brush_rgb[1] = 1.0f;
468                 brush_rgb[2] = 1.0f;
469         }
470
471         /* fill pixels */
472         for (y = origy; y < h; y++) {
473                 for (x = origx; x < w; x++) {
474                         /* sample texture and multiply with brush color */
475                         float texco[3], rgba[4];
476
477                         if (!use_texture_old) {
478                                 if (is_texbrush) {
479                                         brush_imbuf_tex_co(&tex_mapping, x, y, texco);
480                                         BKE_brush_sample_tex_3d(scene, brush, texco, rgba, thread, pool);
481                                         /* TODO(sergey): Support texture paint color space. */
482                                         if (!use_float) {
483                                                 IMB_colormanagement_scene_linear_to_display_v3(rgba, display);
484                                         }
485                                         mul_v3_v3(rgba, brush_rgb);
486                                 }
487                                 else {
488                                         copy_v3_v3(rgba, brush_rgb);
489                                         rgba[3] = 1.0f;
490                                 }
491                         }
492
493                         if (use_float) {
494                                 /* handle float pixel */
495                                 float *bf = ibuf->rect_float + (y * ibuf->x + x) * 4;
496                                 float *tf = texibuf->rect_float + (y * texibuf->x + x) * 4;
497
498                                 /* read from old texture buffer */
499                                 if (use_texture_old) {
500                                         const float *otf = oldtexibuf->rect_float + ((y - origy + yt) * oldtexibuf->x + (x - origx + xt)) * 4;
501                                         copy_v4_v4(rgba, otf);
502                                 }
503
504                                 /* write to new texture buffer */
505                                 copy_v4_v4(tf, rgba);
506
507                                 /* output premultiplied float image, mf was already premultiplied */
508                                 mul_v3_v3fl(bf, rgba, rgba[3]);
509                                 bf[3] = rgba[3];
510                         }
511                         else {
512                                 unsigned char crgba[4];
513
514                                 /* handle byte pixel */
515                                 unsigned char *b = (unsigned char *)ibuf->rect + (y * ibuf->x + x) * 4;
516                                 unsigned char *t = (unsigned char *)texibuf->rect + (y * texibuf->x + x) * 4;
517
518                                 /* read from old texture buffer */
519                                 if (use_texture_old) {
520                                         unsigned char *ot = (unsigned char *)oldtexibuf->rect + ((y - origy + yt) * oldtexibuf->x + (x - origx + xt)) * 4;
521                                         crgba[0] = ot[0];
522                                         crgba[1] = ot[1];
523                                         crgba[2] = ot[2];
524                                         crgba[3] = ot[3];
525                                 }
526                                 else
527                                         rgba_float_to_uchar(crgba, rgba);
528
529                                 /* write to new texture buffer */
530                                 t[0] = crgba[0];
531                                 t[1] = crgba[1];
532                                 t[2] = crgba[2];
533                                 t[3] = crgba[3];
534
535                                 /* write to brush image buffer */
536                                 b[0] = crgba[0];
537                                 b[1] = crgba[1];
538                                 b[2] = crgba[2];
539                                 b[3] = crgba[3];
540                         }
541                 }
542         }
543 }
544
545 /* update the brush image by trying to reuse the cached texture result. this
546  * can be considerably faster for brushes that change size due to pressure or
547  * textures that stick to the surface where only part of the pixels are new */
548 static void brush_painter_imbuf_partial_update(BrushPainter *painter, const float pos[2], int diameter)
549 {
550         BrushPainterCache *cache = &painter->cache;
551         ImBuf *oldtexibuf, *ibuf;
552         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
553
554         /* create brush image buffer if it didn't exist yet */
555         imbflag = (cache->use_float) ? IB_rectfloat : IB_rect;
556         if (!cache->ibuf)
557                 cache->ibuf = IMB_allocImBuf(diameter, diameter, 32, imbflag);
558         ibuf = cache->ibuf;
559
560         /* create new texture image buffer with coordinates relative to old */
561         oldtexibuf = cache->texibuf;
562         cache->texibuf = IMB_allocImBuf(diameter, diameter, 32, imbflag);
563
564         if (oldtexibuf) {
565                 srcx = srcy = 0;
566                 w = oldtexibuf->x;
567                 h = oldtexibuf->y;
568                 destx = (int)floorf(painter->lastpaintpos[0]) - (int)floorf(pos[0]) + (diameter / 2 - w / 2);
569                 desty = (int)floorf(painter->lastpaintpos[1]) - (int)floorf(pos[1]) + (diameter / 2 - h / 2);
570
571                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
572         }
573         else {
574                 srcx = srcy = 0;
575                 destx = desty = 0;
576                 w = h = 0;
577         }
578
579         x1 = min_ii(destx, ibuf->x);
580         y1 = min_ii(desty, ibuf->y);
581         x2 = min_ii(destx + w, ibuf->x);
582         y2 = min_ii(desty + h, ibuf->y);
583
584         /* blend existing texture in new position */
585         if ((x1 < x2) && (y1 < y2))
586                 brush_painter_imbuf_update(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy);
587
588         if (oldtexibuf)
589                 IMB_freeImBuf(oldtexibuf);
590
591         /* sample texture in new areas */
592         if ((0 < x1) && (0 < ibuf->y))
593                 brush_painter_imbuf_update(painter, NULL, 0, 0, x1, ibuf->y, 0, 0);
594         if ((x2 < ibuf->x) && (0 < ibuf->y))
595                 brush_painter_imbuf_update(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0);
596         if ((x1 < x2) && (0 < y1))
597                 brush_painter_imbuf_update(painter, NULL, x1, 0, x2, y1, 0, 0);
598         if ((x1 < x2) && (y2 < ibuf->y))
599                 brush_painter_imbuf_update(painter, NULL, x1, y2, x2, ibuf->y, 0, 0);
600 }
601
602 static void brush_painter_2d_tex_mapping(ImagePaintState *s, int diameter, const float startpos[2], const float pos[2], const float mouse[2], int mapmode, rctf *mapping)
603 {
604         float invw = 1.0f / (float)s->canvas->x;
605         float invh = 1.0f / (float)s->canvas->y;
606         int xmin, ymin, xmax, ymax;
607         int ipos[2];
608
609         /* find start coordinate of brush in canvas */
610         ipos[0] = (int)floorf((pos[0] - diameter / 2) + 1.0f);
611         ipos[1] = (int)floorf((pos[1] - diameter / 2) + 1.0f);
612
613         if (mapmode == MTEX_MAP_MODE_STENCIL) {
614                 /* map from view coordinates of brush to region coordinates */
615                 UI_view2d_view_to_region(s->v2d, ipos[0] * invw, ipos[1] * invh, &xmin, &ymin);
616                 UI_view2d_view_to_region(s->v2d, (ipos[0] + diameter) * invw, (ipos[1] + diameter) * invh, &xmax, &ymax);
617
618                 /* output mapping from brush ibuf x/y to region coordinates */
619                 mapping->xmin = xmin;
620                 mapping->ymin = ymin;
621                 mapping->xmax = (xmax - xmin) / (float)diameter;
622                 mapping->ymax = (ymax - ymin) / (float)diameter;
623         }
624         else if (mapmode == MTEX_MAP_MODE_3D) {
625                 /* 3D mapping, just mapping to canvas 0..1  */
626                 mapping->xmin = 2.0f * (ipos[0] * invw - 0.5f);
627                 mapping->ymin = 2.0f * (ipos[1] * invh - 0.5f);
628                 mapping->xmax = 2.0f * invw;
629                 mapping->ymax = 2.0f * invh;
630         }
631         else if (ELEM(mapmode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_RANDOM)) {
632                 /* view mapping */
633                 mapping->xmin = mouse[0] - diameter * 0.5f + 0.5f;
634                 mapping->ymin = mouse[1] - diameter * 0.5f + 0.5f;
635                 mapping->xmax = 1.0f;
636                 mapping->ymax = 1.0f;
637         }
638         else /* if (mapmode == MTEX_MAP_MODE_TILED) */ {
639                 mapping->xmin = (int)(-diameter * 0.5) + (int)floorf(pos[0]) - (int)floorf(startpos[0]);
640                 mapping->ymin = (int)(-diameter * 0.5) + (int)floorf(pos[1]) - (int)floorf(startpos[1]);
641                 mapping->xmax = 1.0f;
642                 mapping->ymax = 1.0f;
643         }
644 }
645
646 static void brush_painter_2d_refresh_cache(ImagePaintState *s, BrushPainter *painter, const float pos[2], const float mouse[2], float pressure, float distance, float size)
647 {
648         const Scene *scene = painter->scene;
649         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
650         Brush *brush = painter->brush;
651         BrushPainterCache *cache = &painter->cache;
652         const int diameter = 2 * size;
653
654         bool do_random = false;
655         bool do_partial_update = false;
656         bool update_color = (
657                 (brush->flag & BRUSH_USE_GRADIENT) &&
658                 ((ELEM(brush->gradient_stroke_mode,
659                        BRUSH_GRADIENT_SPACING_REPEAT,
660                        BRUSH_GRADIENT_SPACING_CLAMP)) ||
661                  (cache->last_pressure != pressure)));
662         float tex_rotation = -brush->mtex.rot;
663         float mask_rotation = -brush->mask_mtex.rot;
664
665         painter->pool = BKE_image_pool_new();
666
667         /* determine how can update based on textures used */
668         if (painter->cache.is_texbrush) {
669                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
670                         tex_rotation += ups->brush_rotation;
671                 }
672                 else if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM)
673                         do_random = true;
674                 else if (!((brush->flag & BRUSH_ANCHORED) || update_color))
675                         do_partial_update = true;
676
677                 brush_painter_2d_tex_mapping(
678                         s, diameter, painter->startpaintpos, pos, mouse,
679                         brush->mtex.brush_map_mode, &painter->tex_mapping);
680         }
681
682         if (painter->cache.is_maskbrush) {
683                 bool renew_maxmask = false;
684                 bool do_partial_update_mask = false;
685                 /* invalidate case for all mapping modes */
686                 if (brush->mask_mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
687                         mask_rotation += ups->brush_rotation_sec;
688                 }
689                 else if (brush->mask_mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM) {
690                         renew_maxmask = true;
691                 }
692                 else if (!(brush->flag & BRUSH_ANCHORED)) {
693                         do_partial_update_mask = true;
694                         renew_maxmask = true;
695                 }
696                 /* explicitly disable partial update even if it has been enabled above */
697                 if (brush->mask_pressure) {
698                         do_partial_update_mask = false;
699                         renew_maxmask = true;
700                 }
701
702                 if ((diameter != cache->lastdiameter) ||
703                     (mask_rotation != cache->last_mask_rotation) ||
704                     renew_maxmask)
705                 {
706                         if (cache->tex_mask) {
707                                 MEM_freeN(cache->tex_mask);
708                                 cache->tex_mask = NULL;
709                         }
710
711                         brush_painter_2d_tex_mapping(
712                                 s, diameter, painter->startpaintpos, pos, mouse,
713                                 brush->mask_mtex.brush_map_mode, &painter->mask_mapping);
714
715                         if (do_partial_update_mask)
716                                 brush_painter_mask_imbuf_partial_update(painter, pos, diameter);
717                         else
718                                 cache->tex_mask = brush_painter_mask_ibuf_new(painter, diameter);
719                         cache->last_mask_rotation = mask_rotation;
720                 }
721         }
722
723         /* curve mask can only change if the size changes */
724         if (diameter != cache->lastdiameter) {
725                 if (cache->curve_mask) {
726                         MEM_freeN(cache->curve_mask);
727                         cache->curve_mask = NULL;
728                 }
729
730                 cache->curve_mask = brush_painter_curve_mask_new(painter, diameter, size);
731         }
732
733         /* detect if we need to recreate image brush buffer */
734         if ((diameter != cache->lastdiameter) ||
735             (tex_rotation != cache->last_tex_rotation) ||
736             do_random ||
737             update_color)
738         {
739                 if (cache->ibuf) {
740                         IMB_freeImBuf(cache->ibuf);
741                         cache->ibuf = NULL;
742                 }
743
744                 if (do_partial_update) {
745                         /* do partial update of texture */
746                         brush_painter_imbuf_partial_update(painter, pos, diameter);
747                 }
748                 else {
749                         /* create brush from scratch */
750                         cache->ibuf = brush_painter_imbuf_new(painter, diameter, pressure, distance);
751                 }
752
753                 cache->lastdiameter = diameter;
754                 cache->last_tex_rotation = tex_rotation;
755                 cache->last_pressure = pressure;
756         }
757         else if (do_partial_update) {
758                 /* do only partial update of texture */
759                 int dx = (int)floorf(painter->lastpaintpos[0]) - (int)floorf(pos[0]);
760                 int dy = (int)floorf(painter->lastpaintpos[1]) - (int)floorf(pos[1]);
761
762                 if ((dx != 0) || (dy != 0)) {
763                         brush_painter_imbuf_partial_update(painter, pos, diameter);
764                 }
765         }
766
767         BKE_image_pool_free(painter->pool);
768         painter->pool = NULL;
769 }
770
771 /* keep these functions in sync */
772 static void paint_2d_ibuf_rgb_get(ImBuf *ibuf, int x, int y, float r_rgb[4])
773 {
774         if (ibuf->rect_float) {
775                 const float *rrgbf = ibuf->rect_float + (ibuf->x * y + x) * 4;
776                 copy_v4_v4(r_rgb, rrgbf);
777         }
778         else {
779                 unsigned char *rrgb = (unsigned char *)ibuf->rect + (ibuf->x * y + x) * 4;
780                 straight_uchar_to_premul_float(r_rgb, rrgb);
781         }
782 }
783 static void paint_2d_ibuf_rgb_set(ImBuf *ibuf, int x, int y, const bool is_torus, const float rgb[4])
784 {
785         if (is_torus) {
786                 x %= ibuf->x;
787                 if (x < 0) x += ibuf->x;
788                 y %= ibuf->y;
789                 if (y < 0) y += ibuf->y;
790         }
791
792         if (ibuf->rect_float) {
793                 float *rrgbf = ibuf->rect_float + (ibuf->x * y + x) * 4;
794                 float map_alpha = (rgb[3] == 0.0f) ? rrgbf[3] : rrgbf[3] / rgb[3];
795
796                 mul_v3_v3fl(rrgbf, rgb, map_alpha);
797                 rrgbf[3] = rgb[3];
798         }
799         else {
800                 unsigned char straight[4];
801                 unsigned char *rrgb = (unsigned char *)ibuf->rect + (ibuf->x * y + x) * 4;
802
803                 premul_float_to_straight_uchar(straight, rgb);
804                 rrgb[0] = straight[0];
805                 rrgb[1] = straight[1];
806                 rrgb[2] = straight[2];
807                 rrgb[3] = straight[3];
808         }
809 }
810
811 static void paint_2d_ibuf_tile_convert(ImBuf *ibuf, int *x, int *y, short tile)
812 {
813         if (tile & PAINT_TILE_X) {
814                 *x %= ibuf->x;
815                 if (*x < 0) *x += ibuf->x;
816         }
817         if (tile & PAINT_TILE_Y) {
818                 *y %= ibuf->y;
819                 if (*y < 0) *y += ibuf->y;
820         }
821 }
822
823
824 static float paint_2d_ibuf_add_if(ImBuf *ibuf, int x, int y, float *outrgb, short tile, float w)
825 {
826         float inrgb[4];
827
828         if (tile) paint_2d_ibuf_tile_convert(ibuf, &x, &y, tile);
829         /* need to also do clipping here always since tiled coordinates
830          * are not always within bounds */
831         if (x < ibuf->x && x >= 0 && y < ibuf->y && y >= 0) {
832                 paint_2d_ibuf_rgb_get(ibuf, x, y, inrgb);
833         }
834         else return 0;
835
836         mul_v4_fl(inrgb, w);
837         add_v4_v4(outrgb, inrgb);
838
839         return w;
840 }
841
842 static void paint_2d_lift_soften(ImagePaintState *s, ImBuf *ibuf, ImBuf *ibufb, int *pos, const short tile)
843 {
844         bool sharpen = (s->painter->cache.invert ^ ((s->brush->flag & BRUSH_DIR_IN) != 0));
845         float threshold = s->brush->sharp_threshold;
846         int x, y, xi, yi, xo, yo, xk, yk;
847         float count;
848         int out_off[2], in_off[2], dim[2];
849         int diff_pos[2];
850         float outrgb[4];
851         float rgba[4];
852         BlurKernel *kernel = s->blurkernel;
853
854         dim[0] = ibufb->x;
855         dim[1] = ibufb->y;
856         in_off[0] = pos[0];
857         in_off[1] = pos[1];
858         out_off[0] = out_off[1] = 0;
859
860         if (!tile) {
861                 IMB_rectclip(
862                         ibuf, ibufb, &in_off[0], &in_off[1], &out_off[0],
863                         &out_off[1], &dim[0], &dim[1]);
864
865                 if ((dim[0] == 0) || (dim[1] == 0))
866                         return;
867         }
868
869         /* find offset inside mask buffers to sample them */
870         sub_v2_v2v2_int(diff_pos, out_off, in_off);
871
872         for (y = 0; y < dim[1]; y++) {
873                 for (x = 0; x < dim[0]; x++) {
874                         /* get input pixel */
875                         xi = in_off[0] + x;
876                         yi = in_off[1] + y;
877
878                         count = 0.0;
879                         if (tile) {
880                                 paint_2d_ibuf_tile_convert(ibuf, &xi, &yi, tile);
881                                 if (xi < ibuf->x && xi >= 0 && yi < ibuf->y && yi >= 0)
882                                         paint_2d_ibuf_rgb_get(ibuf, xi, yi, rgba);
883                                 else
884                                         zero_v4(rgba);
885                         }
886                         else {
887                                 /* coordinates have been clipped properly here, it should be safe to do this */
888                                 paint_2d_ibuf_rgb_get(ibuf, xi, yi, rgba);
889                         }
890                         zero_v4(outrgb);
891
892                         for (yk = 0; yk < kernel->side; yk++) {
893                                 for (xk = 0; xk < kernel->side; xk++) {
894                                         count += paint_2d_ibuf_add_if(
895                                                 ibuf, xi + xk - kernel->pixel_len,
896                                                 yi + yk - kernel->pixel_len, outrgb, tile,
897                                                 kernel->wdata[xk + yk * kernel->side]);
898                                 }
899                         }
900
901                         if (count > 0.0f) {
902                                 mul_v4_fl(outrgb, 1.0f / (float)count);
903
904                                 if (sharpen) {
905                                         /* subtract blurred image from normal image gives high pass filter */
906                                         sub_v3_v3v3(outrgb, rgba, outrgb);
907
908                                         /* now rgba_ub contains the edge result, but this should be converted to luminance to avoid
909                                          * colored speckles appearing in final image, and also to check for threshold */
910                                         outrgb[0] = outrgb[1] = outrgb[2] = IMB_colormanagement_get_luminance(outrgb);
911                                         if (fabsf(outrgb[0]) > threshold) {
912                                                 float mask = BKE_brush_alpha_get(s->scene, s->brush);
913                                                 float alpha = rgba[3];
914                                                 rgba[3] = outrgb[3] = mask;
915
916                                                 /* add to enhance edges */
917                                                 blend_color_add_float(outrgb, rgba, outrgb);
918                                                 outrgb[3] = alpha;
919                                         }
920                                         else
921                                                 copy_v4_v4(outrgb, rgba);
922                                 }
923                         }
924                         else
925                                 copy_v4_v4(outrgb, rgba);
926                         /* write into brush buffer */
927                         xo = out_off[0] + x;
928                         yo = out_off[1] + y;
929                         paint_2d_ibuf_rgb_set(ibufb, xo, yo, 0, outrgb);
930                 }
931         }
932 }
933
934 static void paint_2d_set_region(ImagePaintRegion *region, int destx, int desty, int srcx, int srcy, int width, int height)
935 {
936         region->destx = destx;
937         region->desty = desty;
938         region->srcx = srcx;
939         region->srcy = srcy;
940         region->width = width;
941         region->height = height;
942 }
943
944 static int paint_2d_torus_split_region(ImagePaintRegion region[4], ImBuf *dbuf, ImBuf *sbuf, short tile)
945 {
946         int destx = region->destx;
947         int desty = region->desty;
948         int srcx = region->srcx;
949         int srcy = region->srcy;
950         int width = region->width;
951         int height = region->height;
952         int origw, origh, w, h, tot = 0;
953
954         /* convert destination and source coordinates to be within image */
955         if (tile & PAINT_TILE_X) {
956                 destx = destx % dbuf->x;
957                 if (destx < 0) destx += dbuf->x;
958                 srcx = srcx % sbuf->x;
959                 if (srcx < 0) srcx += sbuf->x;
960         }
961         if (tile & PAINT_TILE_Y) {
962                 desty = desty % dbuf->y;
963                 if (desty < 0) desty += dbuf->y;
964                 srcy = srcy % sbuf->y;
965                 if (srcy < 0) srcy += sbuf->y;
966         }
967         /* clip width of blending area to destination imbuf, to avoid writing the
968          * same pixel twice */
969         origw = w = (width > dbuf->x) ? dbuf->x : width;
970         origh = h = (height > dbuf->y) ? dbuf->y : height;
971
972         /* clip within image */
973         IMB_rectclip(dbuf, sbuf, &destx, &desty, &srcx, &srcy, &w, &h);
974         paint_2d_set_region(&region[tot++], destx, desty, srcx, srcy, w, h);
975
976         /* do 3 other rects if needed */
977         if ((tile & PAINT_TILE_X) && w < origw)
978                 paint_2d_set_region(&region[tot++], (destx + w) % dbuf->x, desty, (srcx + w) % sbuf->x, srcy, origw - w, h);
979         if ((tile & PAINT_TILE_Y) && h < origh)
980                 paint_2d_set_region(&region[tot++], destx, (desty + h) % dbuf->y, srcx, (srcy + h) % sbuf->y, w, origh - h);
981         if ((tile & PAINT_TILE_X) && (tile & PAINT_TILE_Y) && (w < origw) && (h < origh))
982                 paint_2d_set_region(&region[tot++], (destx + w) % dbuf->x, (desty + h) % dbuf->y, (srcx + w) % sbuf->x, (srcy + h) % sbuf->y, origw - w, origh - h);
983
984         return tot;
985 }
986
987 static void paint_2d_lift_smear(ImBuf *ibuf, ImBuf *ibufb, int *pos, short tile)
988 {
989         ImagePaintRegion region[4];
990         int a, tot;
991
992         paint_2d_set_region(region, 0, 0, pos[0], pos[1], ibufb->x, ibufb->y);
993         tot = paint_2d_torus_split_region(region, ibufb, ibuf, tile);
994
995         for (a = 0; a < tot; a++)
996                 IMB_rectblend(
997                         ibufb, ibufb, ibuf, NULL, NULL, NULL, 0, region[a].destx, region[a].desty,
998                         region[a].destx, region[a].desty,
999                         region[a].srcx, region[a].srcy,
1000                         region[a].width, region[a].height, IMB_BLEND_COPY, false);
1001 }
1002
1003 static ImBuf *paint_2d_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos)
1004 {
1005         /* note: allocImbuf returns zero'd memory, so regions outside image will
1006          * have zero alpha, and hence not be blended onto the image */
1007         int w = ibufb->x, h = ibufb->y, destx = 0, desty = 0, srcx = pos[0], srcy = pos[1];
1008         ImBuf *clonebuf = IMB_allocImBuf(w, h, ibufb->planes, ibufb->flags);
1009
1010         IMB_rectclip(clonebuf, ibuf, &destx, &desty, &srcx, &srcy, &w, &h);
1011         IMB_rectblend(
1012                 clonebuf, clonebuf, ibufb, NULL, NULL, NULL, 0, destx, desty, destx, desty, destx, desty, w, h,
1013                 IMB_BLEND_COPY_ALPHA, false);
1014         IMB_rectblend(
1015                 clonebuf, clonebuf, ibuf, NULL, NULL, NULL, 0, destx, desty, destx, desty, srcx, srcy, w, h,
1016                 IMB_BLEND_COPY_RGB, false);
1017
1018         return clonebuf;
1019 }
1020
1021 static void paint_2d_convert_brushco(ImBuf *ibufb, const float pos[2], int ipos[2])
1022 {
1023         ipos[0] = (int)floorf((pos[0] - ibufb->x / 2));
1024         ipos[1] = (int)floorf((pos[1] - ibufb->y / 2));
1025 }
1026
1027 static void paint_2d_do_making_brush(
1028         ImagePaintState *s,
1029         ImagePaintRegion *region,
1030         unsigned short *curveb,
1031         unsigned short *texmaskb,
1032         ImBuf *frombuf,
1033         float mask_max,
1034         short blend,
1035         int tilex, int tiley,
1036         int tilew, int tileh)
1037 {
1038         ImBuf tmpbuf;
1039         IMB_initImBuf(&tmpbuf, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, 0);
1040
1041         ListBase *undo_tiles = ED_image_undo_get_tiles();
1042
1043         for (int ty = tiley; ty <= tileh; ty++) {
1044                 for (int tx = tilex; tx <= tilew; tx++) {
1045                         /* retrieve original pixels + mask from undo buffer */
1046                         unsigned short *mask;
1047                         int origx = region->destx - tx * IMAPAINT_TILE_SIZE;
1048                         int origy = region->desty - ty * IMAPAINT_TILE_SIZE;
1049
1050                         if (s->canvas->rect_float)
1051                                 tmpbuf.rect_float = image_undo_find_tile(undo_tiles, s->image, s->canvas, tx, ty, &mask, false);
1052                         else
1053                                 tmpbuf.rect = image_undo_find_tile(undo_tiles, s->image, s->canvas, tx, ty, &mask, false);
1054
1055                         IMB_rectblend(
1056                                 s->canvas, &tmpbuf, frombuf, mask,
1057                                 curveb, texmaskb, mask_max,
1058                                 region->destx, region->desty,
1059                                 origx, origy,
1060                                 region->srcx, region->srcy,
1061                                 region->width, region->height,
1062                                 blend, ((s->brush->flag & BRUSH_ACCUMULATE) != 0));
1063                 }
1064         }
1065 }
1066
1067 typedef struct Paint2DForeachData {
1068         ImagePaintState *s;
1069         ImagePaintRegion *region;
1070         unsigned short *curveb;
1071         unsigned short *texmaskb;
1072         ImBuf *frombuf;
1073         float mask_max;
1074         short blend;
1075         int tilex;
1076         int tilew;
1077 } Paint2DForeachData;
1078
1079 static void paint_2d_op_foreach_do(
1080         void *__restrict data_v,
1081         const int iter,
1082         const ParallelRangeTLS *__restrict UNUSED(tls))
1083 {
1084         Paint2DForeachData *data = (Paint2DForeachData *)data_v;
1085         paint_2d_do_making_brush(
1086                 data->s, data->region, data->curveb,
1087                 data->texmaskb, data->frombuf, data->mask_max,
1088                 data->blend,
1089                 data->tilex, iter,
1090                 data->tilew, iter);
1091 }
1092
1093 static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsigned short *texmaskb, const float lastpos[2], const float pos[2])
1094 {
1095         ImagePaintState *s = ((ImagePaintState *)state);
1096         ImBuf *clonebuf = NULL, *frombuf;
1097         ImagePaintRegion region[4];
1098         short tile = s->symmetry & (PAINT_TILE_X | PAINT_TILE_Y);
1099         short blend = s->blend;
1100         const float *offset = s->brush->clone.offset;
1101         float liftpos[2];
1102         float mask_max = BKE_brush_alpha_get(s->scene, s->brush);
1103         int bpos[2], blastpos[2], bliftpos[2];
1104         int a, tot;
1105
1106         paint_2d_convert_brushco(ibufb, pos, bpos);
1107
1108         /* lift from canvas */
1109         if (s->tool == PAINT_TOOL_SOFTEN) {
1110                 paint_2d_lift_soften(s, s->canvas, ibufb, bpos, tile);
1111                 blend = IMB_BLEND_INTERPOLATE;
1112         }
1113         else if (s->tool == PAINT_TOOL_SMEAR) {
1114                 if (lastpos[0] == pos[0] && lastpos[1] == pos[1])
1115                         return 0;
1116
1117                 paint_2d_convert_brushco(ibufb, lastpos, blastpos);
1118                 paint_2d_lift_smear(s->canvas, ibufb, blastpos, tile);
1119                 blend = IMB_BLEND_INTERPOLATE;
1120         }
1121         else if (s->tool == PAINT_TOOL_CLONE && s->clonecanvas) {
1122                 liftpos[0] = pos[0] - offset[0] * s->canvas->x;
1123                 liftpos[1] = pos[1] - offset[1] * s->canvas->y;
1124
1125                 paint_2d_convert_brushco(ibufb, liftpos, bliftpos);
1126                 clonebuf = paint_2d_lift_clone(s->clonecanvas, ibufb, bliftpos);
1127         }
1128
1129         frombuf = (clonebuf) ? clonebuf : ibufb;
1130
1131         if (tile) {
1132                 paint_2d_set_region(region, bpos[0], bpos[1], 0, 0, frombuf->x, frombuf->y);
1133                 tot = paint_2d_torus_split_region(region, s->canvas, frombuf, tile);
1134         }
1135         else {
1136                 paint_2d_set_region(region, bpos[0], bpos[1], 0, 0, frombuf->x, frombuf->y);
1137                 tot = 1;
1138         }
1139
1140         /* blend into canvas */
1141         for (a = 0; a < tot; a++) {
1142                 ED_imapaint_dirty_region(
1143                         s->image, s->canvas,
1144                         region[a].destx, region[a].desty,
1145                         region[a].width, region[a].height, true);
1146
1147                 if (s->do_masking) {
1148                         /* masking, find original pixels tiles from undo buffer to composite over */
1149                         int tilex, tiley, tilew, tileh;
1150
1151                         imapaint_region_tiles(
1152                                 s->canvas, region[a].destx, region[a].desty,
1153                                 region[a].width, region[a].height,
1154                                 &tilex, &tiley, &tilew, &tileh);
1155
1156                         if (tiley == tileh) {
1157                                 paint_2d_do_making_brush(
1158                                         s, &region[a], curveb, texmaskb, frombuf,
1159                                         mask_max, blend, tilex, tiley, tilew, tileh);
1160                         }
1161                         else {
1162                                 Paint2DForeachData data;
1163                                 data.s = s;
1164                                 data.region = &region[a];
1165                                 data.curveb = curveb;
1166                                 data.texmaskb = texmaskb;
1167                                 data.frombuf = frombuf;
1168                                 data.mask_max = mask_max;
1169                                 data.blend = blend;
1170                                 data.tilex = tilex;
1171                                 data.tilew = tilew;
1172
1173                                 ParallelRangeSettings settings;
1174                                 BLI_parallel_range_settings_defaults(&settings);
1175                                 BLI_task_parallel_range(
1176                                         tiley, tileh + 1, &data,
1177                                         paint_2d_op_foreach_do,
1178                                         &settings);
1179
1180                         }
1181                 }
1182                 else {
1183                         /* no masking, composite brush directly onto canvas */
1184                         IMB_rectblend_threaded(
1185                                 s->canvas, s->canvas, frombuf, NULL, curveb, texmaskb, mask_max,
1186                                 region[a].destx, region[a].desty,
1187                                 region[a].destx, region[a].desty,
1188                                 region[a].srcx, region[a].srcy,
1189                                 region[a].width, region[a].height, blend, false);
1190                 }
1191         }
1192
1193         if (clonebuf) IMB_freeImBuf(clonebuf);
1194
1195         return 1;
1196 }
1197
1198
1199 static int paint_2d_canvas_set(ImagePaintState *s, Image *ima)
1200 {
1201         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, s->sima ? &s->sima->iuser : NULL, NULL);
1202
1203         /* verify that we can paint and set canvas */
1204         if (ima == NULL) {
1205                 return 0;
1206         }
1207         else if (BKE_image_has_packedfile(ima) && ima->rr) {
1208                 s->warnpackedfile = ima->id.name + 2;
1209                 return 0;
1210         }
1211         else if (ibuf && ibuf->channels != 4) {
1212                 s->warnmultifile = ima->id.name + 2;
1213                 return 0;
1214         }
1215         else if (!ibuf || !(ibuf->rect || ibuf->rect_float))
1216                 return 0;
1217
1218         s->image = ima;
1219         s->canvas = ibuf;
1220
1221         /* set clone canvas */
1222         if (s->tool == PAINT_TOOL_CLONE) {
1223                 ima = s->brush->clone.image;
1224                 ibuf = BKE_image_acquire_ibuf(ima, s->sima ? &s->sima->iuser : NULL, NULL);
1225
1226                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
1227                         BKE_image_release_ibuf(ima, ibuf, NULL);
1228                         BKE_image_release_ibuf(s->image, s->canvas, NULL);
1229                         return 0;
1230                 }
1231
1232                 s->clonecanvas = ibuf;
1233
1234                 /* temporarily add float rect for cloning */
1235                 if (s->canvas->rect_float && !s->clonecanvas->rect_float) {
1236                         IMB_float_from_rect(s->clonecanvas);
1237                 }
1238                 else if (!s->canvas->rect_float && !s->clonecanvas->rect)
1239                         IMB_rect_from_float(s->clonecanvas);
1240         }
1241
1242         /* set masking */
1243         s->do_masking = paint_use_opacity_masking(s->brush);
1244
1245         return 1;
1246 }
1247
1248 static void paint_2d_canvas_free(ImagePaintState *s)
1249 {
1250         BKE_image_release_ibuf(s->image, s->canvas, NULL);
1251         BKE_image_release_ibuf(s->brush->clone.image, s->clonecanvas, NULL);
1252
1253         if (s->blurkernel) {
1254                 paint_delete_blur_kernel(s->blurkernel);
1255                 MEM_freeN(s->blurkernel);
1256         }
1257
1258         image_undo_remove_masks();
1259 }
1260
1261 void paint_2d_stroke(void *ps, const float prev_mval[2], const float mval[2], const bool eraser, float pressure, float distance, float size)
1262 {
1263         float newuv[2], olduv[2];
1264         ImagePaintState *s = ps;
1265         BrushPainter *painter = s->painter;
1266         ImBuf *ibuf = BKE_image_acquire_ibuf(s->image, s->sima ? &s->sima->iuser : NULL, NULL);
1267         const bool is_data = (ibuf && ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA);
1268
1269         if (!ibuf)
1270                 return;
1271
1272         s->blend = s->brush->blend;
1273         if (eraser)
1274                 s->blend = IMB_BLEND_ERASE_ALPHA;
1275
1276         UI_view2d_region_to_view(s->v2d, mval[0], mval[1], &newuv[0], &newuv[1]);
1277         UI_view2d_region_to_view(s->v2d, prev_mval[0], prev_mval[1], &olduv[0], &olduv[1]);
1278
1279         newuv[0] *= ibuf->x;
1280         newuv[1] *= ibuf->y;
1281
1282         olduv[0] *= ibuf->x;
1283         olduv[1] *= ibuf->y;
1284
1285         if (painter->firsttouch) {
1286                 float startuv[2];
1287
1288                 UI_view2d_region_to_view(s->v2d, 0, 0, &startuv[0], &startuv[1]);
1289
1290                 /* paint exactly once on first touch */
1291                 painter->startpaintpos[0] = startuv[0] * ibuf->x;
1292                 painter->startpaintpos[1] = startuv[1] * ibuf->y;
1293
1294                 painter->firsttouch = 0;
1295                 copy_v2_v2(painter->lastpaintpos, newuv);
1296         }
1297         else {
1298                 copy_v2_v2(painter->lastpaintpos, olduv);
1299         }
1300
1301         /* OCIO_TODO: float buffers are now always linear, so always use color correction
1302          *            this should probably be changed when texture painting color space is supported
1303          */
1304         brush_painter_2d_require_imbuf(painter, (ibuf->rect_float != NULL), !is_data);
1305
1306         brush_painter_2d_refresh_cache(s, painter, newuv, mval, pressure, distance, size);
1307
1308         if (paint_2d_op(s, painter->cache.ibuf, painter->cache.curve_mask, painter->cache.tex_mask, olduv, newuv))
1309                 s->need_redraw = true;
1310
1311         BKE_image_release_ibuf(s->image, ibuf, NULL);
1312 }
1313
1314 void *paint_2d_new_stroke(bContext *C, wmOperator *op, int mode)
1315 {
1316         Scene *scene = CTX_data_scene(C);
1317         ToolSettings *settings = scene->toolsettings;
1318         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
1319
1320         ImagePaintState *s = MEM_callocN(sizeof(ImagePaintState), "ImagePaintState");
1321
1322         s->sima = CTX_wm_space_image(C);
1323         s->v2d = &CTX_wm_region(C)->v2d;
1324         s->scene = scene;
1325         s->screen = CTX_wm_screen(C);
1326
1327         s->brush = brush;
1328         s->tool = brush->imagepaint_tool;
1329         s->blend = brush->blend;
1330
1331         s->image = s->sima->image;
1332         s->symmetry = settings->imapaint.paint.symmetry_flags;
1333
1334         if (!paint_2d_canvas_set(s, s->image)) {
1335                 if (s->warnmultifile)
1336                         BKE_report(op->reports, RPT_WARNING, "Image requires 4 color channels to paint");
1337                 if (s->warnpackedfile)
1338                         BKE_report(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted");
1339
1340                 MEM_freeN(s);
1341                 return NULL;
1342         }
1343
1344         if (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) {
1345                 s->blurkernel = paint_new_blur_kernel(brush, false);
1346         }
1347
1348         paint_brush_init_tex(s->brush);
1349
1350         /* create painter */
1351         s->painter = brush_painter_2d_new(scene, s->brush, mode == BRUSH_STROKE_INVERT);
1352
1353         return s;
1354 }
1355
1356 void paint_2d_redraw(const bContext *C, void *ps, bool final)
1357 {
1358         ImagePaintState *s = ps;
1359
1360         if (s->need_redraw) {
1361                 ImBuf *ibuf = BKE_image_acquire_ibuf(s->image, s->sima ? &s->sima->iuser : NULL, NULL);
1362
1363                 imapaint_image_update(s->sima, s->image, ibuf, false);
1364                 ED_imapaint_clear_partial_redraw();
1365
1366                 BKE_image_release_ibuf(s->image, ibuf, NULL);
1367
1368                 s->need_redraw = false;
1369         }
1370         else if (!final) {
1371                 return;
1372         }
1373
1374         if (final) {
1375                 if (s->image && !(s->sima && s->sima->lock))
1376                         GPU_free_image(s->image);
1377
1378                 /* compositor listener deals with updating */
1379                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, s->image);
1380                 DEG_id_tag_update(&s->image->id, 0);
1381         }
1382         else {
1383                 if (!s->sima || !s->sima->lock)
1384                         ED_region_tag_redraw(CTX_wm_region(C));
1385                 else
1386                         WM_event_add_notifier(C, NC_IMAGE | NA_PAINTING, s->image);
1387         }
1388 }
1389
1390 void paint_2d_stroke_done(void *ps)
1391 {
1392         ImagePaintState *s = ps;
1393
1394         paint_2d_canvas_free(s);
1395         brush_painter_2d_free(s->painter);
1396         paint_brush_exit_tex(s->brush);
1397
1398         MEM_freeN(s);
1399 }
1400
1401 static void paint_2d_fill_add_pixel_byte(
1402         const int x_px, const int y_px, ImBuf *ibuf, BLI_Stack *stack, BLI_bitmap *touched,
1403         const float color[4], float threshold_sq)
1404 {
1405         size_t coordinate;
1406
1407         if (x_px >= ibuf->x || x_px < 0 || y_px >= ibuf->y || y_px < 0)
1408                 return;
1409
1410         coordinate = ((size_t)y_px) * ibuf->x + x_px;
1411
1412         if (!BLI_BITMAP_TEST(touched, coordinate)) {
1413                 float color_f[4];
1414                 unsigned char *color_b = (unsigned char *)(ibuf->rect + coordinate);
1415                 rgba_uchar_to_float(color_f, color_b);
1416                 straight_to_premul_v4(color_f);
1417
1418                 if (compare_len_squared_v4v4(color_f, color, threshold_sq)) {
1419                         BLI_stack_push(stack, &coordinate);
1420                 }
1421                 BLI_BITMAP_SET(touched, coordinate, true);
1422         }
1423 }
1424
1425 static void paint_2d_fill_add_pixel_float(
1426         const int x_px, const int y_px, ImBuf *ibuf, BLI_Stack *stack, BLI_bitmap *touched,
1427         const float color[4], float threshold_sq)
1428 {
1429         size_t coordinate;
1430
1431         if (x_px >= ibuf->x || x_px < 0 || y_px >= ibuf->y || y_px < 0)
1432                 return;
1433
1434         coordinate = ((size_t)y_px) * ibuf->x + x_px;
1435
1436         if (!BLI_BITMAP_TEST(touched, coordinate)) {
1437                 if (compare_len_squared_v4v4(ibuf->rect_float + 4 * coordinate, color, threshold_sq)) {
1438                         BLI_stack_push(stack, &coordinate);
1439                 }
1440                 BLI_BITMAP_SET(touched, coordinate, true);
1441         }
1442 }
1443
1444 /* this function expects linear space color values */
1445 void paint_2d_bucket_fill(
1446         const bContext *C, const float color[3], Brush *br,
1447         const float mouse_init[2],
1448         void *ps)
1449 {
1450         SpaceImage *sima = CTX_wm_space_image(C);
1451         Image *ima = sima->image;
1452
1453         ImagePaintState *s = ps;
1454
1455         ImBuf *ibuf;
1456         int x_px, y_px;
1457         unsigned int color_b;
1458         float color_f[4];
1459         float strength = br ? br->alpha : 1.0f;
1460
1461         bool do_float;
1462
1463         if (!ima)
1464                 return;
1465
1466         ibuf = BKE_image_acquire_ibuf(ima, &sima->iuser, NULL);
1467
1468         if (!ibuf)
1469                 return;
1470
1471         do_float = (ibuf->rect_float != NULL);
1472         /* first check if our image is float. If it is not we should correct the color to
1473          * be in gamma space. strictly speaking this is not correct, but blender does not paint
1474          * byte images in linear space */
1475         if (!do_float) {
1476                 linearrgb_to_srgb_uchar3((unsigned char *)&color_b, color);
1477                 *(((char *)&color_b) + 3) = strength * 255;
1478         }
1479         else {
1480                 copy_v3_v3(color_f, color);
1481                 color_f[3] = strength;
1482         }
1483
1484         if (!mouse_init || !br) {
1485                 /* first case, no image UV, fill the whole image */
1486                 ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y, false);
1487
1488                 if (do_float) {
1489                         for (x_px = 0; x_px < ibuf->x; x_px++) {
1490                                 for (y_px = 0; y_px < ibuf->y; y_px++) {
1491                                         blend_color_mix_float(
1492                                                 ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px),
1493                                                 ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), color_f);
1494                                 }
1495                         }
1496                 }
1497                 else {
1498                         for (x_px = 0; x_px < ibuf->x; x_px++) {
1499                                 for (y_px = 0; y_px < ibuf->y; y_px++) {
1500                                         blend_color_mix_byte(
1501                                                 (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px),
1502                                                 (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), (unsigned char *)&color_b);
1503                                 }
1504                         }
1505                 }
1506         }
1507         else {
1508                 /* second case, start sweeping the neighboring pixels, looking for pixels whose
1509                  * value is within the brush fill threshold from the fill color */
1510                 BLI_Stack *stack;
1511                 BLI_bitmap *touched;
1512                 size_t coordinate;
1513                 int width = ibuf->x;
1514                 float image_init[2];
1515                 int minx = ibuf->x, miny = ibuf->y, maxx = 0, maxy = 0;
1516                 float pixel_color[4];
1517                 /* We are comparing to sum of three squared values
1518                  * (assumed in range [0,1]), so need to multiply... */
1519                 float threshold_sq = br->fill_threshold * br->fill_threshold * 3;
1520
1521                 UI_view2d_region_to_view(s->v2d, mouse_init[0], mouse_init[1], &image_init[0], &image_init[1]);
1522
1523                 x_px = image_init[0] * ibuf->x;
1524                 y_px = image_init[1] * ibuf->y;
1525
1526                 if (x_px >= ibuf->x || x_px < 0 || y_px > ibuf->y || y_px < 0) {
1527                         BKE_image_release_ibuf(ima, ibuf, NULL);
1528                         return;
1529                 }
1530
1531                 /* change image invalidation method later */
1532                 ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y, false);
1533
1534                 stack = BLI_stack_new(sizeof(size_t), __func__);
1535                 touched = BLI_BITMAP_NEW(((size_t)ibuf->x) * ibuf->y, "bucket_fill_bitmap");
1536
1537                 coordinate = (((size_t)y_px) * ibuf->x + x_px);
1538
1539                 if (do_float) {
1540                         copy_v4_v4(pixel_color, ibuf->rect_float + 4 * coordinate);
1541                 }
1542                 else {
1543                         int pixel_color_b = *(ibuf->rect + coordinate);
1544                         rgba_uchar_to_float(pixel_color, (unsigned char *)&pixel_color_b);
1545                         straight_to_premul_v4(pixel_color);
1546                 }
1547
1548                 BLI_stack_push(stack, &coordinate);
1549                 BLI_BITMAP_SET(touched, coordinate, true);
1550
1551                 if (do_float) {
1552                         while (!BLI_stack_is_empty(stack)) {
1553                                 BLI_stack_pop(stack, &coordinate);
1554
1555                                 IMB_blend_color_float(
1556                                         ibuf->rect_float + 4 * (coordinate),
1557                                         ibuf->rect_float + 4 * (coordinate),
1558                                         color_f, br->blend);
1559
1560                                 /* reconstruct the coordinates here */
1561                                 x_px = coordinate % width;
1562                                 y_px = coordinate / width;
1563
1564                                 paint_2d_fill_add_pixel_float(x_px - 1, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1565                                 paint_2d_fill_add_pixel_float(x_px - 1, y_px, ibuf, stack, touched, pixel_color, threshold_sq);
1566                                 paint_2d_fill_add_pixel_float(x_px - 1, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1567                                 paint_2d_fill_add_pixel_float(x_px, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1568                                 paint_2d_fill_add_pixel_float(x_px, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1569                                 paint_2d_fill_add_pixel_float(x_px + 1, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1570                                 paint_2d_fill_add_pixel_float(x_px + 1, y_px, ibuf, stack, touched, pixel_color, threshold_sq);
1571                                 paint_2d_fill_add_pixel_float(x_px + 1, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1572
1573                                 if (x_px > maxx)
1574                                         maxx = x_px;
1575                                 if (x_px < minx)
1576                                         minx = x_px;
1577                                 if (y_px > maxy)
1578                                         maxy = y_px;
1579                                 if (x_px > miny)
1580                                         miny = y_px;
1581                         }
1582                 }
1583                 else {
1584                         while (!BLI_stack_is_empty(stack)) {
1585                                 BLI_stack_pop(stack, &coordinate);
1586
1587                                 IMB_blend_color_byte(
1588                                         (unsigned char *)(ibuf->rect + coordinate),
1589                                         (unsigned char *)(ibuf->rect + coordinate),
1590                                         (unsigned char *)&color_b, br->blend);
1591
1592                                 /* reconstruct the coordinates here */
1593                                 x_px = coordinate % width;
1594                                 y_px = coordinate / width;
1595
1596                                 paint_2d_fill_add_pixel_byte(x_px - 1, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1597                                 paint_2d_fill_add_pixel_byte(x_px - 1, y_px, ibuf, stack, touched, pixel_color, threshold_sq);
1598                                 paint_2d_fill_add_pixel_byte(x_px - 1, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1599                                 paint_2d_fill_add_pixel_byte(x_px, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1600                                 paint_2d_fill_add_pixel_byte(x_px, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1601                                 paint_2d_fill_add_pixel_byte(x_px + 1, y_px - 1, ibuf, stack, touched, pixel_color, threshold_sq);
1602                                 paint_2d_fill_add_pixel_byte(x_px + 1, y_px, ibuf, stack, touched, pixel_color, threshold_sq);
1603                                 paint_2d_fill_add_pixel_byte(x_px + 1, y_px + 1, ibuf, stack, touched, pixel_color, threshold_sq);
1604
1605                                 if (x_px > maxx)
1606                                         maxx = x_px;
1607                                 if (x_px < minx)
1608                                         minx = x_px;
1609                                 if (y_px > maxy)
1610                                         maxy = y_px;
1611                                 if (x_px > miny)
1612                                         miny = y_px;
1613                         }
1614                 }
1615
1616                 MEM_freeN(touched);
1617                 BLI_stack_free(stack);
1618         }
1619
1620         imapaint_image_update(sima, ima, ibuf, false);
1621         ED_imapaint_clear_partial_redraw();
1622
1623         BKE_image_release_ibuf(ima, ibuf, NULL);
1624
1625         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1626 }
1627
1628 void paint_2d_gradient_fill(
1629         const bContext *C, Brush *br,
1630         const float mouse_init[2], const float mouse_final[2],
1631         void *ps)
1632 {
1633         SpaceImage *sima = CTX_wm_space_image(C);
1634         Image *ima = sima->image;
1635         ImagePaintState *s = ps;
1636
1637         ImBuf *ibuf;
1638         int x_px, y_px;
1639         unsigned int color_b;
1640         float color_f[4];
1641         float image_init[2], image_final[2];
1642         float tangent[2];
1643         float line_len_sq_inv, line_len;
1644
1645         bool do_float;
1646
1647         if (!ima)
1648                 return;
1649
1650         ibuf = BKE_image_acquire_ibuf(ima, &sima->iuser, NULL);
1651
1652         if (!ibuf)
1653                 return;
1654
1655         UI_view2d_region_to_view(s->v2d, mouse_final[0], mouse_final[1], &image_final[0], &image_final[1]);
1656         UI_view2d_region_to_view(s->v2d, mouse_init[0], mouse_init[1], &image_init[0], &image_init[1]);
1657
1658         image_final[0] *= ibuf->x;
1659         image_final[1] *= ibuf->y;
1660
1661         image_init[0] *= ibuf->x;
1662         image_init[1] *= ibuf->y;
1663
1664         /* some math to get needed gradient variables */
1665         sub_v2_v2v2(tangent, image_final, image_init);
1666         line_len = len_squared_v2(tangent);
1667         line_len_sq_inv = 1.0f / line_len;
1668         line_len = sqrtf(line_len);
1669
1670         do_float = (ibuf->rect_float != NULL);
1671
1672         /* this will be substituted by something else when selection is available */
1673         ED_imapaint_dirty_region(ima, ibuf, 0, 0, ibuf->x, ibuf->y, false);
1674
1675         if (do_float) {
1676                 for (x_px = 0; x_px < ibuf->x; x_px++) {
1677                         for (y_px = 0; y_px < ibuf->y; y_px++) {
1678                                 float f;
1679                                 float p[2] = {x_px - image_init[0], y_px - image_init[1]};
1680
1681                                 switch (br->gradient_fill_mode) {
1682                                         case BRUSH_GRADIENT_LINEAR:
1683                                         {
1684                                                 f = dot_v2v2(p, tangent) * line_len_sq_inv;
1685                                                 break;
1686                                         }
1687                                         case BRUSH_GRADIENT_RADIAL:
1688                                         default:
1689                                         {
1690                                                 f = len_v2(p) / line_len;
1691                                                 break;
1692                                         }
1693                                 }
1694                                 BKE_colorband_evaluate(br->gradient, f, color_f);
1695                                 /* convert to premultiplied */
1696                                 mul_v3_fl(color_f, color_f[3]);
1697                                 color_f[3] *= br->alpha;
1698                                 IMB_blend_color_float(
1699                                         ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px),
1700                                         ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px),
1701                                         color_f, br->blend);
1702                         }
1703                 }
1704         }
1705         else {
1706                 for (x_px = 0; x_px < ibuf->x; x_px++) {
1707                         for (y_px = 0; y_px < ibuf->y; y_px++) {
1708                                 float f;
1709                                 float p[2] = {x_px - image_init[0], y_px - image_init[1]};
1710
1711                                 switch (br->gradient_fill_mode) {
1712                                         case BRUSH_GRADIENT_LINEAR:
1713                                         {
1714                                                 f = dot_v2v2(p, tangent) * line_len_sq_inv;
1715                                                 break;
1716                                         }
1717                                         case BRUSH_GRADIENT_RADIAL:
1718                                         default:
1719                                         {
1720                                                 f = len_v2(p) / line_len;
1721                                                 break;
1722                                         }
1723                                 }
1724
1725                                 BKE_colorband_evaluate(br->gradient, f, color_f);
1726                                 linearrgb_to_srgb_v3_v3(color_f, color_f);
1727                                 rgba_float_to_uchar((unsigned char *)&color_b, color_f);
1728                                 ((unsigned char *)&color_b)[3] *= br->alpha;
1729                                 IMB_blend_color_byte(
1730                                         (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px),
1731                                         (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px),
1732                                         (unsigned char *)&color_b, br->blend);
1733                         }
1734                 }
1735         }
1736
1737         imapaint_image_update(sima, ima, ibuf, false);
1738         ED_imapaint_clear_partial_redraw();
1739
1740         BKE_image_release_ibuf(ima, ibuf, NULL);
1741
1742         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, ima);
1743 }