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