Fix issue with texture painting: Tex slot scale was being applied twice.
[blender.git] / source / blender / blenkernel / intern / brush.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  * Contributor(s): none yet.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/blenkernel/intern/brush.c
24  *  \ingroup bke
25  */
26
27 #include "MEM_guardedalloc.h"
28
29 #include "DNA_brush_types.h"
30 #include "DNA_scene_types.h"
31 #include "DNA_object_types.h"
32
33 #include "BLI_math.h"
34 #include "BLI_blenlib.h"
35 #include "BLI_rand.h"
36 #include "BLI_rect.h"
37
38 #include "BKE_brush.h"
39 #include "BKE_colortools.h"
40 #include "BKE_global.h"
41 #include "BKE_image.h"
42 #include "BKE_library.h"
43 #include "BKE_main.h"
44 #include "BKE_paint.h"
45 #include "BKE_texture.h"
46 #include "BKE_icons.h"
47
48 #include "IMB_colormanagement.h"
49 #include "IMB_imbuf.h"
50 #include "IMB_imbuf_types.h"
51
52 #include "RE_render_ext.h" /* externtex */
53 #include "RE_shader_ext.h"
54
55 static RNG *brush_rng;
56
57 void BKE_brush_system_init(void)
58 {
59         brush_rng = BLI_rng_new(0);
60         BLI_rng_srandom(brush_rng, 31415682);
61 }
62
63 void BKE_brush_system_exit(void)
64 {
65         BLI_rng_free(brush_rng);
66 }
67
68
69 static void brush_defaults(Brush *brush)
70 {
71         brush->blend = 0;
72         brush->flag = 0;
73
74         brush->ob_mode = OB_MODE_ALL_PAINT;
75
76         /* BRUSH SCULPT TOOL SETTINGS */
77         brush->weight = 1.0f; /* weight of brush 0 - 1.0 */
78         brush->size = 35; /* radius of the brush in pixels */
79         brush->alpha = 0.5f; /* brush strength/intensity probably variable should be renamed? */
80         brush->autosmooth_factor = 0.0f;
81         brush->crease_pinch_factor = 0.5f;
82         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
83         brush->plane_offset = 0.0f; /* how far above or below the plane that is found by averaging the faces */
84         brush->plane_trim = 0.5f;
85         brush->clone.alpha = 0.5f;
86         brush->normal_weight = 0.0f;
87         brush->flag |= BRUSH_ALPHA_PRESSURE;
88
89         /* BRUSH PAINT TOOL SETTINGS */
90         brush->rgb[0] = 1.0f; /* default rgb color of the brush when painting - white */
91         brush->rgb[1] = 1.0f;
92         brush->rgb[2] = 1.0f;
93
94         /* BRUSH STROKE SETTINGS */
95         brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
96         brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
97
98         brush->smooth_stroke_radius = 75;
99         brush->smooth_stroke_factor = 0.9f;
100
101         brush->rate = 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
102
103         brush->jitter = 0.0f;
104
105         /* BRUSH TEXTURE SETTINGS */
106         default_mtex(&brush->mtex);
107         default_mtex(&brush->mask_mtex);
108
109         brush->texture_sample_bias = 0; /* value to added to texture samples */
110         brush->texture_overlay_alpha = 33;
111         brush->mask_overlay_alpha = 33;
112         brush->cursor_overlay_alpha = 33;
113         brush->overlay_flags = 0;
114
115         /* brush appearance  */
116
117         brush->add_col[0] = 1.00; /* add mode color is light red */
118         brush->add_col[1] = 0.39;
119         brush->add_col[2] = 0.39;
120
121         brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
122         brush->sub_col[1] = 0.39;
123         brush->sub_col[2] = 1.00;
124
125         brush->stencil_pos[0] = 256;
126         brush->stencil_pos[1] = 256;
127
128         brush->stencil_dimension[0] = 256;
129         brush->stencil_dimension[1] = 256;
130 }
131
132 /* Datablock add/copy/free/make_local */
133
134 Brush *BKE_brush_add(Main *bmain, const char *name)
135 {
136         Brush *brush;
137
138         brush = BKE_libblock_alloc(bmain, ID_BR, name);
139
140         /* enable fake user by default */
141         brush->id.flag |= LIB_FAKEUSER;
142
143         brush_defaults(brush);
144
145         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
146
147         /* the default alpha falloff curve */
148         BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
149
150         return brush;
151 }
152
153 Brush *BKE_brush_copy(Brush *brush)
154 {
155         Brush *brushn;
156         
157         brushn = BKE_libblock_copy(&brush->id);
158
159         if (brush->mtex.tex)
160                 id_us_plus((ID *)brush->mtex.tex);
161
162         if (brush->mask_mtex.tex)
163                 id_us_plus((ID *)brush->mask_mtex.tex);
164
165         if (brush->icon_imbuf)
166                 brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
167
168         brushn->preview = NULL;
169
170         brushn->curve = curvemapping_copy(brush->curve);
171
172         /* enable fake user by default */
173         if (!(brushn->id.flag & LIB_FAKEUSER)) {
174                 brushn->id.flag |= LIB_FAKEUSER;
175                 brushn->id.us++;
176         }
177         
178         return brushn;
179 }
180
181 /* not brush itself */
182 void BKE_brush_free(Brush *brush)
183 {
184         if (brush->mtex.tex)
185                 brush->mtex.tex->id.us--;
186
187         if (brush->mask_mtex.tex)
188                 brush->mask_mtex.tex->id.us--;
189
190         if (brush->icon_imbuf)
191                 IMB_freeImBuf(brush->icon_imbuf);
192
193         BKE_previewimg_free(&(brush->preview));
194
195         curvemapping_free(brush->curve);
196 }
197
198 static void extern_local_brush(Brush *brush)
199 {
200         id_lib_extern((ID *)brush->mtex.tex);
201         id_lib_extern((ID *)brush->mask_mtex.tex);
202         id_lib_extern((ID *)brush->clone.image);
203 }
204
205 void BKE_brush_make_local(Brush *brush)
206 {
207
208         /* - only lib users: do nothing
209          * - only local users: set flag
210          * - mixed: make copy
211          */
212
213         Main *bmain = G.main;
214         Scene *scene;
215         int is_local = FALSE, is_lib = FALSE;
216
217         if (brush->id.lib == NULL) return;
218
219         if (brush->clone.image) {
220                 /* special case: ima always local immediately. Clone image should only
221                  * have one user anyway. */
222                 id_clear_lib_data(bmain, &brush->clone.image->id);
223                 extern_local_brush(brush);
224         }
225
226         for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
227                 if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
228                         if (scene->id.lib) is_lib = TRUE;
229                         else is_local = TRUE;
230                 }
231         }
232
233         if (is_local && is_lib == FALSE) {
234                 id_clear_lib_data(bmain, &brush->id);
235                 extern_local_brush(brush);
236
237                 /* enable fake user by default */
238                 if (!(brush->id.flag & LIB_FAKEUSER)) {
239                         brush->id.flag |= LIB_FAKEUSER;
240                         brush->id.us++;
241                 }
242         }
243         else if (is_local && is_lib) {
244                 Brush *brush_new = BKE_brush_copy(brush);
245                 brush_new->id.us = 1; /* only keep fake user */
246                 brush_new->id.flag |= LIB_FAKEUSER;
247
248                 /* Remap paths of new ID using old library as base. */
249                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
250                 
251                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
252                         if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
253                                 if (scene->id.lib == NULL) {
254                                         BKE_paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
255                                 }
256                         }
257                 }
258         }
259 }
260
261 void BKE_brush_debug_print_state(Brush *br)
262 {
263         /* create a fake brush and set it to the defaults */
264         Brush def = {{NULL}};
265         brush_defaults(&def);
266         
267 #define BR_TEST(field, t)                                       \
268         if (br->field != def.field)                             \
269                 printf("br->" #field " = %" #t ";\n", br->field)
270
271 #define BR_TEST_FLAG(_f)                                                        \
272         if ((br->flag & _f) && !(def.flag & _f))                \
273                 printf("br->flag |= " #_f ";\n");                       \
274         else if (!(br->flag & _f) && (def.flag & _f))   \
275                 printf("br->flag &= ~" #_f ";\n")
276         
277 #define BR_TEST_FLAG_OVERLAY(_f)                                                        \
278         if ((br->overlay_flags & _f) && !(def.overlay_flags & _f))              \
279                 printf("br->overlay_flags |= " #_f ";\n");                      \
280         else if (!(br->overlay_flags & _f) && (def.overlay_flags & _f)) \
281                 printf("br->overlay_flags &= ~" #_f ";\n")
282
283         /* print out any non-default brush state */
284         BR_TEST(normal_weight, f);
285
286         BR_TEST(blend, d);
287         BR_TEST(size, d);
288
289         /* br->flag */
290         BR_TEST_FLAG(BRUSH_AIRBRUSH);
291         BR_TEST_FLAG(BRUSH_TORUS);
292         BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
293         BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
294         BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
295         BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
296         BR_TEST_FLAG(BRUSH_RAKE);
297         BR_TEST_FLAG(BRUSH_ANCHORED);
298         BR_TEST_FLAG(BRUSH_DIR_IN);
299         BR_TEST_FLAG(BRUSH_SPACE);
300         BR_TEST_FLAG(BRUSH_SMOOTH_STROKE);
301         BR_TEST_FLAG(BRUSH_PERSISTENT);
302         BR_TEST_FLAG(BRUSH_ACCUMULATE);
303         BR_TEST_FLAG(BRUSH_LOCK_ALPHA);
304         BR_TEST_FLAG(BRUSH_ORIGINAL_NORMAL);
305         BR_TEST_FLAG(BRUSH_OFFSET_PRESSURE);
306         BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
307         BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
308         BR_TEST_FLAG(BRUSH_LOCK_SIZE);
309         BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
310         BR_TEST_FLAG(BRUSH_DRAG_DOT);
311         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
312         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
313         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
314         BR_TEST_FLAG(BRUSH_FRONTFACE);
315         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
316
317         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR);
318         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY);
319         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY);
320         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE);
321         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE);
322         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE);
323
324         BR_TEST(jitter, f);
325         BR_TEST(spacing, d);
326         BR_TEST(smooth_stroke_radius, d);
327         BR_TEST(smooth_stroke_factor, f);
328         BR_TEST(rate, f);
329
330         BR_TEST(alpha, f);
331
332         BR_TEST(sculpt_plane, d);
333
334         BR_TEST(plane_offset, f);
335
336         BR_TEST(autosmooth_factor, f);
337
338         BR_TEST(crease_pinch_factor, f);
339
340         BR_TEST(plane_trim, f);
341
342         BR_TEST(texture_sample_bias, f);
343         BR_TEST(texture_overlay_alpha, d);
344
345         BR_TEST(add_col[0], f);
346         BR_TEST(add_col[1], f);
347         BR_TEST(add_col[2], f);
348         BR_TEST(sub_col[0], f);
349         BR_TEST(sub_col[1], f);
350         BR_TEST(sub_col[2], f);
351
352         printf("\n");
353         
354 #undef BR_TEST
355 #undef BR_TEST_FLAG
356 }
357
358 void BKE_brush_sculpt_reset(Brush *br)
359 {
360         /* enable this to see any non-default
361          * settings used by a brush: */
362         // BKE_brush_debug_print_state(br);
363
364         brush_defaults(br);
365         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
366
367         switch (br->sculpt_tool) {
368                 case SCULPT_TOOL_CLAY:
369                         br->flag |= BRUSH_FRONTFACE;
370                         break;
371                 case SCULPT_TOOL_CREASE:
372                         br->flag |= BRUSH_DIR_IN;
373                         br->alpha = 0.25;
374                         break;
375                 case SCULPT_TOOL_FILL:
376                         br->add_col[1] = 1;
377                         br->sub_col[0] = 0.25;
378                         br->sub_col[1] = 1;
379                         break;
380                 case SCULPT_TOOL_FLATTEN:
381                         br->add_col[1] = 1;
382                         br->sub_col[0] = 0.25;
383                         br->sub_col[1] = 1;
384                         break;
385                 case SCULPT_TOOL_INFLATE:
386                         br->add_col[0] = 0.750000;
387                         br->add_col[1] = 0.750000;
388                         br->add_col[2] = 0.750000;
389                         br->sub_col[0] = 0.250000;
390                         br->sub_col[1] = 0.250000;
391                         br->sub_col[2] = 0.250000;
392                         break;
393                 case SCULPT_TOOL_NUDGE:
394                         br->add_col[0] = 0.250000;
395                         br->add_col[1] = 1.000000;
396                         br->add_col[2] = 0.250000;
397                         break;
398                 case SCULPT_TOOL_PINCH:
399                         br->add_col[0] = 0.750000;
400                         br->add_col[1] = 0.750000;
401                         br->add_col[2] = 0.750000;
402                         br->sub_col[0] = 0.250000;
403                         br->sub_col[1] = 0.250000;
404                         br->sub_col[2] = 0.250000;
405                         break;
406                 case SCULPT_TOOL_SCRAPE:
407                         br->add_col[1] = 1.000000;
408                         br->sub_col[0] = 0.250000;
409                         br->sub_col[1] = 1.000000;
410                         break;
411                 case SCULPT_TOOL_ROTATE:
412                         br->alpha = 1.0;
413                         break;
414                 case SCULPT_TOOL_SMOOTH:
415                         br->flag &= ~BRUSH_SPACE_ATTEN;
416                         br->spacing = 5;
417                         br->add_col[0] = 0.750000;
418                         br->add_col[1] = 0.750000;
419                         br->add_col[2] = 0.750000;
420                         break;
421                 case SCULPT_TOOL_GRAB:
422                 case SCULPT_TOOL_SNAKE_HOOK:
423                 case SCULPT_TOOL_THUMB:
424                         br->size = 75;
425                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
426                         br->flag &= ~BRUSH_SPACE;
427                         br->flag &= ~BRUSH_SPACE_ATTEN;
428                         br->add_col[0] = 0.250000;
429                         br->add_col[1] = 1.000000;
430                         br->add_col[2] = 0.250000;
431                         break;
432                 default:
433                         break;
434         }
435 }
436
437 /**
438  * Library Operations
439  * \param preset  CurveMappingPreset
440  */
441 void BKE_brush_curve_preset(Brush *b, int preset)
442 {
443         CurveMap *cm = NULL;
444
445         if (!b->curve)
446                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
447
448         cm = b->curve->cm;
449         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
450
451         b->curve->preset = preset;
452         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
453         curvemapping_changed(b->curve, FALSE);
454 }
455
456 int BKE_brush_texture_set_nr(Brush *brush, int nr)
457 {
458         ID *idtest, *id = NULL;
459
460         id = (ID *)brush->mtex.tex;
461
462         idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
463         if (idtest == NULL) { /* new tex */
464                 if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
465                 else idtest = (ID *)add_texture(G.main, "Tex");
466                 idtest->us--;
467         }
468         if (idtest != id) {
469                 BKE_brush_texture_delete(brush);
470
471                 brush->mtex.tex = (Tex *)idtest;
472                 id_us_plus(idtest);
473
474                 return 1;
475         }
476
477         return 0;
478 }
479
480 int BKE_brush_texture_delete(Brush *brush)
481 {
482         if (brush->mtex.tex)
483                 brush->mtex.tex->id.us--;
484
485         return 1;
486 }
487
488 int BKE_brush_clone_image_set_nr(Brush *brush, int nr)
489 {
490         if (brush && nr > 0) {
491                 Image *ima = (Image *)BLI_findlink(&G.main->image, nr - 1);
492
493                 if (ima) {
494                         BKE_brush_clone_image_delete(brush);
495                         brush->clone.image = ima;
496                         id_us_plus(&ima->id);
497                         brush->clone.offset[0] = brush->clone.offset[1] = 0.0f;
498
499                         return 1;
500                 }
501         }
502
503         return 0;
504 }
505
506 int BKE_brush_clone_image_delete(Brush *brush)
507 {
508         if (brush && brush->clone.image) {
509                 brush->clone.image->id.us--;
510                 brush->clone.image = NULL;
511                 return 1;
512         }
513
514         return 0;
515 }
516
517 /* Generic texture sampler for 3D painting systems. point has to be either in
518  * region space mouse coordinates, or 3d world coordinates for 3D mapping.
519  *
520  * rgba outputs straight alpha. */
521 float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
522                               const float point[3],
523                               float rgba[4], const int thread,
524                               struct ImagePool *pool)
525 {
526         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
527         MTex *mtex = &br->mtex;
528         float intensity = 1.0;
529         bool hasrgb = false;
530
531         if (!mtex->tex) {
532                 intensity = 1;
533         }
534         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
535                 /* Get strength by feeding the vertex
536                  * location directly into a texture */
537                 hasrgb = externtex(mtex, point, &intensity,
538                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
539         }
540         else if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
541                 float rotation = -mtex->rot;
542                 float point_2d[2] = {point[0], point[1]};
543                 float x, y;
544                 float co[3];
545
546                 x = point_2d[0] - br->stencil_pos[0];
547                 y = point_2d[1] - br->stencil_pos[1];
548
549                 if (rotation > 0.001f || rotation < -0.001f) {
550                         const float angle    = atan2f(y, x) + rotation;
551                         const float flen     = sqrtf(x * x + y * y);
552
553                         x = flen * cosf(angle);
554                         y = flen * sinf(angle);
555                 }
556
557                 if (fabsf(x) > br->stencil_dimension[0] || fabsf(y) > br->stencil_dimension[1]) {
558                         zero_v4(rgba);
559                         return 0.0f;
560                 }
561                 x /= (br->stencil_dimension[0]);
562                 y /= (br->stencil_dimension[1]);
563
564                 co[0] = x;
565                 co[1] = y;
566                 co[2] = 0.0f;
567
568                 hasrgb = externtex(mtex, co, &intensity,
569                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
570         }
571         else {
572                 float rotation = -mtex->rot;
573                 float point_2d[2] = {point[0], point[1]};
574                 float x = 0.0f, y = 0.0f; /* Quite warnings */
575                 float invradius = 1.0f; /* Quite warnings */
576                 float co[3];
577
578                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
579                         /* keep coordinates relative to mouse */
580
581                         rotation += ups->brush_rotation;
582
583                         x = point_2d[0] - ups->tex_mouse[0];
584                         y = point_2d[1] - ups->tex_mouse[1];
585
586                         /* use pressure adjusted size for fixed mode */
587                         invradius = 1.0f / ups->pixel_radius;
588                 }
589                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
590                         /* leave the coordinates relative to the screen */
591
592                         /* use unadjusted size for tiled mode */
593                         invradius = 1.0f / BKE_brush_size_get(scene, br);
594
595                         x = point_2d[0];
596                         y = point_2d[1];
597                 }
598                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
599                         rotation += ups->brush_rotation;
600                         /* these contain a random coordinate */
601                         x = point_2d[0] - ups->tex_mouse[0];
602                         y = point_2d[1] - ups->tex_mouse[1];
603
604                         invradius = 1.0f / ups->pixel_radius;
605                 }
606
607                 x *= invradius;
608                 y *= invradius;
609
610                 /* it is probably worth optimizing for those cases where
611                  * the texture is not rotated by skipping the calls to
612                  * atan2, sqrtf, sin, and cos. */
613                 if (rotation > 0.001f || rotation < -0.001f) {
614                         const float angle    = atan2f(y, x) + rotation;
615                         const float flen     = sqrtf(x * x + y * y);
616
617                         x = flen * cosf(angle);
618                         y = flen * sinf(angle);
619                 }
620
621                 co[0] = x;
622                 co[1] = y;
623                 co[2] = 0.0f;
624
625                 hasrgb = externtex(mtex, co, &intensity,
626                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
627         }
628
629         intensity += br->texture_sample_bias;
630
631         if (!hasrgb) {
632                 rgba[0] = intensity;
633                 rgba[1] = intensity;
634                 rgba[2] = intensity;
635                 rgba[3] = 1.0f;
636         }
637         else {
638                 if (br->mtex.tex->type == TEX_IMAGE && br->mtex.tex->ima) {
639                         ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(br->mtex.tex->ima, &br->mtex.tex->iuser, pool);
640                         /* For consistency, sampling always returns color in linear space */
641                         if (tex_ibuf && tex_ibuf->rect_float == NULL) {
642                                 IMB_colormanagement_colorspace_to_scene_linear_v3(rgba, tex_ibuf->rect_colorspace);
643                         }
644                         BKE_image_pool_release_ibuf(br->mtex.tex->ima, tex_ibuf, pool);
645                 }
646         }
647
648         return intensity;
649 }
650
651 float BKE_brush_sample_masktex(const Scene *scene, Brush *br,
652                                const float point[3],
653                                const int thread,
654                                struct ImagePool *pool)
655 {
656         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
657         MTex *mtex = &br->mask_mtex;
658         float rgba[4], intensity;
659
660         if (!mtex->tex) {
661                 return 1.0f;
662         }
663         if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
664                 float rotation = -mtex->rot;
665                 float point_2d[2] = {point[0], point[1]};
666                 float x, y;
667                 float co[3];
668
669                 x = point_2d[0] - br->mask_stencil_pos[0];
670                 y = point_2d[1] - br->mask_stencil_pos[1];
671
672                 if (rotation > 0.001f || rotation < -0.001f) {
673                         const float angle    = atan2f(y, x) + rotation;
674                         const float flen     = sqrtf(x * x + y * y);
675
676                         x = flen * cosf(angle);
677                         y = flen * sinf(angle);
678                 }
679
680                 if (fabsf(x) > br->mask_stencil_dimension[0] || fabsf(y) > br->mask_stencil_dimension[1]) {
681                         zero_v4(rgba);
682                         return 0.0f;
683                 }
684                 x /= (br->mask_stencil_dimension[0]);
685                 y /= (br->mask_stencil_dimension[1]);
686
687                 x *= mtex->size[0];
688                 y *= mtex->size[1];
689
690                 co[0] = x + mtex->ofs[0];
691                 co[1] = y + mtex->ofs[1];
692                 co[2] = 0.0f;
693
694                 externtex(mtex, co, &intensity,
695                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
696         }
697         else {
698                 float rotation = -mtex->rot;
699                 float point_2d[2] = {point[0], point[1]};
700                 float x = 0.0f, y = 0.0f; /* Quite warnings */
701                 float invradius = 1.0f; /* Quite warnings */
702                 float co[3];
703
704                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
705                         /* keep coordinates relative to mouse */
706
707                         rotation += ups->brush_rotation;
708
709                         x = point_2d[0] - ups->mask_tex_mouse[0];
710                         y = point_2d[1] - ups->mask_tex_mouse[1];
711
712                         /* use pressure adjusted size for fixed mode */
713                         invradius = 1.0f / ups->pixel_radius;
714                 }
715                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
716                         /* leave the coordinates relative to the screen */
717
718                         /* use unadjusted size for tiled mode */
719                         invradius = 1.0f / BKE_brush_size_get(scene, br);
720
721                         x = point_2d[0];
722                         y = point_2d[1];
723                 }
724                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
725                         rotation += ups->brush_rotation;
726                         /* these contain a random coordinate */
727                         x = point_2d[0] - ups->mask_tex_mouse[0];
728                         y = point_2d[1] - ups->mask_tex_mouse[1];
729
730                         invradius = 1.0f / ups->pixel_radius;
731                 }
732
733                 x *= invradius;
734                 y *= invradius;
735
736                 /* it is probably worth optimizing for those cases where
737                  * the texture is not rotated by skipping the calls to
738                  * atan2, sqrtf, sin, and cos. */
739                 if (rotation > 0.001f || rotation < -0.001f) {
740                         const float angle    = atan2f(y, x) + rotation;
741                         const float flen     = sqrtf(x * x + y * y);
742
743                         x = flen * cosf(angle);
744                         y = flen * sinf(angle);
745                 }
746
747                 x *= mtex->size[0];
748                 y *= mtex->size[1];
749
750                 co[0] = x + mtex->ofs[0];
751                 co[1] = y + mtex->ofs[1];
752                 co[2] = 0.0f;
753
754                 externtex(mtex, co, &intensity,
755                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
756         }
757
758         return intensity;
759 }
760
761 /* Unified Size and Strength */
762
763 /* XXX: be careful about setting size and unprojected radius
764  * because they depend on one another
765  * these functions do not set the other corresponding value
766  * this can lead to odd behavior if size and unprojected
767  * radius become inconsistent.
768  * the biggest problem is that it isn't possible to change
769  * unprojected radius because a view context is not
770  * available.  my usual solution to this is to use the
771  * ratio of change of the size to change the unprojected
772  * radius.  Not completely convinced that is correct.
773  * In any case, a better solution is needed to prevent
774  * inconsistency. */
775
776 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
777 {
778         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
779         
780         size = (int)((float)size / U.pixelsize);
781         
782         if (ups->flag & UNIFIED_PAINT_SIZE)
783                 ups->size = size;
784         else
785                 brush->size = size;
786 }
787
788 int BKE_brush_size_get(const Scene *scene, Brush *brush)
789 {
790         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
791         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
792         
793         return (int)((float)size * U.pixelsize);
794 }
795
796 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
797 {
798         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
799
800         return (us_flag & UNIFIED_PAINT_SIZE) ?
801                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
802                (brush->flag & BRUSH_LOCK_SIZE);
803 }
804
805 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
806 {
807         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
808
809         return (us_flag & UNIFIED_PAINT_SIZE) ?
810                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
811                (brush->flag & BRUSH_SIZE_PRESSURE);
812 }
813
814 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
815 {
816         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
817
818         return (us_flag & UNIFIED_PAINT_ALPHA) ?
819                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
820                (brush->flag & BRUSH_ALPHA_PRESSURE);
821 }
822
823 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
824 {
825         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
826
827         if (ups->flag & UNIFIED_PAINT_SIZE)
828                 ups->unprojected_radius = unprojected_radius;
829         else
830                 brush->unprojected_radius = unprojected_radius;
831 }
832
833 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
834 {
835         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
836
837         return (ups->flag & UNIFIED_PAINT_SIZE) ?
838                ups->unprojected_radius :
839                brush->unprojected_radius;
840 }
841
842 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
843 {
844         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
845
846         if (ups->flag & UNIFIED_PAINT_ALPHA)
847                 ups->alpha = alpha;
848         else
849                 brush->alpha = alpha;
850 }
851
852 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
853 {
854         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
855
856         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
857 }
858
859 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
860 {
861         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
862
863         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
864 }
865
866 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
867 {
868         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
869
870         if (ups->flag & UNIFIED_PAINT_WEIGHT)
871                 ups->weight = value;
872         else
873                 brush->weight = value;
874 }
875
876 /* scale unprojected radius to reflect a change in the brush's 2D size */
877 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
878                                         int new_brush_size,
879                                         int old_brush_size)
880 {
881         float scale = new_brush_size;
882         /* avoid division by zero */
883         if (old_brush_size != 0)
884                 scale /= (float)old_brush_size;
885         (*unprojected_radius) *= scale;
886 }
887
888 /* scale brush size to reflect a change in the brush's unprojected radius */
889 void BKE_brush_scale_size(int *r_brush_size,
890                           float new_unprojected_radius,
891                           float old_unprojected_radius)
892 {
893         float scale = new_unprojected_radius;
894         /* avoid division by zero */
895         if (old_unprojected_radius != 0)
896                 scale /= new_unprojected_radius;
897         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
898 }
899
900 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
901 {
902         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
903                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
904
905         /* jitter-ed brush gives weird and unpredictable result for this
906          * kinds of stroke, so manually disable jitter usage (sergey) */
907         use_jitter &= (brush->flag & (BRUSH_DRAG_DOT | BRUSH_ANCHORED)) == 0;
908
909         if (use_jitter) {
910                 float rand_pos[2];
911                 float spread;
912                 int diameter;
913
914                 do {
915                         rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
916                         rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
917                 } while (len_squared_v2(rand_pos) > (0.5f * 0.5f));
918
919
920                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
921                         diameter = 2 * brush->jitter_absolute;
922                         spread = 1.0;
923                 }
924                 else {
925                         diameter = 2 * BKE_brush_size_get(scene, brush);
926                         spread = brush->jitter;
927                 }
928                 /* find random position within a circle of diameter 1 */
929                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
930                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
931         }
932         else {
933                 copy_v2_v2(jitterpos, pos);
934         }
935 }
936
937 void BKE_brush_randomize_texture_coordinates(UnifiedPaintSettings *ups, bool mask)
938 {
939         /* we multiply with brush radius as an optimization for the brush
940          * texture sampling functions */
941         if (mask) {
942                 ups->mask_tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
943                 ups->mask_tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
944         }
945         else {
946                 ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
947                 ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
948         }
949 }
950
951 /* Uses the brush curve control to find a strength value between 0 and 1 */
952 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
953 {
954         float strength;
955
956         if (p >= len) return 0;
957         else p = p / len;
958
959         strength = curvemapping_evaluateF(br->curve, 0, p);
960
961         CLAMP(strength, 0.0f, 1.0f);
962
963         return strength;
964 }
965 /* same as above but can return negative values if the curve enables
966  * used for sculpt only */
967 float BKE_brush_curve_strength(Brush *br, float p, const float len)
968 {
969         if (p >= len)
970                 p = 1.0f;
971         else
972                 p = p / len;
973
974         return curvemapping_evaluateF(br->curve, 0, p);
975 }
976
977 /* TODO: should probably be unified with BrushPainter stuff? */
978 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side, bool use_secondary)
979 {
980         unsigned int *texcache = NULL;
981         MTex *mtex = (use_secondary) ? &br->mask_mtex : &br->mtex;
982         float intensity;
983         float rgba[4];
984         int ix, iy;
985         int side = half_side * 2;
986
987         if (mtex->tex) {
988                 float x, y, step = 2.0 / side, co[3];
989
990                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
991
992                 /* do normalized cannonical view coords for texture */
993                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
994                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
995                                 co[0] = x;
996                                 co[1] = y;
997                                 co[2] = 0.0f;
998
999                                 /* This is copied from displace modifier code */
1000                                 /* TODO(sergey): brush are always cacheing with CM enabled for now. */
1001                                 externtex(mtex, co, &intensity,
1002                                                   rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL);
1003
1004                                 ((char *)texcache)[(iy * side + ix) * 4] =
1005                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
1006                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
1007                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(intensity * 255.0f);
1008                         }
1009                 }
1010         }
1011
1012         return texcache;
1013 }
1014
1015
1016 /**** Radial Control ****/
1017 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br, bool secondary)
1018 {
1019         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1020         unsigned int *texcache;
1021         int side = 128;
1022         int half = side / 2;
1023         int i, j;
1024
1025         curvemapping_initialize(br->curve);
1026         texcache = BKE_brush_gen_texture_cache(br, half, secondary);
1027         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1028         im->x = im->y = side;
1029
1030         for (i = 0; i < side; ++i) {
1031                 for (j = 0; j < side; ++j) {
1032                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1033                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1034                 }
1035         }
1036
1037         /* Modulate curve with texture */
1038         if (texcache) {
1039                 for (i = 0; i < side; ++i) {
1040                         for (j = 0; j < side; ++j) {
1041                                 const int col = texcache[i * side + j];
1042                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1043                         }
1044                 }
1045
1046                 MEM_freeN(texcache);
1047         }
1048
1049         return im;
1050 }