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