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