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