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