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