Image paint: 2D painting now supports texture masks and does masking more
[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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/brush.c
29  *  \ingroup bke
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_brush_types.h"
35 #include "DNA_scene_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41 #include "BLI_rect.h"
42
43 #include "BKE_brush.h"
44 #include "BKE_colortools.h"
45 #include "BKE_global.h"
46 #include "BKE_image.h"
47 #include "BKE_library.h"
48 #include "BKE_main.h"
49 #include "BKE_paint.h"
50 #include "BKE_texture.h"
51 #include "BKE_icons.h"
52
53 #include "IMB_imbuf.h"
54 #include "IMB_imbuf_types.h"
55
56 #include "RE_render_ext.h" /* externtex */
57 #include "RE_shader_ext.h"
58
59 static RNG *brush_rng;
60
61 void BKE_brush_system_init(void)
62 {
63         brush_rng = BLI_rng_new(0);
64         BLI_rng_srandom(brush_rng, 31415682);
65 }
66
67 void BKE_brush_system_exit(void)
68 {
69         BLI_rng_free(brush_rng);
70 }
71
72
73 static void brush_defaults(Brush *brush)
74 {
75         brush->blend = 0;
76         brush->flag = 0;
77
78         brush->ob_mode = OB_MODE_ALL_PAINT;
79
80         /* BRUSH SCULPT TOOL SETTINGS */
81         brush->weight = 1.0f; /* weight of brush 0 - 1.0 */
82         brush->size = 35; /* radius of the brush in pixels */
83         brush->alpha = 0.5f; /* brush strength/intensity probably variable should be renamed? */
84         brush->autosmooth_factor = 0.0f;
85         brush->crease_pinch_factor = 0.5f;
86         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
87         brush->plane_offset = 0.0f; /* how far above or below the plane that is found by averaging the faces */
88         brush->plane_trim = 0.5f;
89         brush->clone.alpha = 0.5f;
90         brush->normal_weight = 0.0f;
91         brush->flag |= BRUSH_ALPHA_PRESSURE;
92
93         /* BRUSH PAINT TOOL SETTINGS */
94         brush->rgb[0] = 1.0f; /* default rgb color of the brush when painting - white */
95         brush->rgb[1] = 1.0f;
96         brush->rgb[2] = 1.0f;
97
98         /* BRUSH STROKE SETTINGS */
99         brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
100         brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
101
102         brush->smooth_stroke_radius = 75;
103         brush->smooth_stroke_factor = 0.9f;
104
105         brush->rate = 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
106
107         brush->jitter = 0.0f;
108
109         /* BRUSH TEXTURE SETTINGS */
110         default_mtex(&brush->mtex);
111         default_mtex(&brush->mask_mtex);
112
113         brush->texture_sample_bias = 0; /* value to added to texture samples */
114         brush->texture_overlay_alpha = 33;
115         brush->mask_overlay_alpha = 33;
116         brush->cursor_overlay_alpha = 33;
117         brush->overlay_flags = 0;
118
119         /* brush appearance  */
120
121         brush->add_col[0] = 1.00; /* add mode color is light red */
122         brush->add_col[1] = 0.39;
123         brush->add_col[2] = 0.39;
124
125         brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
126         brush->sub_col[1] = 0.39;
127         brush->sub_col[2] = 1.00;
128
129         brush->stencil_pos[0] = 256;
130         brush->stencil_pos[1] = 256;
131
132         brush->stencil_dimension[0] = 256;
133         brush->stencil_dimension[1] = 256;
134 }
135
136 /* Datablock add/copy/free/make_local */
137
138 Brush *BKE_brush_add(Main *bmain, const char *name)
139 {
140         Brush *brush;
141
142         brush = BKE_libblock_alloc(&bmain->brush, ID_BR, name);
143
144         /* enable fake user by default */
145         brush->id.flag |= LIB_FAKEUSER;
146
147         brush_defaults(brush);
148
149         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
150
151         /* the default alpha falloff curve */
152         BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
153
154         return brush;
155 }
156
157 Brush *BKE_brush_copy(Brush *brush)
158 {
159         Brush *brushn;
160         
161         brushn = BKE_libblock_copy(&brush->id);
162
163         if (brush->mtex.tex)
164                 id_us_plus((ID *)brush->mtex.tex);
165
166         if (brush->mask_mtex.tex)
167                 id_us_plus((ID *)brush->mask_mtex.tex);
168
169         if (brush->icon_imbuf)
170                 brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
171
172         brushn->preview = NULL;
173
174         brushn->curve = curvemapping_copy(brush->curve);
175
176         /* enable fake user by default */
177         if (!(brushn->id.flag & LIB_FAKEUSER)) {
178                 brushn->id.flag |= LIB_FAKEUSER;
179                 brushn->id.us++;
180         }
181         
182         return brushn;
183 }
184
185 /* not brush itself */
186 void BKE_brush_free(Brush *brush)
187 {
188         if (brush->mtex.tex)
189                 brush->mtex.tex->id.us--;
190
191         if (brush->mask_mtex.tex)
192                 brush->mask_mtex.tex->id.us--;
193
194         if (brush->icon_imbuf)
195                 IMB_freeImBuf(brush->icon_imbuf);
196
197         BKE_previewimg_free(&(brush->preview));
198
199         curvemapping_free(brush->curve);
200 }
201
202 static void extern_local_brush(Brush *brush)
203 {
204         id_lib_extern((ID *)brush->mtex.tex);
205         id_lib_extern((ID *)brush->mask_mtex.tex);
206         id_lib_extern((ID *)brush->clone.image);
207 }
208
209 void BKE_brush_make_local(Brush *brush)
210 {
211
212         /* - only lib users: do nothing
213          * - only local users: set flag
214          * - mixed: make copy
215          */
216
217         Main *bmain = G.main;
218         Scene *scene;
219         int is_local = FALSE, is_lib = FALSE;
220
221         if (brush->id.lib == NULL) return;
222
223         if (brush->clone.image) {
224                 /* special case: ima always local immediately. Clone image should only
225                  * have one user anyway. */
226                 id_clear_lib_data(bmain, &brush->clone.image->id);
227                 extern_local_brush(brush);
228         }
229
230         for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
231                 if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
232                         if (scene->id.lib) is_lib = TRUE;
233                         else is_local = TRUE;
234                 }
235         }
236
237         if (is_local && is_lib == FALSE) {
238                 id_clear_lib_data(bmain, &brush->id);
239                 extern_local_brush(brush);
240
241                 /* enable fake user by default */
242                 if (!(brush->id.flag & LIB_FAKEUSER)) {
243                         brush->id.flag |= LIB_FAKEUSER;
244                         brush->id.us++;
245                 }
246         }
247         else if (is_local && is_lib) {
248                 Brush *brush_new = BKE_brush_copy(brush);
249                 brush_new->id.us = 1; /* only keep fake user */
250                 brush_new->id.flag |= LIB_FAKEUSER;
251
252                 /* Remap paths of new ID using old library as base. */
253                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
254                 
255                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
256                         if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
257                                 if (scene->id.lib == NULL) {
258                                         BKE_paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
259                                 }
260                         }
261                 }
262         }
263 }
264
265 void BKE_brush_debug_print_state(Brush *br)
266 {
267         /* create a fake brush and set it to the defaults */
268         Brush def = {{NULL}};
269         brush_defaults(&def);
270         
271 #define BR_TEST(field, t)                                       \
272         if (br->field != def.field)                             \
273                 printf("br->" #field " = %" #t ";\n", br->field)
274
275 #define BR_TEST_FLAG(_f)                                                        \
276         if ((br->flag & _f) && !(def.flag & _f))                \
277                 printf("br->flag |= " #_f ";\n");                       \
278         else if (!(br->flag & _f) && (def.flag & _f))   \
279                 printf("br->flag &= ~" #_f ";\n")
280         
281 #define BR_TEST_FLAG_OVERLAY(_f)                                                        \
282         if ((br->overlay_flags & _f) && !(def.overlay_flags & _f))              \
283                 printf("br->overlay_flags |= " #_f ";\n");                      \
284         else if (!(br->overlay_flags & _f) && (def.overlay_flags & _f)) \
285                 printf("br->overlay_flags &= ~" #_f ";\n")
286
287         /* print out any non-default brush state */
288         BR_TEST(normal_weight, f);
289
290         BR_TEST(blend, d);
291         BR_TEST(size, d);
292
293         /* br->flag */
294         BR_TEST_FLAG(BRUSH_AIRBRUSH);
295         BR_TEST_FLAG(BRUSH_TORUS);
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_RAKE);
301         BR_TEST_FLAG(BRUSH_ANCHORED);
302         BR_TEST_FLAG(BRUSH_DIR_IN);
303         BR_TEST_FLAG(BRUSH_SPACE);
304         BR_TEST_FLAG(BRUSH_SMOOTH_STROKE);
305         BR_TEST_FLAG(BRUSH_PERSISTENT);
306         BR_TEST_FLAG(BRUSH_ACCUMULATE);
307         BR_TEST_FLAG(BRUSH_LOCK_ALPHA);
308         BR_TEST_FLAG(BRUSH_ORIGINAL_NORMAL);
309         BR_TEST_FLAG(BRUSH_OFFSET_PRESSURE);
310         BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
311         BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
312         BR_TEST_FLAG(BRUSH_LOCK_SIZE);
313         BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
314         BR_TEST_FLAG(BRUSH_RESTORE_MESH);
315         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
316         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
317         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
318         BR_TEST_FLAG(BRUSH_FRONTFACE);
319         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
320
321         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR);
322         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY);
323         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY);
324         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE);
325         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE);
326         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE);
327
328         BR_TEST(jitter, f);
329         BR_TEST(spacing, d);
330         BR_TEST(smooth_stroke_radius, d);
331         BR_TEST(smooth_stroke_factor, f);
332         BR_TEST(rate, f);
333
334         BR_TEST(alpha, f);
335
336         BR_TEST(sculpt_plane, d);
337
338         BR_TEST(plane_offset, f);
339
340         BR_TEST(autosmooth_factor, f);
341
342         BR_TEST(crease_pinch_factor, f);
343
344         BR_TEST(plane_trim, f);
345
346         BR_TEST(texture_sample_bias, f);
347         BR_TEST(texture_overlay_alpha, d);
348
349         BR_TEST(add_col[0], f);
350         BR_TEST(add_col[1], f);
351         BR_TEST(add_col[2], f);
352         BR_TEST(sub_col[0], f);
353         BR_TEST(sub_col[1], f);
354         BR_TEST(sub_col[2], f);
355
356         printf("\n");
357         
358 #undef BR_TEST
359 #undef BR_TEST_FLAG
360 }
361
362 void BKE_brush_sculpt_reset(Brush *br)
363 {
364         /* enable this to see any non-default
365          * settings used by a brush: */
366         // BKE_brush_debug_print_state(br);
367
368         brush_defaults(br);
369         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
370
371         switch (br->sculpt_tool) {
372                 case SCULPT_TOOL_CLAY:
373                         br->flag |= BRUSH_FRONTFACE;
374                         break;
375                 case SCULPT_TOOL_CREASE:
376                         br->flag |= BRUSH_DIR_IN;
377                         br->alpha = 0.25;
378                         break;
379                 case SCULPT_TOOL_FILL:
380                         br->add_col[1] = 1;
381                         br->sub_col[0] = 0.25;
382                         br->sub_col[1] = 1;
383                         break;
384                 case SCULPT_TOOL_FLATTEN:
385                         br->add_col[1] = 1;
386                         br->sub_col[0] = 0.25;
387                         br->sub_col[1] = 1;
388                         break;
389                 case SCULPT_TOOL_INFLATE:
390                         br->add_col[0] = 0.750000;
391                         br->add_col[1] = 0.750000;
392                         br->add_col[2] = 0.750000;
393                         br->sub_col[0] = 0.250000;
394                         br->sub_col[1] = 0.250000;
395                         br->sub_col[2] = 0.250000;
396                         break;
397                 case SCULPT_TOOL_NUDGE:
398                         br->add_col[0] = 0.250000;
399                         br->add_col[1] = 1.000000;
400                         br->add_col[2] = 0.250000;
401                         break;
402                 case SCULPT_TOOL_PINCH:
403                         br->add_col[0] = 0.750000;
404                         br->add_col[1] = 0.750000;
405                         br->add_col[2] = 0.750000;
406                         br->sub_col[0] = 0.250000;
407                         br->sub_col[1] = 0.250000;
408                         br->sub_col[2] = 0.250000;
409                         break;
410                 case SCULPT_TOOL_SCRAPE:
411                         br->add_col[1] = 1.000000;
412                         br->sub_col[0] = 0.250000;
413                         br->sub_col[1] = 1.000000;
414                         break;
415                 case SCULPT_TOOL_ROTATE:
416                         br->alpha = 1.0;
417                         break;
418                 case SCULPT_TOOL_SMOOTH:
419                         br->flag &= ~BRUSH_SPACE_ATTEN;
420                         br->spacing = 5;
421                         br->add_col[0] = 0.750000;
422                         br->add_col[1] = 0.750000;
423                         br->add_col[2] = 0.750000;
424                         break;
425                 case SCULPT_TOOL_GRAB:
426                 case SCULPT_TOOL_SNAKE_HOOK:
427                 case SCULPT_TOOL_THUMB:
428                         br->size = 75;
429                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
430                         br->flag &= ~BRUSH_SPACE;
431                         br->flag &= ~BRUSH_SPACE_ATTEN;
432                         br->add_col[0] = 0.250000;
433                         br->add_col[1] = 1.000000;
434                         br->add_col[2] = 0.250000;
435                         break;
436                 default:
437                         break;
438         }
439 }
440
441 /**
442  * Library Operations
443  * \param preset  CurveMappingPreset
444  */
445 void BKE_brush_curve_preset(Brush *b, int preset)
446 {
447         CurveMap *cm = NULL;
448
449         if (!b->curve)
450                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
451
452         cm = b->curve->cm;
453         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
454
455         b->curve->preset = preset;
456         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
457         curvemapping_changed(b->curve, FALSE);
458 }
459
460 int BKE_brush_texture_set_nr(Brush *brush, int nr)
461 {
462         ID *idtest, *id = NULL;
463
464         id = (ID *)brush->mtex.tex;
465
466         idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
467         if (idtest == NULL) { /* new tex */
468                 if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
469                 else idtest = (ID *)add_texture(G.main, "Tex");
470                 idtest->us--;
471         }
472         if (idtest != id) {
473                 BKE_brush_texture_delete(brush);
474
475                 brush->mtex.tex = (Tex *)idtest;
476                 id_us_plus(idtest);
477
478                 return 1;
479         }
480
481         return 0;
482 }
483
484 int BKE_brush_texture_delete(Brush *brush)
485 {
486         if (brush->mtex.tex)
487                 brush->mtex.tex->id.us--;
488
489         return 1;
490 }
491
492 int BKE_brush_clone_image_set_nr(Brush *brush, int nr)
493 {
494         if (brush && nr > 0) {
495                 Image *ima = (Image *)BLI_findlink(&G.main->image, nr - 1);
496
497                 if (ima) {
498                         BKE_brush_clone_image_delete(brush);
499                         brush->clone.image = ima;
500                         id_us_plus(&ima->id);
501                         brush->clone.offset[0] = brush->clone.offset[1] = 0.0f;
502
503                         return 1;
504                 }
505         }
506
507         return 0;
508 }
509
510 int BKE_brush_clone_image_delete(Brush *brush)
511 {
512         if (brush && brush->clone.image) {
513                 brush->clone.image->id.us--;
514                 brush->clone.image = NULL;
515                 return 1;
516         }
517
518         return 0;
519 }
520
521 /* Generic texture sampler for 3D painting systems. point has to be either in
522  * region space mouse coordinates, or 3d world coordinates for 3D mapping.
523  *
524  * rgba outputs straight alpha. */
525 float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
526                               const float point[3],
527                               float rgba[4], const int thread,
528                               struct ImagePool *pool)
529 {
530         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
531         MTex *mtex = &br->mtex;
532         float intensity = 1.0;
533         bool hasrgb = false;
534
535         if (!mtex->tex) {
536                 intensity = 1;
537         }
538         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
539                 /* Get strength by feeding the vertex
540                  * location directly into a texture */
541                 hasrgb = externtex(mtex, point, &intensity,
542                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
543         }
544         else if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
545                 float rotation = -mtex->rot;
546                 float point_2d[2] = {point[0], point[1]};
547                 float x = 0.0f, y = 0.0f; /* Quite warnings */
548                 float co[3];
549
550                 x = point_2d[0] - br->stencil_pos[0];
551                 y = point_2d[1] - br->stencil_pos[1];
552
553                 if (rotation > 0.001f || rotation < -0.001f) {
554                         const float angle    = atan2f(y, x) + rotation;
555                         const float flen     = sqrtf(x * x + y * y);
556
557                         x = flen * cosf(angle);
558                         y = flen * sinf(angle);
559                 }
560
561                 if (fabsf(x) > br->stencil_dimension[0] || fabsf(y) > br->stencil_dimension[1]) {
562                         zero_v4(rgba);
563                         return 0.0f;
564                 }
565                 x /= (br->stencil_dimension[0]);
566                 y /= (br->stencil_dimension[1]);
567
568                 x *= mtex->size[0];
569                 y *= mtex->size[1];
570
571                 co[0] = x + mtex->ofs[0];
572                 co[1] = y + mtex->ofs[1];
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                 x *= mtex->size[0];
629                 y *= mtex->size[1];
630
631                 co[0] = x + mtex->ofs[0];
632                 co[1] = y + mtex->ofs[1];
633                 co[2] = 0.0f;
634
635                 hasrgb = externtex(mtex, co, &intensity,
636                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
637         }
638
639         intensity += br->texture_sample_bias;
640
641         if (!hasrgb) {
642                 rgba[0] = intensity;
643                 rgba[1] = intensity;
644                 rgba[2] = intensity;
645                 rgba[3] = 1.0f;
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 = 0.0f, y = 0.0f; /* Quite warnings */
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 ussual 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_RESTORE_MESH | 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_v2(rand_pos) > 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         curvemapping_initialize(br->curve);
960         strength = curvemapping_evaluateF(br->curve, 0, p);
961
962         CLAMP(strength, 0.0f, 1.0f);
963
964         return strength;
965 }
966 /* same as above but can return negative values if the curve enables
967  * used for sculpt only */
968 float BKE_brush_curve_strength(Brush *br, float p, const float len)
969 {
970         if (p >= len)
971                 p = 1.0f;
972         else
973                 p = p / len;
974
975         curvemapping_initialize(br->curve);
976         return curvemapping_evaluateF(br->curve, 0, p);
977 }
978
979 /* TODO: should probably be unified with BrushPainter stuff? */
980 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
981 {
982         unsigned int *texcache = NULL;
983         MTex *mtex = &br->mtex;
984         TexResult texres = {0};
985         int hasrgb, ix, iy;
986         int side = half_side * 2;
987
988         if (mtex->tex) {
989                 float x, y, step = 2.0 / side, co[3];
990
991                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
992
993                 /* do normalized cannonical view coords for texture */
994                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
995                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
996                                 co[0] = x;
997                                 co[1] = y;
998                                 co[2] = 0.0f;
999
1000                                 /* This is copied from displace modifier code */
1001                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
1002
1003                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1004                                  * intensity, so calculate one (formula from do_material_tex).
1005                                  * if the texture didn't give an RGB value, copy the intensity across
1006                                  */
1007                                 if (hasrgb & TEX_RGB)
1008                                         texres.tin = rgb_to_grayscale(&texres.tr);
1009
1010                                 ((char *)texcache)[(iy * side + ix) * 4] =
1011                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
1012                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
1013                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
1014                         }
1015                 }
1016         }
1017
1018         return texcache;
1019 }
1020
1021
1022 /**** Radial Control ****/
1023 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
1024 {
1025         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1026         unsigned int *texcache;
1027         int side = 128;
1028         int half = side / 2;
1029         int i, j;
1030
1031         texcache = BKE_brush_gen_texture_cache(br, half);
1032         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1033         im->x = im->y = side;
1034
1035         for (i = 0; i < side; ++i) {
1036                 for (j = 0; j < side; ++j) {
1037                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1038                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1039                 }
1040         }
1041
1042         /* Modulate curve with texture */
1043         if (texcache) {
1044                 for (i = 0; i < side; ++i) {
1045                         for (j = 0; j < side; ++j) {
1046                                 const int col = texcache[i * side + j];
1047                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1048                         }
1049                 }
1050
1051                 MEM_freeN(texcache);
1052         }
1053
1054         return im;
1055 }