Fix some names, and move overlay flag to overlay_flags.
[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_OVERRIDE_ON_STROKE);
324
325         BR_TEST(jitter, f);
326         BR_TEST(spacing, d);
327         BR_TEST(smooth_stroke_radius, d);
328         BR_TEST(smooth_stroke_factor, f);
329         BR_TEST(rate, f);
330
331         BR_TEST(alpha, f);
332
333         BR_TEST(sculpt_plane, d);
334
335         BR_TEST(plane_offset, f);
336
337         BR_TEST(autosmooth_factor, f);
338
339         BR_TEST(crease_pinch_factor, f);
340
341         BR_TEST(plane_trim, f);
342
343         BR_TEST(texture_sample_bias, f);
344         BR_TEST(texture_overlay_alpha, d);
345
346         BR_TEST(add_col[0], f);
347         BR_TEST(add_col[1], f);
348         BR_TEST(add_col[2], f);
349         BR_TEST(sub_col[0], f);
350         BR_TEST(sub_col[1], f);
351         BR_TEST(sub_col[2], f);
352
353         printf("\n");
354         
355 #undef BR_TEST
356 #undef BR_TEST_FLAG
357 }
358
359 void BKE_brush_sculpt_reset(Brush *br)
360 {
361         /* enable this to see any non-default
362          * settings used by a brush: */
363         // BKE_brush_debug_print_state(br);
364
365         brush_defaults(br);
366         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
367
368         switch (br->sculpt_tool) {
369                 case SCULPT_TOOL_CLAY:
370                         br->flag |= BRUSH_FRONTFACE;
371                         break;
372                 case SCULPT_TOOL_CREASE:
373                         br->flag |= BRUSH_DIR_IN;
374                         br->alpha = 0.25;
375                         break;
376                 case SCULPT_TOOL_FILL:
377                         br->add_col[1] = 1;
378                         br->sub_col[0] = 0.25;
379                         br->sub_col[1] = 1;
380                         break;
381                 case SCULPT_TOOL_FLATTEN:
382                         br->add_col[1] = 1;
383                         br->sub_col[0] = 0.25;
384                         br->sub_col[1] = 1;
385                         break;
386                 case SCULPT_TOOL_INFLATE:
387                         br->add_col[0] = 0.750000;
388                         br->add_col[1] = 0.750000;
389                         br->add_col[2] = 0.750000;
390                         br->sub_col[0] = 0.250000;
391                         br->sub_col[1] = 0.250000;
392                         br->sub_col[2] = 0.250000;
393                         break;
394                 case SCULPT_TOOL_NUDGE:
395                         br->add_col[0] = 0.250000;
396                         br->add_col[1] = 1.000000;
397                         br->add_col[2] = 0.250000;
398                         break;
399                 case SCULPT_TOOL_PINCH:
400                         br->add_col[0] = 0.750000;
401                         br->add_col[1] = 0.750000;
402                         br->add_col[2] = 0.750000;
403                         br->sub_col[0] = 0.250000;
404                         br->sub_col[1] = 0.250000;
405                         br->sub_col[2] = 0.250000;
406                         break;
407                 case SCULPT_TOOL_SCRAPE:
408                         br->add_col[1] = 1.000000;
409                         br->sub_col[0] = 0.250000;
410                         br->sub_col[1] = 1.000000;
411                         break;
412                 case SCULPT_TOOL_ROTATE:
413                         br->alpha = 1.0;
414                         break;
415                 case SCULPT_TOOL_SMOOTH:
416                         br->flag &= ~BRUSH_SPACE_ATTEN;
417                         br->spacing = 5;
418                         br->add_col[0] = 0.750000;
419                         br->add_col[1] = 0.750000;
420                         br->add_col[2] = 0.750000;
421                         break;
422                 case SCULPT_TOOL_GRAB:
423                 case SCULPT_TOOL_SNAKE_HOOK:
424                 case SCULPT_TOOL_THUMB:
425                         br->size = 75;
426                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
427                         br->flag &= ~BRUSH_SPACE;
428                         br->flag &= ~BRUSH_SPACE_ATTEN;
429                         br->add_col[0] = 0.250000;
430                         br->add_col[1] = 1.000000;
431                         br->add_col[2] = 0.250000;
432                         break;
433                 default:
434                         break;
435         }
436 }
437
438 /**
439  * Library Operations
440  * \param preset  CurveMappingPreset
441  */
442 void BKE_brush_curve_preset(Brush *b, int preset)
443 {
444         CurveMap *cm = NULL;
445
446         if (!b->curve)
447                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
448
449         cm = b->curve->cm;
450         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
451
452         b->curve->preset = preset;
453         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
454         curvemapping_changed(b->curve, FALSE);
455 }
456
457 int BKE_brush_texture_set_nr(Brush *brush, int nr)
458 {
459         ID *idtest, *id = NULL;
460
461         id = (ID *)brush->mtex.tex;
462
463         idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
464         if (idtest == NULL) { /* new tex */
465                 if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
466                 else idtest = (ID *)add_texture(G.main, "Tex");
467                 idtest->us--;
468         }
469         if (idtest != id) {
470                 BKE_brush_texture_delete(brush);
471
472                 brush->mtex.tex = (Tex *)idtest;
473                 id_us_plus(idtest);
474
475                 return 1;
476         }
477
478         return 0;
479 }
480
481 int BKE_brush_texture_delete(Brush *brush)
482 {
483         if (brush->mtex.tex)
484                 brush->mtex.tex->id.us--;
485
486         return 1;
487 }
488
489 int BKE_brush_clone_image_set_nr(Brush *brush, int nr)
490 {
491         if (brush && nr > 0) {
492                 Image *ima = (Image *)BLI_findlink(&G.main->image, nr - 1);
493
494                 if (ima) {
495                         BKE_brush_clone_image_delete(brush);
496                         brush->clone.image = ima;
497                         id_us_plus(&ima->id);
498                         brush->clone.offset[0] = brush->clone.offset[1] = 0.0f;
499
500                         return 1;
501                 }
502         }
503
504         return 0;
505 }
506
507 int BKE_brush_clone_image_delete(Brush *brush)
508 {
509         if (brush && brush->clone.image) {
510                 brush->clone.image->id.us--;
511                 brush->clone.image = NULL;
512                 return 1;
513         }
514
515         return 0;
516 }
517
518 /* Generic texture sampler for 3D painting systems. point has to be either in
519  * region space mouse coordinates, or 3d world coordinates for 3D mapping */
520 float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
521                               const float point[3],
522                               float rgba[4], const int thread,
523                               struct ImagePool *pool)
524 {
525         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
526         MTex *mtex = &br->mtex;
527         float intensity = 1.0;
528         bool hasrgb = false;
529
530         if (!mtex->tex) {
531                 intensity = 1;
532         }
533         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
534                 /* Get strength by feeding the vertex
535                  * location directly into a texture */
536                 hasrgb = externtex(mtex, point, &intensity,
537                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
538         }
539         else if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
540                 float rotation = -mtex->rot;
541                 float point_2d[2] = {point[0], point[1]};
542                 float x = 0.0f, y = 0.0f; /* Quite warnings */
543                 float co[3];
544
545                 x = point_2d[0] - br->stencil_pos[0];
546                 y = point_2d[1] - br->stencil_pos[1];
547
548                 if (rotation > 0.001f || rotation < -0.001f) {
549                         const float angle    = atan2f(y, x) + rotation;
550                         const float flen     = sqrtf(x * x + y * y);
551
552                         x = flen * cosf(angle);
553                         y = flen * sinf(angle);
554                 }
555
556                 if (fabsf(x) > br->stencil_dimension[0] || fabsf(y) > br->stencil_dimension[1]) {
557                         zero_v4(rgba);
558                         return 0.0f;
559                 }
560                 x /= (br->stencil_dimension[0]);
561                 y /= (br->stencil_dimension[1]);
562
563                 x *= br->mtex.size[0];
564                 y *= br->mtex.size[1];
565
566                 co[0] = x + br->mtex.ofs[0];
567                 co[1] = y + br->mtex.ofs[1];
568                 co[2] = 0.0f;
569
570                 hasrgb = externtex(mtex, co, &intensity,
571                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
572         }
573         else {
574                 float rotation = -mtex->rot;
575                 float point_2d[2] = {point[0], point[1]};
576                 float x = 0.0f, y = 0.0f; /* Quite warnings */
577                 float invradius = 1.0f; /* Quite warnings */
578                 float co[3];
579
580                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
581                         /* keep coordinates relative to mouse */
582
583                         rotation += ups->brush_rotation;
584
585                         x = point_2d[0] - ups->tex_mouse[0];
586                         y = point_2d[1] - ups->tex_mouse[1];
587
588                         /* use pressure adjusted size for fixed mode */
589                         invradius = 1.0f / ups->pixel_radius;
590                 }
591                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
592                         /* leave the coordinates relative to the screen */
593
594                         /* use unadjusted size for tiled mode */
595                         invradius = 1.0f / BKE_brush_size_get(scene, br);
596
597                         x = point_2d[0];
598                         y = point_2d[1];
599                 }
600                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
601                         rotation += ups->brush_rotation;
602                         /* these contain a random coordinate */
603                         x = point_2d[0] - ups->tex_mouse[0];
604                         y = point_2d[1] - ups->tex_mouse[1];
605
606                         invradius = 1.0f / ups->pixel_radius;
607                 }
608
609                 x *= invradius;
610                 y *= invradius;
611
612                 /* it is probably worth optimizing for those cases where
613                  * the texture is not rotated by skipping the calls to
614                  * atan2, sqrtf, sin, and cos. */
615                 if (rotation > 0.001f || rotation < -0.001f) {
616                         const float angle    = atan2f(y, x) + rotation;
617                         const float flen     = sqrtf(x * x + y * y);
618
619                         x = flen * cosf(angle);
620                         y = flen * sinf(angle);
621                 }
622
623                 x *= br->mtex.size[0];
624                 y *= br->mtex.size[1];
625
626                 co[0] = x + br->mtex.ofs[0];
627                 co[1] = y + br->mtex.ofs[1];
628                 co[2] = 0.0f;
629
630                 hasrgb = externtex(mtex, co, &intensity,
631                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
632         }
633
634         intensity += br->texture_sample_bias;
635
636         if (!hasrgb) {
637                 rgba[0] = intensity;
638                 rgba[1] = intensity;
639                 rgba[2] = intensity;
640                 rgba[3] = 1.0f;
641         }
642
643         return intensity;
644 }
645
646 float BKE_brush_sample_masktex(const Scene *scene, Brush *br,
647                                const float point[3],
648                                const int thread,
649                                struct ImagePool *pool)
650 {
651         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
652         MTex *mtex = &br->mask_mtex;
653
654         if (mtex && mtex->tex) {
655                 float rotation = -mtex->rot;
656                 float point_2d[2] = {point[0], point[1]};
657                 float x = 0.0f, y = 0.0f; /* Quite warnings */
658                 float radius = 1.0f; /* Quite warnings */
659                 float co[3];
660                 float rgba[4], intensity = 1.0;
661
662                 point_2d[0] -= ups->tex_mouse[0];
663                 point_2d[1] -= ups->tex_mouse[1];
664
665                 /* use pressure adjusted size for fixed mode */
666                 radius = ups->pixel_radius;
667
668                 x = point_2d[0];
669                 y = point_2d[1];
670
671                 x /= radius;
672                 y /= radius;
673
674                 /* it is probably worth optimizing for those cases where
675                  * the texture is not rotated by skipping the calls to
676                  * atan2, sqrtf, sin, and cos. */
677                 if (rotation > 0.001f || rotation < -0.001f) {
678                         const float angle    = atan2f(y, x) + rotation;
679                         const float flen     = sqrtf(x * x + y * y);
680
681                         x = flen * cosf(angle);
682                         y = flen * sinf(angle);
683                 }
684
685                 x *= br->mask_mtex.size[0];
686                 y *= br->mask_mtex.size[1];
687
688                 co[0] = x + br->mask_mtex.ofs[0];
689                 co[1] = y + br->mask_mtex.ofs[1];
690                 co[2] = 0.0f;
691
692                 externtex(mtex, co, &intensity,
693                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
694
695                 return intensity;
696         }
697         else {
698                 return 1.0f;
699         }
700 }
701
702 /* Brush Sampling for 2D brushes. when we unify the brush systems this will be necessarily a separate function */
703 float BKE_brush_sample_tex_2D(const Scene *scene, Brush *brush, const float xy[2], float rgba[4])
704 {
705         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
706         MTex *mtex = &brush->mtex;
707
708         if (mtex && mtex->tex) {
709                 float co[3], tin, tr, tg, tb, ta;
710                 float x = xy[0], y = xy[1];
711                 int hasrgb;
712                 int radius = BKE_brush_size_get(scene, brush);
713                 float rotation = -mtex->rot;
714
715                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
716                         rotation += ups->brush_rotation;
717                         radius = ups->pixel_radius;
718                 }
719                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
720                         rotation += ups->brush_rotation;
721                         /* these contain a random coordinate */
722                         x -= ups->tex_mouse[0];
723                         y -= ups->tex_mouse[1];
724
725                         radius = ups->pixel_radius;
726                 }
727
728                 x /= radius;
729                 y /= radius;
730
731                 if (rotation > 0.001f || rotation < -0.001f) {
732                         const float angle    = atan2f(y, x) + rotation;
733                         const float flen     = sqrtf(x * x + y * y);
734
735                         x = flen * cosf(angle);
736                         y = flen * sinf(angle);
737                 }
738
739                 x *= brush->mtex.size[0];
740                 y *= brush->mtex.size[1];
741
742                 co[0] = x + brush->mtex.ofs[0];
743                 co[1] = y + brush->mtex.ofs[1];
744                 co[2] = 0.0f;
745
746                 hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, 0, NULL);
747
748                 if (hasrgb) {
749                         rgba[0] = tr;
750                         rgba[1] = tg;
751                         rgba[2] = tb;
752                         rgba[3] = ta;
753                 }
754                 else {
755                         rgba[0] = tin;
756                         rgba[1] = tin;
757                         rgba[2] = tin;
758                         rgba[3] = 1.0f;
759                 }
760                 return tin;
761         }
762         else {
763                 rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
764                 return 1.0;
765         }
766 }
767
768 /* TODO, use define for 'texfall' arg
769  * NOTE: only used for 2d brushes currently! */
770 void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize, ImBuf **outbuf, int use_color_correction)
771 {
772         ImBuf *ibuf;
773         float xy[2], rgba[4], *dstf;
774         int x, y, rowbytes, xoff, yoff, imbflag;
775         const int radius = BKE_brush_size_get(scene, brush);
776         unsigned char *dst, crgb[3];
777         const float alpha = BKE_brush_alpha_get(scene, brush);
778         float brush_rgb[3];
779
780         imbflag = (flt) ? IB_rectfloat : IB_rect;
781         xoff = -bufsize / 2.0f + 0.5f;
782         yoff = -bufsize / 2.0f + 0.5f;
783         rowbytes = bufsize * 4;
784
785         if (*outbuf)
786                 ibuf = *outbuf;
787         else
788                 ibuf = IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
789
790         if (flt) {
791                 copy_v3_v3(brush_rgb, brush->rgb);
792                 if (use_color_correction) {
793                         srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
794                 }
795
796                 for (y = 0; y < ibuf->y; y++) {
797                         dstf = ibuf->rect_float + y * rowbytes;
798
799                         for (x = 0; x < ibuf->x; x++, dstf += 4) {
800                                 xy[0] = x + xoff;
801                                 xy[1] = y + yoff;
802
803                                 if (texfall == 0) {
804                                         copy_v3_v3(dstf, brush_rgb);
805                                         dstf[3] = alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
806                                 }
807                                 else if (texfall == 1) {
808                                         BKE_brush_sample_tex_2D(scene, brush, xy, dstf);
809                                 }
810                                 else if (texfall == 2) {
811                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
812                                         mul_v3_v3v3(dstf, rgba, brush_rgb);
813                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
814                                 }
815                                 else {
816                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
817                                         copy_v3_v3(dstf, brush_rgb);
818                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
819                                 }
820                         }
821                 }
822         }
823         else {
824                 float alpha_f; /* final float alpha to convert to char */
825                 rgb_float_to_uchar(crgb, brush->rgb);
826
827                 for (y = 0; y < ibuf->y; y++) {
828                         dst = (unsigned char *)ibuf->rect + y * rowbytes;
829
830                         for (x = 0; x < ibuf->x; x++, dst += 4) {
831                                 xy[0] = x + xoff;
832                                 xy[1] = y + yoff;
833
834                                 if (texfall == 0) {
835                                         alpha_f = alpha * BKE_brush_curve_strength(brush, len_v2(xy), radius);
836
837                                         dst[0] = crgb[0];
838                                         dst[1] = crgb[1];
839                                         dst[2] = crgb[2];
840                                         dst[3] = FTOCHAR(alpha_f);
841                                 }
842                                 else if (texfall == 1) {
843                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
844                                         rgba_float_to_uchar(dst, rgba);
845                                 }
846                                 else if (texfall == 2) {
847                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
848                                         mul_v3_v3(rgba, brush->rgb);
849                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
850
851                                         rgb_float_to_uchar(dst, rgba);
852
853                                         dst[3] = FTOCHAR(alpha_f);
854                                 }
855                                 else {
856                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
857                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
858
859                                         dst[0] = crgb[0];
860                                         dst[1] = crgb[1];
861                                         dst[2] = crgb[2];
862                                         dst[3] = FTOCHAR(alpha_f);
863                                 }
864                         }
865                 }
866         }
867
868         *outbuf = ibuf;
869 }
870
871 /* Unified Size and Strength */
872
873 /* XXX: be careful about setting size and unprojected radius
874  * because they depend on one another
875  * these functions do not set the other corresponding value
876  * this can lead to odd behavior if size and unprojected
877  * radius become inconsistent.
878  * the biggest problem is that it isn't possible to change
879  * unprojected radius because a view context is not
880  * available.  my ussual solution to this is to use the
881  * ratio of change of the size to change the unprojected
882  * radius.  Not completely convinced that is correct.
883  * In any case, a better solution is needed to prevent
884  * inconsistency. */
885
886 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
887 {
888         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
889         
890         size = (int)((float)size / U.pixelsize);
891         
892         if (ups->flag & UNIFIED_PAINT_SIZE)
893                 ups->size = size;
894         else
895                 brush->size = size;
896 }
897
898 int BKE_brush_size_get(const Scene *scene, Brush *brush)
899 {
900         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
901         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
902         
903         return (int)((float)size * U.pixelsize);
904 }
905
906 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
907 {
908         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
909
910         return (us_flag & UNIFIED_PAINT_SIZE) ?
911                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
912                (brush->flag & BRUSH_LOCK_SIZE);
913 }
914
915 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
916 {
917         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
918
919         return (us_flag & UNIFIED_PAINT_SIZE) ?
920                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
921                (brush->flag & BRUSH_SIZE_PRESSURE);
922 }
923
924 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
925 {
926         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
927
928         return (us_flag & UNIFIED_PAINT_ALPHA) ?
929                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
930                (brush->flag & BRUSH_ALPHA_PRESSURE);
931 }
932
933 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
934 {
935         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
936
937         if (ups->flag & UNIFIED_PAINT_SIZE)
938                 ups->unprojected_radius = unprojected_radius;
939         else
940                 brush->unprojected_radius = unprojected_radius;
941 }
942
943 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
944 {
945         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
946
947         return (ups->flag & UNIFIED_PAINT_SIZE) ?
948                ups->unprojected_radius :
949                brush->unprojected_radius;
950 }
951
952 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
953 {
954         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
955
956         if (ups->flag & UNIFIED_PAINT_ALPHA)
957                 ups->alpha = alpha;
958         else
959                 brush->alpha = alpha;
960 }
961
962 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
963 {
964         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
965
966         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
967 }
968
969 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
970 {
971         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
972
973         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
974 }
975
976 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
977 {
978         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
979
980         if (ups->flag & UNIFIED_PAINT_WEIGHT)
981                 ups->weight = value;
982         else
983                 brush->weight = value;
984 }
985
986 /* scale unprojected radius to reflect a change in the brush's 2D size */
987 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
988                                         int new_brush_size,
989                                         int old_brush_size)
990 {
991         float scale = new_brush_size;
992         /* avoid division by zero */
993         if (old_brush_size != 0)
994                 scale /= (float)old_brush_size;
995         (*unprojected_radius) *= scale;
996 }
997
998 /* scale brush size to reflect a change in the brush's unprojected radius */
999 void BKE_brush_scale_size(int *r_brush_size,
1000                           float new_unprojected_radius,
1001                           float old_unprojected_radius)
1002 {
1003         float scale = new_unprojected_radius;
1004         /* avoid division by zero */
1005         if (old_unprojected_radius != 0)
1006                 scale /= new_unprojected_radius;
1007         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
1008 }
1009
1010 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
1011 {
1012         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
1013                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
1014
1015         /* jitter-ed brush gives weird and unpredictable result for this
1016          * kinds of stroke, so manually disable jitter usage (sergey) */
1017         use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH | BRUSH_ANCHORED)) == 0;
1018
1019         if (use_jitter) {
1020                 float rand_pos[2];
1021                 float spread;
1022                 int diameter;
1023
1024                 do {
1025                         rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
1026                         rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
1027                 } while (len_v2(rand_pos) > 0.5f);
1028
1029
1030                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
1031                         diameter = 2 * brush->jitter_absolute;
1032                         spread = 1.0;
1033                 }
1034                 else {
1035                         diameter = 2 * BKE_brush_size_get(scene, brush);
1036                         spread = brush->jitter;
1037                 }
1038                 /* find random position within a circle of diameter 1 */
1039                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
1040                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
1041         }
1042         else {
1043                 copy_v2_v2(jitterpos, pos);
1044         }
1045 }
1046
1047 void BKE_brush_randomize_texture_coordinates(UnifiedPaintSettings *ups)
1048 {
1049         /* we multiply with brush radius as an optimization for the brush
1050          * texture sampling functions */
1051         ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1052         ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1053 }
1054
1055 /* Uses the brush curve control to find a strength value between 0 and 1 */
1056 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
1057 {
1058         if (p >= len) return 0;
1059         else p = p / len;
1060
1061         curvemapping_initialize(br->curve);
1062         p = curvemapping_evaluateF(br->curve, 0, p);
1063
1064         if (p < 0.0f) p = 0.0f;
1065         else if (p > 1.0f) p = 1.0f;
1066         return p;
1067 }
1068 /* same as above but can return negative values if the curve enables
1069  * used for sculpt only */
1070 float BKE_brush_curve_strength(Brush *br, float p, const float len)
1071 {
1072         if (p >= len)
1073                 p = 1.0f;
1074         else
1075                 p = p / len;
1076
1077         curvemapping_initialize(br->curve);
1078         return curvemapping_evaluateF(br->curve, 0, p);
1079 }
1080
1081 /* TODO: should probably be unified with BrushPainter stuff? */
1082 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
1083 {
1084         unsigned int *texcache = NULL;
1085         MTex *mtex = &br->mtex;
1086         TexResult texres = {0};
1087         int hasrgb, ix, iy;
1088         int side = half_side * 2;
1089
1090         if (mtex->tex) {
1091                 float x, y, step = 2.0 / side, co[3];
1092
1093                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1094
1095                 /* do normalized cannonical view coords for texture */
1096                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
1097                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
1098                                 co[0] = x;
1099                                 co[1] = y;
1100                                 co[2] = 0.0f;
1101
1102                                 /* This is copied from displace modifier code */
1103                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
1104
1105                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1106                                  * intensity, so calculate one (formula from do_material_tex).
1107                                  * if the texture didn't give an RGB value, copy the intensity across
1108                                  */
1109                                 if (hasrgb & TEX_RGB)
1110                                         texres.tin = rgb_to_grayscale(&texres.tr);
1111
1112                                 ((char *)texcache)[(iy * side + ix) * 4] =
1113                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
1114                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
1115                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
1116                         }
1117                 }
1118         }
1119
1120         return texcache;
1121 }
1122
1123
1124 /**** Radial Control ****/
1125 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
1126 {
1127         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1128         unsigned int *texcache;
1129         int side = 128;
1130         int half = side / 2;
1131         int i, j;
1132
1133         texcache = BKE_brush_gen_texture_cache(br, half);
1134         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1135         im->x = im->y = side;
1136
1137         for (i = 0; i < side; ++i) {
1138                 for (j = 0; j < side; ++j) {
1139                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1140                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1141                 }
1142         }
1143
1144         /* Modulate curve with texture */
1145         if (texcache) {
1146                 for (i = 0; i < side; ++i) {
1147                         for (j = 0; j < side; ++j) {
1148                                 const int col = texcache[i * side + j];
1149                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1150                         }
1151                 }
1152
1153                 MEM_freeN(texcache);
1154         }
1155
1156         return im;
1157 }