More image painting fixes:
[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
42 #include "BKE_brush.h"
43 #include "BKE_colortools.h"
44 #include "BKE_global.h"
45 #include "BKE_image.h"
46 #include "BKE_library.h"
47 #include "BKE_main.h"
48 #include "BKE_paint.h"
49 #include "BKE_texture.h"
50 #include "BKE_icons.h"
51
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "RE_render_ext.h" /* externtex */
56 #include "RE_shader_ext.h"
57
58 static RNG *brush_rng;
59
60 void BKE_brush_system_init(void)
61 {
62         brush_rng = BLI_rng_new(0);
63         BLI_rng_srandom(brush_rng, 31415682);
64 }
65
66 void BKE_brush_system_exit(void)
67 {
68         BLI_rng_free(brush_rng);
69 }
70
71
72 static void brush_defaults(Brush *brush)
73 {
74         brush->blend = 0;
75         brush->flag = 0;
76
77         brush->ob_mode = OB_MODE_ALL_PAINT;
78
79         /* BRUSH SCULPT TOOL SETTINGS */
80         brush->weight = 1.0f; /* weight of brush 0 - 1.0 */
81         brush->size = 35; /* radius of the brush in pixels */
82         brush->alpha = 0.5f; /* brush strength/intensity probably variable should be renamed? */
83         brush->autosmooth_factor = 0.0f;
84         brush->crease_pinch_factor = 0.5f;
85         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
86         brush->plane_offset = 0.0f; /* how far above or below the plane that is found by averaging the faces */
87         brush->plane_trim = 0.5f;
88         brush->clone.alpha = 0.5f;
89         brush->normal_weight = 0.0f;
90         brush->flag |= BRUSH_ALPHA_PRESSURE;
91
92         /* BRUSH PAINT TOOL SETTINGS */
93         brush->rgb[0] = 1.0f; /* default rgb color of the brush when painting - white */
94         brush->rgb[1] = 1.0f;
95         brush->rgb[2] = 1.0f;
96
97         /* BRUSH STROKE SETTINGS */
98         brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
99         brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
100
101         brush->smooth_stroke_radius = 75;
102         brush->smooth_stroke_factor = 0.9f;
103
104         brush->rate = 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
105
106         brush->jitter = 0.0f;
107
108         /* BRUSH TEXTURE SETTINGS */
109         default_mtex(&brush->mtex);
110         default_mtex(&brush->mask_mtex);
111
112         brush->texture_sample_bias = 0; /* value to added to texture samples */
113         brush->texture_overlay_alpha = 33;
114         brush->mask_overlay_alpha = 33;
115         brush->cursor_overlay_alpha = 33;
116         brush->overlay_flags = 0;
117
118         /* brush appearance  */
119
120         brush->add_col[0] = 1.00; /* add mode color is light red */
121         brush->add_col[1] = 0.39;
122         brush->add_col[2] = 0.39;
123
124         brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
125         brush->sub_col[1] = 0.39;
126         brush->sub_col[2] = 1.00;
127
128         brush->stencil_pos[0] = 256;
129         brush->stencil_pos[1] = 256;
130
131         brush->stencil_dimension[0] = 256;
132         brush->stencil_dimension[1] = 256;
133 }
134
135 /* Datablock add/copy/free/make_local */
136
137 Brush *BKE_brush_add(Main *bmain, const char *name)
138 {
139         Brush *brush;
140
141         brush = BKE_libblock_alloc(&bmain->brush, ID_BR, name);
142
143         /* enable fake user by default */
144         brush->id.flag |= LIB_FAKEUSER;
145
146         brush_defaults(brush);
147
148         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
149
150         /* the default alpha falloff curve */
151         BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
152
153         return brush;
154 }
155
156 Brush *BKE_brush_copy(Brush *brush)
157 {
158         Brush *brushn;
159         
160         brushn = BKE_libblock_copy(&brush->id);
161
162         if (brush->mtex.tex)
163                 id_us_plus((ID *)brush->mtex.tex);
164
165         if (brush->mask_mtex.tex)
166                 id_us_plus((ID *)brush->mask_mtex.tex);
167
168         if (brush->icon_imbuf)
169                 brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
170
171         brushn->preview = NULL;
172
173         brushn->curve = curvemapping_copy(brush->curve);
174
175         /* enable fake user by default */
176         if (!(brushn->id.flag & LIB_FAKEUSER)) {
177                 brushn->id.flag |= LIB_FAKEUSER;
178                 brushn->id.us++;
179         }
180         
181         return brushn;
182 }
183
184 /* not brush itself */
185 void BKE_brush_free(Brush *brush)
186 {
187         if (brush->mtex.tex)
188                 brush->mtex.tex->id.us--;
189
190         if (brush->mask_mtex.tex)
191                 brush->mask_mtex.tex->id.us--;
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
201 static void extern_local_brush(Brush *brush)
202 {
203         id_lib_extern((ID *)brush->mtex.tex);
204         id_lib_extern((ID *)brush->mask_mtex.tex);
205         id_lib_extern((ID *)brush->clone.image);
206 }
207
208 void BKE_brush_make_local(Brush *brush)
209 {
210
211         /* - only lib users: do nothing
212          * - only local users: set flag
213          * - mixed: make copy
214          */
215
216         Main *bmain = G.main;
217         Scene *scene;
218         int is_local = FALSE, is_lib = FALSE;
219
220         if (brush->id.lib == NULL) return;
221
222         if (brush->clone.image) {
223                 /* special case: ima always local immediately. Clone image should only
224                  * have one user anyway. */
225                 id_clear_lib_data(bmain, &brush->clone.image->id);
226                 extern_local_brush(brush);
227         }
228
229         for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
230                 if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
231                         if (scene->id.lib) is_lib = TRUE;
232                         else is_local = TRUE;
233                 }
234         }
235
236         if (is_local && is_lib == FALSE) {
237                 id_clear_lib_data(bmain, &brush->id);
238                 extern_local_brush(brush);
239
240                 /* enable fake user by default */
241                 if (!(brush->id.flag & LIB_FAKEUSER)) {
242                         brush->id.flag |= LIB_FAKEUSER;
243                         brush->id.us++;
244                 }
245         }
246         else if (is_local && is_lib) {
247                 Brush *brush_new = BKE_brush_copy(brush);
248                 brush_new->id.us = 1; /* only keep fake user */
249                 brush_new->id.flag |= LIB_FAKEUSER;
250
251                 /* Remap paths of new ID using old library as base. */
252                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
253                 
254                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
255                         if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
256                                 if (scene->id.lib == NULL) {
257                                         BKE_paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
258                                 }
259                         }
260                 }
261         }
262 }
263
264 void BKE_brush_debug_print_state(Brush *br)
265 {
266         /* create a fake brush and set it to the defaults */
267         Brush def = {{NULL}};
268         brush_defaults(&def);
269         
270 #define BR_TEST(field, t)                                       \
271         if (br->field != def.field)                             \
272                 printf("br->" #field " = %" #t ";\n", br->field)
273
274 #define BR_TEST_FLAG(_f)                                                        \
275         if ((br->flag & _f) && !(def.flag & _f))                \
276                 printf("br->flag |= " #_f ";\n");                       \
277         else if (!(br->flag & _f) && (def.flag & _f))   \
278                 printf("br->flag &= ~" #_f ";\n")
279         
280 #define BR_TEST_FLAG_OVERLAY(_f)                                                        \
281         if ((br->overlay_flags & _f) && !(def.overlay_flags & _f))              \
282                 printf("br->overlay_flags |= " #_f ";\n");                      \
283         else if (!(br->overlay_flags & _f) && (def.overlay_flags & _f)) \
284                 printf("br->overlay_flags &= ~" #_f ";\n")
285
286         /* print out any non-default brush state */
287         BR_TEST(normal_weight, f);
288
289         BR_TEST(blend, d);
290         BR_TEST(size, d);
291
292         /* br->flag */
293         BR_TEST_FLAG(BRUSH_AIRBRUSH);
294         BR_TEST_FLAG(BRUSH_TORUS);
295         BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
296         BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
297         BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
298         BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
299         BR_TEST_FLAG(BRUSH_RAKE);
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_RESTORE_MESH);
314         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
315         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
316         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
317         BR_TEST_FLAG(BRUSH_FRONTFACE);
318         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
319
320         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR);
321         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY);
322         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY);
323         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE);
324         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE);
325         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE);
326
327         BR_TEST(jitter, f);
328         BR_TEST(spacing, d);
329         BR_TEST(smooth_stroke_radius, d);
330         BR_TEST(smooth_stroke_factor, f);
331         BR_TEST(rate, f);
332
333         BR_TEST(alpha, f);
334
335         BR_TEST(sculpt_plane, d);
336
337         BR_TEST(plane_offset, f);
338
339         BR_TEST(autosmooth_factor, f);
340
341         BR_TEST(crease_pinch_factor, f);
342
343         BR_TEST(plane_trim, f);
344
345         BR_TEST(texture_sample_bias, f);
346         BR_TEST(texture_overlay_alpha, d);
347
348         BR_TEST(add_col[0], f);
349         BR_TEST(add_col[1], f);
350         BR_TEST(add_col[2], f);
351         BR_TEST(sub_col[0], f);
352         BR_TEST(sub_col[1], f);
353         BR_TEST(sub_col[2], f);
354
355         printf("\n");
356         
357 #undef BR_TEST
358 #undef BR_TEST_FLAG
359 }
360
361 void BKE_brush_sculpt_reset(Brush *br)
362 {
363         /* enable this to see any non-default
364          * settings used by a brush: */
365         // BKE_brush_debug_print_state(br);
366
367         brush_defaults(br);
368         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
369
370         switch (br->sculpt_tool) {
371                 case SCULPT_TOOL_CLAY:
372                         br->flag |= BRUSH_FRONTFACE;
373                         break;
374                 case SCULPT_TOOL_CREASE:
375                         br->flag |= BRUSH_DIR_IN;
376                         br->alpha = 0.25;
377                         break;
378                 case SCULPT_TOOL_FILL:
379                         br->add_col[1] = 1;
380                         br->sub_col[0] = 0.25;
381                         br->sub_col[1] = 1;
382                         break;
383                 case SCULPT_TOOL_FLATTEN:
384                         br->add_col[1] = 1;
385                         br->sub_col[0] = 0.25;
386                         br->sub_col[1] = 1;
387                         break;
388                 case SCULPT_TOOL_INFLATE:
389                         br->add_col[0] = 0.750000;
390                         br->add_col[1] = 0.750000;
391                         br->add_col[2] = 0.750000;
392                         br->sub_col[0] = 0.250000;
393                         br->sub_col[1] = 0.250000;
394                         br->sub_col[2] = 0.250000;
395                         break;
396                 case SCULPT_TOOL_NUDGE:
397                         br->add_col[0] = 0.250000;
398                         br->add_col[1] = 1.000000;
399                         br->add_col[2] = 0.250000;
400                         break;
401                 case SCULPT_TOOL_PINCH:
402                         br->add_col[0] = 0.750000;
403                         br->add_col[1] = 0.750000;
404                         br->add_col[2] = 0.750000;
405                         br->sub_col[0] = 0.250000;
406                         br->sub_col[1] = 0.250000;
407                         br->sub_col[2] = 0.250000;
408                         break;
409                 case SCULPT_TOOL_SCRAPE:
410                         br->add_col[1] = 1.000000;
411                         br->sub_col[0] = 0.250000;
412                         br->sub_col[1] = 1.000000;
413                         break;
414                 case SCULPT_TOOL_ROTATE:
415                         br->alpha = 1.0;
416                         break;
417                 case SCULPT_TOOL_SMOOTH:
418                         br->flag &= ~BRUSH_SPACE_ATTEN;
419                         br->spacing = 5;
420                         br->add_col[0] = 0.750000;
421                         br->add_col[1] = 0.750000;
422                         br->add_col[2] = 0.750000;
423                         break;
424                 case SCULPT_TOOL_GRAB:
425                 case SCULPT_TOOL_SNAKE_HOOK:
426                 case SCULPT_TOOL_THUMB:
427                         br->size = 75;
428                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
429                         br->flag &= ~BRUSH_SPACE;
430                         br->flag &= ~BRUSH_SPACE_ATTEN;
431                         br->add_col[0] = 0.250000;
432                         br->add_col[1] = 1.000000;
433                         br->add_col[2] = 0.250000;
434                         break;
435                 default:
436                         break;
437         }
438 }
439
440 /**
441  * Library Operations
442  * \param preset  CurveMappingPreset
443  */
444 void BKE_brush_curve_preset(Brush *b, int preset)
445 {
446         CurveMap *cm = NULL;
447
448         if (!b->curve)
449                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
450
451         cm = b->curve->cm;
452         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
453
454         b->curve->preset = preset;
455         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
456         curvemapping_changed(b->curve, FALSE);
457 }
458
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((Tex *)id);
468                 else idtest = (ID *)add_texture(G.main, "Tex");
469                 idtest->us--;
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                 brush->mtex.tex->id.us--;
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                 brush->clone.image->id.us--;
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);
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 = 0.0f, y = 0.0f; /* Quite warnings */
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                 x *= mtex->size[0];
568                 y *= mtex->size[1];
569
570                 co[0] = x + mtex->ofs[0];
571                 co[1] = y + mtex->ofs[1];
572                 co[2] = 0.0f;
573
574                 hasrgb = externtex(mtex, co, &intensity,
575                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
576         }
577         else {
578                 float rotation = -mtex->rot;
579                 float point_2d[2] = {point[0], point[1]};
580                 float x = 0.0f, y = 0.0f; /* Quite warnings */
581                 float invradius = 1.0f; /* Quite warnings */
582                 float co[3];
583
584                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
585                         /* keep coordinates relative to mouse */
586
587                         rotation += ups->brush_rotation;
588
589                         x = point_2d[0] - ups->tex_mouse[0];
590                         y = point_2d[1] - ups->tex_mouse[1];
591
592                         /* use pressure adjusted size for fixed mode */
593                         invradius = 1.0f / ups->pixel_radius;
594                 }
595                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
596                         /* leave the coordinates relative to the screen */
597
598                         /* use unadjusted size for tiled mode */
599                         invradius = 1.0f / BKE_brush_size_get(scene, br);
600
601                         x = point_2d[0];
602                         y = point_2d[1];
603                 }
604                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
605                         rotation += ups->brush_rotation;
606                         /* these contain a random coordinate */
607                         x = point_2d[0] - ups->tex_mouse[0];
608                         y = point_2d[1] - ups->tex_mouse[1];
609
610                         invradius = 1.0f / ups->pixel_radius;
611                 }
612
613                 x *= invradius;
614                 y *= invradius;
615
616                 /* it is probably worth optimizing for those cases where
617                  * the texture is not rotated by skipping the calls to
618                  * atan2, sqrtf, sin, and cos. */
619                 if (rotation > 0.001f || rotation < -0.001f) {
620                         const float angle    = atan2f(y, x) + rotation;
621                         const float flen     = sqrtf(x * x + y * y);
622
623                         x = flen * cosf(angle);
624                         y = flen * sinf(angle);
625                 }
626
627                 x *= mtex->size[0];
628                 y *= mtex->size[1];
629
630                 co[0] = x + mtex->ofs[0];
631                 co[1] = y + mtex->ofs[1];
632                 co[2] = 0.0f;
633
634                 hasrgb = externtex(mtex, co, &intensity,
635                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
636         }
637
638         intensity += br->texture_sample_bias;
639
640         if (!hasrgb) {
641                 rgba[0] = intensity;
642                 rgba[1] = intensity;
643                 rgba[2] = intensity;
644                 rgba[3] = 1.0f;
645         }
646
647         return intensity;
648 }
649
650 float BKE_brush_sample_masktex(const Scene *scene, Brush *br,
651                                const float point[3],
652                                const int thread,
653                                struct ImagePool *pool)
654 {
655         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
656         MTex *mtex = &br->mask_mtex;
657         float rgba[4], intensity;
658
659         if (!mtex->tex) {
660                 return 1.0f;
661         }
662         if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
663                 float rotation = -mtex->rot;
664                 float point_2d[2] = {point[0], point[1]};
665                 float x = 0.0f, y = 0.0f; /* Quite warnings */
666                 float co[3];
667
668                 x = point_2d[0] - br->mask_stencil_pos[0];
669                 y = point_2d[1] - br->mask_stencil_pos[1];
670
671                 if (rotation > 0.001f || rotation < -0.001f) {
672                         const float angle    = atan2f(y, x) + rotation;
673                         const float flen     = sqrtf(x * x + y * y);
674
675                         x = flen * cosf(angle);
676                         y = flen * sinf(angle);
677                 }
678
679                 if (fabsf(x) > br->mask_stencil_dimension[0] || fabsf(y) > br->mask_stencil_dimension[1]) {
680                         zero_v4(rgba);
681                         return 0.0f;
682                 }
683                 x /= (br->mask_stencil_dimension[0]);
684                 y /= (br->mask_stencil_dimension[1]);
685
686                 x *= mtex->size[0];
687                 y *= mtex->size[1];
688
689                 co[0] = x + mtex->ofs[0];
690                 co[1] = y + mtex->ofs[1];
691                 co[2] = 0.0f;
692
693                 externtex(mtex, co, &intensity,
694                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
695         }
696         else {
697                 float rotation = -mtex->rot;
698                 float point_2d[2] = {point[0], point[1]};
699                 float x = 0.0f, y = 0.0f; /* Quite warnings */
700                 float invradius = 1.0f; /* Quite warnings */
701                 float co[3];
702
703                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
704                         /* keep coordinates relative to mouse */
705
706                         rotation += ups->brush_rotation;
707
708                         x = point_2d[0] - ups->mask_tex_mouse[0];
709                         y = point_2d[1] - ups->mask_tex_mouse[1];
710
711                         /* use pressure adjusted size for fixed mode */
712                         invradius = 1.0f / ups->pixel_radius;
713                 }
714                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
715                         /* leave the coordinates relative to the screen */
716
717                         /* use unadjusted size for tiled mode */
718                         invradius = 1.0f / BKE_brush_size_get(scene, br);
719
720                         x = point_2d[0];
721                         y = point_2d[1];
722                 }
723                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
724                         rotation += ups->brush_rotation;
725                         /* these contain a random coordinate */
726                         x = point_2d[0] - ups->mask_tex_mouse[0];
727                         y = point_2d[1] - ups->mask_tex_mouse[1];
728
729                         invradius = 1.0f / ups->pixel_radius;
730                 }
731
732                 x *= invradius;
733                 y *= invradius;
734
735                 /* it is probably worth optimizing for those cases where
736                  * the texture is not rotated by skipping the calls to
737                  * atan2, sqrtf, sin, and cos. */
738                 if (rotation > 0.001f || rotation < -0.001f) {
739                         const float angle    = atan2f(y, x) + rotation;
740                         const float flen     = sqrtf(x * x + y * y);
741
742                         x = flen * cosf(angle);
743                         y = flen * sinf(angle);
744                 }
745
746                 x *= mtex->size[0];
747                 y *= mtex->size[1];
748
749                 co[0] = x + mtex->ofs[0];
750                 co[1] = y + mtex->ofs[1];
751                 co[2] = 0.0f;
752
753                 externtex(mtex, co, &intensity,
754                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
755         }
756
757         return intensity;
758 }
759
760 /* Brush Sampling for 2D brushes. when we unify the brush systems this will be
761  * necessarily a separate function.
762  *
763  * rgba outputs straight alpha. */
764 float BKE_brush_sample_tex_2D(const Scene *scene, Brush *brush, const float xy[2], float rgba[4])
765 {
766         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
767         MTex *mtex = &brush->mtex;
768
769         if (mtex && mtex->tex) {
770                 float co[3], tin, tr, tg, tb, ta;
771                 float x = xy[0], y = xy[1];
772                 int hasrgb;
773                 int radius = BKE_brush_size_get(scene, brush);
774                 float rotation = -mtex->rot;
775
776                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
777                         rotation += ups->brush_rotation;
778                         radius = ups->pixel_radius;
779                 }
780                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
781                         rotation += ups->brush_rotation;
782                         /* these contain a random coordinate */
783                         x -= ups->tex_mouse[0];
784                         y -= ups->tex_mouse[1];
785
786                         radius = ups->pixel_radius;
787                 }
788
789                 x /= radius;
790                 y /= radius;
791
792                 if (rotation > 0.001f || rotation < -0.001f) {
793                         const float angle    = atan2f(y, x) + rotation;
794                         const float flen     = sqrtf(x * x + y * y);
795
796                         x = flen * cosf(angle);
797                         y = flen * sinf(angle);
798                 }
799
800                 x *= brush->mtex.size[0];
801                 y *= brush->mtex.size[1];
802
803                 co[0] = x + brush->mtex.ofs[0];
804                 co[1] = y + brush->mtex.ofs[1];
805                 co[2] = 0.0f;
806
807                 hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, 0, NULL);
808
809                 if (hasrgb) {
810                         rgba[0] = tr;
811                         rgba[1] = tg;
812                         rgba[2] = tb;
813                         rgba[3] = ta;
814                 }
815                 else {
816                         rgba[0] = tin;
817                         rgba[1] = tin;
818                         rgba[2] = tin;
819                         rgba[3] = 1.0f;
820                 }
821                 return tin;
822         }
823         else {
824                 rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
825                 return 1.0;
826         }
827 }
828
829 /* TODO, use define for 'texfall' arg
830  * NOTE: only used for 2d brushes currently! */
831 void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize,
832                          ImBuf **outbuf, bool use_color_correction, bool use_brush_alpha)
833 {
834         ImBuf *ibuf;
835         float xy[2], rgba[4], *dstf;
836         int x, y, rowbytes, xoff, yoff, imbflag;
837         const int radius = BKE_brush_size_get(scene, brush);
838         unsigned char *dst, crgb[3];
839         const float alpha = (use_brush_alpha)? BKE_brush_alpha_get(scene, brush): 1.0f;
840         float brush_rgb[3];
841
842         imbflag = (flt) ? IB_rectfloat : IB_rect;
843         xoff = -bufsize / 2.0f + 0.5f;
844         yoff = -bufsize / 2.0f + 0.5f;
845         rowbytes = bufsize * 4;
846
847         if (*outbuf)
848                 ibuf = *outbuf;
849         else
850                 ibuf = IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
851
852         if (flt) {
853                 copy_v3_v3(brush_rgb, brush->rgb);
854                 if (use_color_correction) {
855                         srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
856                 }
857
858                 for (y = 0; y < ibuf->y; y++) {
859                         dstf = ibuf->rect_float + y * rowbytes;
860
861                         for (x = 0; x < ibuf->x; x++, dstf += 4) {
862                                 xy[0] = x + xoff;
863                                 xy[1] = y + yoff;
864
865                                 if (texfall == 0) {
866                                         copy_v3_v3(dstf, brush_rgb);
867                                         dstf[3] = alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
868                                 }
869                                 else if (texfall == 1) {
870                                         BKE_brush_sample_tex_2D(scene, brush, xy, dstf);
871                                 }
872                                 else if (texfall == 2) {
873                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
874                                         mul_v3_v3v3(dstf, rgba, brush_rgb);
875                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
876                                 }
877                                 else {
878                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
879                                         copy_v3_v3(dstf, brush_rgb);
880                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
881                                 }
882
883                                 /* output premultiplied alpha image */
884                                 dstf[0] *= dstf[3];
885                                 dstf[1] *= dstf[3];
886                                 dstf[2] *= dstf[3];
887                         }
888                 }
889         }
890         else {
891                 float alpha_f; /* final float alpha to convert to char */
892                 rgb_float_to_uchar(crgb, brush->rgb);
893
894                 for (y = 0; y < ibuf->y; y++) {
895                         dst = (unsigned char *)ibuf->rect + y * rowbytes;
896
897                         for (x = 0; x < ibuf->x; x++, dst += 4) {
898                                 xy[0] = x + xoff;
899                                 xy[1] = y + yoff;
900
901                                 if (texfall == 0) {
902                                         alpha_f = alpha * BKE_brush_curve_strength(brush, len_v2(xy), radius);
903
904                                         dst[0] = crgb[0];
905                                         dst[1] = crgb[1];
906                                         dst[2] = crgb[2];
907                                         dst[3] = FTOCHAR(alpha_f);
908                                 }
909                                 else if (texfall == 1) {
910                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
911                                         rgba_float_to_uchar(dst, rgba);
912                                 }
913                                 else if (texfall == 2) {
914                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
915                                         mul_v3_v3(rgba, brush->rgb);
916                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
917
918                                         rgb_float_to_uchar(dst, rgba);
919
920                                         dst[3] = FTOCHAR(alpha_f);
921                                 }
922                                 else {
923                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
924                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
925
926                                         dst[0] = crgb[0];
927                                         dst[1] = crgb[1];
928                                         dst[2] = crgb[2];
929                                         dst[3] = FTOCHAR(alpha_f);
930                                 }
931                         }
932                 }
933         }
934
935         *outbuf = ibuf;
936 }
937
938 /* Unified Size and Strength */
939
940 /* XXX: be careful about setting size and unprojected radius
941  * because they depend on one another
942  * these functions do not set the other corresponding value
943  * this can lead to odd behavior if size and unprojected
944  * radius become inconsistent.
945  * the biggest problem is that it isn't possible to change
946  * unprojected radius because a view context is not
947  * available.  my ussual solution to this is to use the
948  * ratio of change of the size to change the unprojected
949  * radius.  Not completely convinced that is correct.
950  * In any case, a better solution is needed to prevent
951  * inconsistency. */
952
953 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
954 {
955         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
956         
957         size = (int)((float)size / U.pixelsize);
958         
959         if (ups->flag & UNIFIED_PAINT_SIZE)
960                 ups->size = size;
961         else
962                 brush->size = size;
963 }
964
965 int BKE_brush_size_get(const Scene *scene, Brush *brush)
966 {
967         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
968         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
969         
970         return (int)((float)size * U.pixelsize);
971 }
972
973 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
974 {
975         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
976
977         return (us_flag & UNIFIED_PAINT_SIZE) ?
978                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
979                (brush->flag & BRUSH_LOCK_SIZE);
980 }
981
982 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
983 {
984         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
985
986         return (us_flag & UNIFIED_PAINT_SIZE) ?
987                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
988                (brush->flag & BRUSH_SIZE_PRESSURE);
989 }
990
991 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
992 {
993         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
994
995         return (us_flag & UNIFIED_PAINT_ALPHA) ?
996                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
997                (brush->flag & BRUSH_ALPHA_PRESSURE);
998 }
999
1000 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
1001 {
1002         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1003
1004         if (ups->flag & UNIFIED_PAINT_SIZE)
1005                 ups->unprojected_radius = unprojected_radius;
1006         else
1007                 brush->unprojected_radius = unprojected_radius;
1008 }
1009
1010 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
1011 {
1012         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1013
1014         return (ups->flag & UNIFIED_PAINT_SIZE) ?
1015                ups->unprojected_radius :
1016                brush->unprojected_radius;
1017 }
1018
1019 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
1020 {
1021         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1022
1023         if (ups->flag & UNIFIED_PAINT_ALPHA)
1024                 ups->alpha = alpha;
1025         else
1026                 brush->alpha = alpha;
1027 }
1028
1029 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
1030 {
1031         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1032
1033         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
1034 }
1035
1036 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
1037 {
1038         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1039
1040         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
1041 }
1042
1043 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
1044 {
1045         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1046
1047         if (ups->flag & UNIFIED_PAINT_WEIGHT)
1048                 ups->weight = value;
1049         else
1050                 brush->weight = value;
1051 }
1052
1053 /* scale unprojected radius to reflect a change in the brush's 2D size */
1054 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
1055                                         int new_brush_size,
1056                                         int old_brush_size)
1057 {
1058         float scale = new_brush_size;
1059         /* avoid division by zero */
1060         if (old_brush_size != 0)
1061                 scale /= (float)old_brush_size;
1062         (*unprojected_radius) *= scale;
1063 }
1064
1065 /* scale brush size to reflect a change in the brush's unprojected radius */
1066 void BKE_brush_scale_size(int *r_brush_size,
1067                           float new_unprojected_radius,
1068                           float old_unprojected_radius)
1069 {
1070         float scale = new_unprojected_radius;
1071         /* avoid division by zero */
1072         if (old_unprojected_radius != 0)
1073                 scale /= new_unprojected_radius;
1074         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
1075 }
1076
1077 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
1078 {
1079         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
1080                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
1081
1082         /* jitter-ed brush gives weird and unpredictable result for this
1083          * kinds of stroke, so manually disable jitter usage (sergey) */
1084         use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH | BRUSH_ANCHORED)) == 0;
1085
1086         if (use_jitter) {
1087                 float rand_pos[2];
1088                 float spread;
1089                 int diameter;
1090
1091                 do {
1092                         rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
1093                         rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
1094                 } while (len_v2(rand_pos) > 0.5f);
1095
1096
1097                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
1098                         diameter = 2 * brush->jitter_absolute;
1099                         spread = 1.0;
1100                 }
1101                 else {
1102                         diameter = 2 * BKE_brush_size_get(scene, brush);
1103                         spread = brush->jitter;
1104                 }
1105                 /* find random position within a circle of diameter 1 */
1106                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
1107                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
1108         }
1109         else {
1110                 copy_v2_v2(jitterpos, pos);
1111         }
1112 }
1113
1114 void BKE_brush_randomize_texture_coordinates(UnifiedPaintSettings *ups, bool mask)
1115 {
1116         /* we multiply with brush radius as an optimization for the brush
1117          * texture sampling functions */
1118         if (mask) {
1119                 ups->mask_tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1120                 ups->mask_tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1121         }
1122         else {
1123                 ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1124                 ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1125         }
1126 }
1127
1128 /* Uses the brush curve control to find a strength value between 0 and 1 */
1129 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
1130 {
1131         if (p >= len) return 0;
1132         else p = p / len;
1133
1134         curvemapping_initialize(br->curve);
1135         p = curvemapping_evaluateF(br->curve, 0, p);
1136
1137         if (p < 0.0f) p = 0.0f;
1138         else if (p > 1.0f) p = 1.0f;
1139         return p;
1140 }
1141 /* same as above but can return negative values if the curve enables
1142  * used for sculpt only */
1143 float BKE_brush_curve_strength(Brush *br, float p, const float len)
1144 {
1145         if (p >= len)
1146                 p = 1.0f;
1147         else
1148                 p = p / len;
1149
1150         curvemapping_initialize(br->curve);
1151         return curvemapping_evaluateF(br->curve, 0, p);
1152 }
1153
1154 /* TODO: should probably be unified with BrushPainter stuff? */
1155 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
1156 {
1157         unsigned int *texcache = NULL;
1158         MTex *mtex = &br->mtex;
1159         TexResult texres = {0};
1160         int hasrgb, ix, iy;
1161         int side = half_side * 2;
1162
1163         if (mtex->tex) {
1164                 float x, y, step = 2.0 / side, co[3];
1165
1166                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1167
1168                 /* do normalized cannonical view coords for texture */
1169                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
1170                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
1171                                 co[0] = x;
1172                                 co[1] = y;
1173                                 co[2] = 0.0f;
1174
1175                                 /* This is copied from displace modifier code */
1176                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
1177
1178                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1179                                  * intensity, so calculate one (formula from do_material_tex).
1180                                  * if the texture didn't give an RGB value, copy the intensity across
1181                                  */
1182                                 if (hasrgb & TEX_RGB)
1183                                         texres.tin = rgb_to_grayscale(&texres.tr);
1184
1185                                 ((char *)texcache)[(iy * side + ix) * 4] =
1186                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
1187                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
1188                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
1189                         }
1190                 }
1191         }
1192
1193         return texcache;
1194 }
1195
1196
1197 /**** Radial Control ****/
1198 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
1199 {
1200         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1201         unsigned int *texcache;
1202         int side = 128;
1203         int half = side / 2;
1204         int i, j;
1205
1206         texcache = BKE_brush_gen_texture_cache(br, half);
1207         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1208         im->x = im->y = side;
1209
1210         for (i = 0; i < side; ++i) {
1211                 for (j = 0; j < side; ++j) {
1212                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1213                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1214                 }
1215         }
1216
1217         /* Modulate curve with texture */
1218         if (texcache) {
1219                 for (i = 0; i < side; ++i) {
1220                         for (j = 0; j < side; ++j) {
1221                                 const int col = texcache[i * side + j];
1222                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1223                         }
1224                 }
1225
1226                 MEM_freeN(texcache);
1227         }
1228
1229         return im;
1230 }