style cleanup / comment formatting for bli/bke/bmesh
[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
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_brush_types.h"
39 #include "DNA_color_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_windowmanager_types.h"
43
44 #include "WM_types.h"
45
46 #include "RNA_access.h"
47
48 #include "BLI_bpath.h"
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_rand.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_brush.h"
55 #include "BKE_colortools.h"
56 #include "BKE_global.h"
57 #include "BKE_image.h"
58 #include "BKE_library.h"
59 #include "BKE_main.h"
60 #include "BKE_paint.h"
61 #include "BKE_texture.h"
62 #include "BKE_icons.h"
63
64 #include "IMB_imbuf.h"
65 #include "IMB_imbuf_types.h"
66
67 #include "RE_render_ext.h" /* externtex */
68 #include "RE_shader_ext.h"
69
70 static void brush_set_defaults(Brush *brush)
71 {
72         brush->blend = 0;
73         brush->flag = 0;
74
75         brush->ob_mode = OB_MODE_ALL_PAINT;
76
77         /* BRUSH SCULPT TOOL SETTINGS */
78         brush->size= 35; /* radius of the brush in pixels */
79         brush->alpha= 0.5f; /* brush strength/intensity probably variable should be renamed? */
80         brush->autosmooth_factor= 0.0f;
81         brush->crease_pinch_factor= 0.5f;
82         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
83         brush->plane_offset= 0.0f; /* how far above or below the plane that is found by averaging the faces */
84         brush->plane_trim= 0.5f;
85         brush->clone.alpha= 0.5f;
86         brush->normal_weight= 0.0f;
87         brush->flag |= BRUSH_ALPHA_PRESSURE;
88
89         /* BRUSH PAINT TOOL SETTINGS */
90         brush->rgb[0]= 1.0f; /* default rgb color of the brush when painting - white */
91         brush->rgb[1]= 1.0f;
92         brush->rgb[2]= 1.0f;
93
94         /* BRUSH STROKE SETTINGS */
95         brush->flag |= (BRUSH_SPACE|BRUSH_SPACE_ATTEN);
96         brush->spacing= 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
97
98         brush->smooth_stroke_radius= 75;
99         brush->smooth_stroke_factor= 0.9f;
100
101         brush->rate= 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
102
103         brush->jitter= 0.0f;
104
105         /* BRUSH TEXTURE SETTINGS */
106         default_mtex(&brush->mtex);
107
108         brush->texture_sample_bias= 0; /* value to added to texture samples */
109         brush->texture_overlay_alpha= 33;
110
111         /* brush appearance  */
112
113         brush->add_col[0]= 1.00; /* add mode color is light red */
114         brush->add_col[1]= 0.39;
115         brush->add_col[2]= 0.39;
116
117         brush->sub_col[0]= 0.39; /* subtract mode color is light blue */
118         brush->sub_col[1]= 0.39;
119         brush->sub_col[2]= 1.00;
120 }
121
122 /* Datablock add/copy/free/make_local */
123
124 Brush *add_brush(const char *name)
125 {
126         Brush *brush;
127
128         brush= alloc_libblock(&G.main->brush, ID_BR, name);
129
130         /* enable fake user by default */
131         brush->id.flag |= LIB_FAKEUSER;
132
133         brush_set_defaults(brush);
134
135         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
136
137          /* the default alpha falloff curve */
138         brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
139
140         return brush;
141 }
142
143 Brush *copy_brush(Brush *brush)
144 {
145         Brush *brushn;
146         
147         brushn= copy_libblock(&brush->id);
148
149         if (brush->mtex.tex)
150                 id_us_plus((ID*)brush->mtex.tex);
151
152         if (brush->icon_imbuf)
153                 brushn->icon_imbuf= IMB_dupImBuf(brush->icon_imbuf);
154
155         brushn->preview = NULL;
156
157         brushn->curve= curvemapping_copy(brush->curve);
158
159         /* enable fake user by default */
160         if (!(brushn->id.flag & LIB_FAKEUSER)) {
161                 brushn->id.flag |= LIB_FAKEUSER;
162                 brushn->id.us++;
163         }
164         
165         return brushn;
166 }
167
168 /* not brush itself */
169 void free_brush(Brush *brush)
170 {
171         if (brush->mtex.tex)
172                 brush->mtex.tex->id.us--;
173
174         if (brush->icon_imbuf)
175                 IMB_freeImBuf(brush->icon_imbuf);
176
177         BKE_previewimg_free(&(brush->preview));
178
179         curvemapping_free(brush->curve);
180 }
181
182 static void extern_local_brush(Brush *brush)
183 {
184         id_lib_extern((ID *)brush->mtex.tex);
185         id_lib_extern((ID *)brush->clone.image);
186 }
187
188 void make_local_brush(Brush *brush)
189 {
190
191         /* - only lib users: do nothing
192          * - only local users: set flag
193          * - mixed: make copy
194          */
195
196         Main *bmain= G.main;
197         Scene *scene;
198         int is_local= FALSE, is_lib= FALSE;
199
200         if(brush->id.lib==NULL) return;
201
202         if(brush->clone.image) {
203                 /* special case: ima always local immediately. Clone image should only
204                  * have one user anyway. */
205                 id_clear_lib_data(bmain, &brush->clone.image->id);
206                 extern_local_brush(brush);
207         }
208
209         for(scene= bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene=scene->id.next) {
210                 if(paint_brush(&scene->toolsettings->imapaint.paint)==brush) {
211                         if(scene->id.lib) is_lib= TRUE;
212                         else is_local= TRUE;
213                 }
214         }
215
216         if(is_local && is_lib == FALSE) {
217                 id_clear_lib_data(bmain, &brush->id);
218                 extern_local_brush(brush);
219
220                 /* enable fake user by default */
221                 if (!(brush->id.flag & LIB_FAKEUSER)) {
222                         brush->id.flag |= LIB_FAKEUSER;
223                         brush->id.us++;
224                 }
225         }
226         else if(is_local && is_lib) {
227                 Brush *brush_new= copy_brush(brush);
228                 brush_new->id.us= 1; /* only keep fake user */
229                 brush_new->id.flag |= LIB_FAKEUSER;
230
231                 /* Remap paths of new ID using old library as base. */
232                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
233                 
234                 for(scene= bmain->scene.first; scene; scene=scene->id.next) {
235                         if(paint_brush(&scene->toolsettings->imapaint.paint)==brush) {
236                                 if(scene->id.lib==NULL) {
237                                         paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
238                                 }
239                         }
240                 }
241         }
242 }
243
244 void brush_debug_print_state(Brush *br)
245 {
246         /* create a fake brush and set it to the defaults */
247         Brush def= {{NULL}};
248         brush_set_defaults(&def);
249         
250 #define BR_TEST(field, t)                                       \
251         if(br->field != def.field)                              \
252                 printf("br->" #field " = %" #t ";\n", br->field)
253
254 #define BR_TEST_FLAG(_f)                                \
255         if((br->flag & _f) && !(def.flag & _f))         \
256                 printf("br->flag |= " #_f ";\n");       \
257         else if(!(br->flag & _f) && (def.flag & _f))    \
258                 printf("br->flag &= ~" #_f ";\n")
259         
260
261         /* print out any non-default brush state */
262         BR_TEST(normal_weight, f);
263
264         BR_TEST(blend, d);
265         BR_TEST(size, d);
266
267         /* br->flag */
268         BR_TEST_FLAG(BRUSH_AIRBRUSH);
269         BR_TEST_FLAG(BRUSH_TORUS);
270         BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
271         BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
272         BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
273         BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
274         BR_TEST_FLAG(BRUSH_FIXED_TEX);
275         BR_TEST_FLAG(BRUSH_RAKE);
276         BR_TEST_FLAG(BRUSH_ANCHORED);
277         BR_TEST_FLAG(BRUSH_DIR_IN);
278         BR_TEST_FLAG(BRUSH_SPACE);
279         BR_TEST_FLAG(BRUSH_SMOOTH_STROKE);
280         BR_TEST_FLAG(BRUSH_PERSISTENT);
281         BR_TEST_FLAG(BRUSH_ACCUMULATE);
282         BR_TEST_FLAG(BRUSH_LOCK_ALPHA);
283         BR_TEST_FLAG(BRUSH_ORIGINAL_NORMAL);
284         BR_TEST_FLAG(BRUSH_OFFSET_PRESSURE);
285         BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
286         BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
287         BR_TEST_FLAG(BRUSH_LOCK_SIZE);
288         BR_TEST_FLAG(BRUSH_TEXTURE_OVERLAY);
289         BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
290         BR_TEST_FLAG(BRUSH_RESTORE_MESH);
291         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
292         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
293         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
294         BR_TEST_FLAG(BRUSH_FRONTFACE);
295         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
296
297         BR_TEST(jitter, f);
298         BR_TEST(spacing, d);
299         BR_TEST(smooth_stroke_radius, d);
300         BR_TEST(smooth_stroke_factor, f);
301         BR_TEST(rate, f);
302
303         BR_TEST(alpha, f);
304
305         BR_TEST(sculpt_plane, d);
306
307         BR_TEST(plane_offset, f);
308
309         BR_TEST(autosmooth_factor, f);
310
311         BR_TEST(crease_pinch_factor, f);
312
313         BR_TEST(plane_trim, f);
314
315         BR_TEST(texture_sample_bias, f);
316         BR_TEST(texture_overlay_alpha, d);
317
318         BR_TEST(add_col[0], f);
319         BR_TEST(add_col[1], f);
320         BR_TEST(add_col[2], f);
321         BR_TEST(sub_col[0], f);
322         BR_TEST(sub_col[1], f);
323         BR_TEST(sub_col[2], f);
324
325         printf("\n");
326         
327 #undef BR_TEST
328 #undef BR_TEST_FLAG
329 }
330
331 void brush_reset_sculpt(Brush *br)
332 {
333         /* enable this to see any non-default
334          * settings used by a brush: */
335         // brush_debug_print_state(br);
336
337         brush_set_defaults(br);
338         brush_curve_preset(br, CURVE_PRESET_SMOOTH);
339
340         switch(br->sculpt_tool) {
341         case SCULPT_TOOL_CLAY:
342                 br->flag |= BRUSH_FRONTFACE;
343                 break;
344         case SCULPT_TOOL_CREASE:
345                 br->flag |= BRUSH_DIR_IN;
346                 br->alpha = 0.25;
347                 break;
348         case SCULPT_TOOL_FILL:
349                 br->add_col[1] = 1;
350                 br->sub_col[0] = 0.25;
351                 br->sub_col[1] = 1;
352                 break;
353         case SCULPT_TOOL_FLATTEN:
354                 br->add_col[1] = 1;
355                 br->sub_col[0] = 0.25;
356                 br->sub_col[1] = 1;
357                 break;
358         case SCULPT_TOOL_INFLATE:
359                 br->add_col[0] = 0.750000;
360                 br->add_col[1] = 0.750000;
361                 br->add_col[2] = 0.750000;
362                 br->sub_col[0] = 0.250000;
363                 br->sub_col[1] = 0.250000;
364                 br->sub_col[2] = 0.250000;
365                 break;
366         case SCULPT_TOOL_NUDGE:
367                 br->add_col[0] = 0.250000;
368                 br->add_col[1] = 1.000000;
369                 br->add_col[2] = 0.250000;
370                 break;
371         case SCULPT_TOOL_PINCH:
372                 br->add_col[0] = 0.750000;
373                 br->add_col[1] = 0.750000;
374                 br->add_col[2] = 0.750000;
375                 br->sub_col[0] = 0.250000;
376                 br->sub_col[1] = 0.250000;
377                 br->sub_col[2] = 0.250000;
378                 break;
379         case SCULPT_TOOL_SCRAPE:
380                 br->add_col[1] = 1.000000;
381                 br->sub_col[0] = 0.250000;
382                 br->sub_col[1] = 1.000000;
383                 break;
384         case SCULPT_TOOL_ROTATE:
385                 br->alpha = 1.0;
386                 break;
387         case SCULPT_TOOL_SMOOTH:
388                 br->flag &= ~BRUSH_SPACE_ATTEN;
389                 br->spacing = 5;
390                 br->add_col[0] = 0.750000;
391                 br->add_col[1] = 0.750000;
392                 br->add_col[2] = 0.750000;
393                 break;
394         case SCULPT_TOOL_GRAB:
395         case SCULPT_TOOL_SNAKE_HOOK:
396         case SCULPT_TOOL_THUMB:
397                 br->size = 75;
398                 br->flag &= ~BRUSH_ALPHA_PRESSURE;
399                 br->flag &= ~BRUSH_SPACE;
400                 br->flag &= ~BRUSH_SPACE_ATTEN;
401                 br->add_col[0] = 0.250000;
402                 br->add_col[1] = 1.000000;
403                 br->add_col[2] = 0.250000;
404                 break;
405         default:
406                 break;
407         }
408 }
409
410 /* Library Operations */
411 void brush_curve_preset(Brush *b, /*CurveMappingPreset*/int preset)
412 {
413         CurveMap *cm = NULL;
414
415         if(!b->curve)
416                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
417
418         cm = b->curve->cm;
419         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
420
421         b->curve->preset = preset;
422         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
423         curvemapping_changed(b->curve, 0);
424 }
425
426 int brush_texture_set_nr(Brush *brush, int nr)
427 {
428         ID *idtest, *id=NULL;
429
430         id= (ID *)brush->mtex.tex;
431
432         idtest= (ID*)BLI_findlink(&G.main->tex, nr-1);
433         if(idtest==NULL) { /* new tex */
434                 if(id) idtest= (ID *)copy_texture((Tex *)id);
435                 else idtest= (ID *)add_texture("Tex");
436                 idtest->us--;
437         }
438         if(idtest!=id) {
439                 brush_texture_delete(brush);
440
441                 brush->mtex.tex= (Tex*)idtest;
442                 id_us_plus(idtest);
443
444                 return 1;
445         }
446
447         return 0;
448 }
449
450 int brush_texture_delete(Brush *brush)
451 {
452         if(brush->mtex.tex)
453                 brush->mtex.tex->id.us--;
454
455         return 1;
456 }
457
458 int brush_clone_image_set_nr(Brush *brush, int nr)
459 {
460         if(brush && nr > 0) {
461                 Image *ima= (Image*)BLI_findlink(&G.main->image, nr-1);
462
463                 if(ima) {
464                         brush_clone_image_delete(brush);
465                         brush->clone.image= ima;
466                         id_us_plus(&ima->id);
467                         brush->clone.offset[0]= brush->clone.offset[1]= 0.0f;
468
469                         return 1;
470                 }
471         }
472
473         return 0;
474 }
475
476 int brush_clone_image_delete(Brush *brush)
477 {
478         if (brush && brush->clone.image) {
479                 brush->clone.image->id.us--;
480                 brush->clone.image= NULL;
481                 return 1;
482         }
483
484         return 0;
485 }
486
487 /* Brush Sampling */
488 void brush_sample_tex(const Scene *scene, Brush *brush, const float xy[2], float rgba[4], const int thread)
489 {
490         MTex *mtex= &brush->mtex;
491
492         if (mtex && mtex->tex) {
493                 float co[3], tin, tr, tg, tb, ta;
494                 int hasrgb;
495                 const int radius= brush_size(scene, brush);
496
497                 co[0]= xy[0]/radius;
498                 co[1]= xy[1]/radius;
499                 co[2]= 0.0f;
500
501                 hasrgb= externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, thread);
502
503                 if (hasrgb) {
504                         rgba[0]= tr;
505                         rgba[1]= tg;
506                         rgba[2]= tb;
507                         rgba[3]= ta;
508                 }
509                 else {
510                         rgba[0]= tin;
511                         rgba[1]= tin;
512                         rgba[2]= tin;
513                         rgba[3]= 1.0f;
514                 }
515         }
516         else {
517                 rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
518         }
519 }
520
521 /* TODO, use define for 'texfall' arg */
522 void brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize, ImBuf **outbuf, int use_color_correction)
523 {
524         ImBuf *ibuf;
525         float xy[2], rgba[4], *dstf;
526         int x, y, rowbytes, xoff, yoff, imbflag;
527         const int radius= brush_size(scene, brush);
528         unsigned char *dst, crgb[3];
529         const float alpha= brush_alpha(scene, brush);
530         float brush_rgb[3];
531     
532         imbflag= (flt)? IB_rectfloat: IB_rect;
533         xoff = -bufsize/2.0f + 0.5f;
534         yoff = -bufsize/2.0f + 0.5f;
535         rowbytes= bufsize*4;
536
537         if (*outbuf)
538                 ibuf= *outbuf;
539         else
540                 ibuf= IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
541
542         if (flt) {
543                 copy_v3_v3(brush_rgb, brush->rgb);
544                 if (use_color_correction) {
545                         srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
546                 }
547
548                 for (y=0; y < ibuf->y; y++) {
549                         dstf = ibuf->rect_float + y*rowbytes;
550
551                         for (x=0; x < ibuf->x; x++, dstf+=4) {
552                                 xy[0] = x + xoff;
553                                 xy[1] = y + yoff;
554
555                                 if (texfall == 0) {
556                                         copy_v3_v3(dstf, brush_rgb);
557                                         dstf[3]= alpha*brush_curve_strength_clamp(brush, len_v2(xy), radius);
558                                 }
559                                 else if (texfall == 1) {
560                                         brush_sample_tex(scene, brush, xy, dstf, 0);
561                                 }
562                                 else {
563                                         brush_sample_tex(scene, brush, xy, rgba, 0);
564                                         mul_v3_v3v3(dstf, rgba, brush_rgb);
565                                         dstf[3] = rgba[3]*alpha*brush_curve_strength_clamp(brush, len_v2(xy), radius);
566                                 }
567                         }
568                 }
569         }
570         else {
571                 float alpha_f; /* final float alpha to convert to char */
572                 rgb_float_to_uchar(crgb, brush->rgb);
573
574                 for (y=0; y < ibuf->y; y++) {
575                         dst = (unsigned char *)ibuf->rect + y*rowbytes;
576
577                         for (x=0; x < ibuf->x; x++, dst+=4) {
578                                 xy[0] = x + xoff;
579                                 xy[1] = y + yoff;
580
581                                 if (texfall == 0) {
582                                         alpha_f = alpha * brush_curve_strength(brush, len_v2(xy), radius);
583
584                                         dst[0] = crgb[0];
585                                         dst[1] = crgb[1];
586                                         dst[2] = crgb[2];
587                                         dst[3] = FTOCHAR(alpha_f);
588                                 }
589                                 else if (texfall == 1) {
590                                         brush_sample_tex(scene, brush, xy, rgba, 0);
591                                         rgba_float_to_uchar(dst, rgba);
592                                 }
593                                 else if (texfall == 2) {
594                                         brush_sample_tex(scene, brush, xy, rgba, 0);
595                                         mul_v3_v3(rgba, brush->rgb);
596                                         alpha_f = rgba[3] * alpha * brush_curve_strength_clamp(brush, len_v2(xy), radius);
597
598                                         rgb_float_to_uchar(dst, rgba);
599
600                                         dst[3] = FTOCHAR(alpha_f);
601                                 }
602                                 else {
603                                         brush_sample_tex(scene, brush, xy, rgba, 0);
604                                         alpha_f = rgba[3] * alpha * brush_curve_strength_clamp(brush, len_v2(xy), radius);
605
606                                         dst[0] = crgb[0];
607                                         dst[1] = crgb[1];
608                                         dst[2] = crgb[2];
609                                         dst[3] = FTOCHAR(alpha_f);
610                                 }
611                         }
612                 }
613         }
614
615         *outbuf= ibuf;
616 }
617
618 /* Unified Size and Strength */
619
620 // XXX: be careful about setting size and unprojected radius
621 // because they depend on one another
622 // these functions do not set the other corresponding value
623 // this can lead to odd behavior if size and unprojected
624 // radius become inconsistent.
625 // the biggest problem is that it isn't possible to change
626 // unprojected radius because a view context is not
627 // available.  my ussual solution to this is to use the
628 // ratio of change of the size to change the unprojected
629 // radius.  Not completely convinced that is correct.
630 // In anycase, a better solution is needed to prevent
631 // inconsistency.
632
633 void brush_set_size(Scene *scene, Brush *brush, int size)
634 {
635         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
636
637         if (ups->flag & UNIFIED_PAINT_SIZE)
638                 ups->size= size;
639         else
640                 brush->size= size;
641 }
642
643 int brush_size(const Scene *scene, Brush *brush)
644 {
645         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
646
647         return (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
648 }
649
650 int brush_use_locked_size(const Scene *scene, Brush *brush)
651 {
652         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
653
654         return (us_flag & UNIFIED_PAINT_SIZE) ?
655                 (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
656                 (brush->flag & BRUSH_LOCK_SIZE);
657 }
658
659 int brush_use_size_pressure(const Scene *scene, Brush *brush)
660 {
661         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
662
663         return (us_flag & UNIFIED_PAINT_SIZE) ?
664                 (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
665                 (brush->flag & BRUSH_SIZE_PRESSURE);
666 }
667
668 int brush_use_alpha_pressure(const Scene *scene, Brush *brush)
669 {
670         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
671
672         return (us_flag & UNIFIED_PAINT_ALPHA) ?
673                 (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
674                 (brush->flag & BRUSH_ALPHA_PRESSURE);
675 }
676
677 void brush_set_unprojected_radius(Scene *scene, Brush *brush, float unprojected_radius)
678 {
679         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
680
681         if (ups->flag & UNIFIED_PAINT_SIZE)
682                 ups->unprojected_radius= unprojected_radius;
683         else
684                 brush->unprojected_radius= unprojected_radius;
685 }
686
687 float brush_unprojected_radius(const Scene *scene, Brush *brush)
688 {
689         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
690
691         return (ups->flag & UNIFIED_PAINT_SIZE) ?
692                 ups->unprojected_radius :
693                 brush->unprojected_radius;
694 }
695
696 static void brush_set_alpha(Scene *scene, Brush *brush, float alpha)
697 {
698         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
699
700         if (ups->flag & UNIFIED_PAINT_ALPHA)
701                 ups->alpha= alpha;
702         else
703                 brush->alpha= alpha;
704 }
705
706 float brush_alpha(const Scene *scene, Brush *brush)
707 {
708         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
709
710         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
711 }
712
713 /* scale unprojected radius to reflect a change in the brush's 2D size */
714 void brush_scale_unprojected_radius(float *unprojected_radius,
715                                                                         int new_brush_size,
716                                                                         int old_brush_size)
717 {
718         float scale = new_brush_size;
719         /* avoid division by zero */
720         if(old_brush_size != 0)
721                 scale /= (float)old_brush_size;
722         (*unprojected_radius) *= scale;
723 }
724
725 /* scale brush size to reflect a change in the brush's unprojected radius */
726 void brush_scale_size(int *brush_size,
727                                           float new_unprojected_radius,
728                                           float old_unprojected_radius)
729 {
730         float scale = new_unprojected_radius;
731         /* avoid division by zero */
732         if(old_unprojected_radius != 0)
733                 scale /= new_unprojected_radius;
734         (*brush_size)= (int)((float)(*brush_size) * scale);
735 }
736
737 /* Brush Painting */
738
739 typedef struct BrushPainterCache {
740         short enabled;
741
742         int size;                       /* size override, if 0 uses 2*brush_size(brush) */
743         short flt;                      /* need float imbuf? */
744         short texonly;          /* no alpha, color or fallof, only texture in imbuf */
745
746         int lastsize;
747         float lastalpha;
748         float lastjitter;
749
750         ImBuf *ibuf;
751         ImBuf *texibuf;
752         ImBuf *maskibuf;
753 } BrushPainterCache;
754
755 struct BrushPainter {
756         Scene *scene;
757         Brush *brush;
758
759         float lastmousepos[2];  /* mouse position of last paint call */
760
761         float accumdistance;    /* accumulated distance of brush since last paint op */
762         float lastpaintpos[2];  /* position of last paint op */
763         float startpaintpos[2]; /* position of first paint */
764
765         double accumtime;               /* accumulated time since last paint op (airbrush) */
766         double lasttime;                /* time of last update */
767
768         float lastpressure;
769
770         short firsttouch;               /* first paint op */
771
772         float startsize;
773         float startalpha;
774         float startjitter;
775         float startspacing;
776
777         BrushPainterCache cache;
778 };
779
780 BrushPainter *brush_painter_new(Scene *scene, Brush *brush)
781 {
782         BrushPainter *painter= MEM_callocN(sizeof(BrushPainter), "BrushPainter");
783
784         painter->brush= brush;
785         painter->scene= scene;
786         painter->firsttouch= 1;
787         painter->cache.lastsize= -1; /* force ibuf create in refresh */
788
789         painter->startsize = brush_size(scene, brush);
790         painter->startalpha = brush_alpha(scene, brush);
791         painter->startjitter = brush->jitter;
792         painter->startspacing = brush->spacing;
793
794         return painter;
795 }
796
797 void brush_painter_require_imbuf(BrushPainter *painter, short flt, short texonly, int size)
798 {
799         if ((painter->cache.flt != flt) || (painter->cache.size != size) ||
800                 ((painter->cache.texonly != texonly) && texonly)) {
801                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
802                 if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
803                 painter->cache.ibuf= painter->cache.maskibuf= NULL;
804                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
805         }
806
807         if (painter->cache.flt != flt) {
808                 if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
809                 painter->cache.texibuf= NULL;
810                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
811         }
812
813         painter->cache.size= size;
814         painter->cache.flt= flt;
815         painter->cache.texonly= texonly;
816         painter->cache.enabled= 1;
817 }
818
819 void brush_painter_free(BrushPainter *painter)
820 {
821         Brush *brush = painter->brush;
822
823         brush_set_size(painter->scene, brush, painter->startsize);
824         brush_set_alpha(painter->scene, brush, painter->startalpha);
825         brush->jitter = painter->startjitter;
826         brush->spacing = painter->startspacing;
827
828         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
829         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
830         if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
831         MEM_freeN(painter);
832 }
833
834 static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf,
835                                      int x, int y, int w, int h, int xt, int yt,
836                                      const float pos[2])
837 {
838         Scene *scene= painter->scene;
839         Brush *brush= painter->brush;
840         ImBuf *ibuf, *maskibuf, *texibuf;
841         float *bf, *mf, *tf, *otf=NULL, xoff, yoff, xy[2], rgba[4];
842         unsigned char *b, *m, *t, *ot= NULL;
843         int dotexold, origx= x, origy= y;
844         const int radius= brush_size(painter->scene, brush);
845
846         xoff = -radius + 0.5f;
847         yoff = -radius + 0.5f;
848         xoff += (int)pos[0] - (int)painter->startpaintpos[0];
849         yoff += (int)pos[1] - (int)painter->startpaintpos[1];
850
851         ibuf = painter->cache.ibuf;
852         texibuf = painter->cache.texibuf;
853         maskibuf = painter->cache.maskibuf;
854
855         dotexold = (oldtexibuf != NULL);
856
857         /* not sure if it's actually needed or it's a mistake in coords/sizes
858          * calculation in brush_painter_fixed_tex_partial_update(), but without this
859          * limitation memory gets corrupted at fast strokes with quite big spacing (sergey) */
860         w = MIN2(w, ibuf->x);
861         h = MIN2(h, ibuf->y);
862
863         if (painter->cache.flt) {
864                 for (; y < h; y++) {
865                         bf = ibuf->rect_float + (y*ibuf->x + origx)*4;
866                         tf = texibuf->rect_float + (y*texibuf->x + origx)*4;
867                         mf = maskibuf->rect_float + (y*maskibuf->x + origx)*4;
868
869                         if (dotexold)
870                                 otf = oldtexibuf->rect_float + ((y - origy + yt)*oldtexibuf->x + xt)*4;
871
872                         for (x=origx; x < w; x++, bf+=4, mf+=4, tf+=4) {
873                                 if (dotexold) {
874                                         copy_v3_v3(tf, otf);
875                                         tf[3] = otf[3];
876                                         otf += 4;
877                                 }
878                                 else {
879                                         xy[0] = x + xoff;
880                                         xy[1] = y + yoff;
881
882                                         brush_sample_tex(scene, brush, xy, tf, 0);
883                                 }
884
885                                 bf[0] = tf[0]*mf[0];
886                                 bf[1] = tf[1]*mf[1];
887                                 bf[2] = tf[2]*mf[2];
888                                 bf[3] = tf[3]*mf[3];
889                         }
890                 }
891         }
892         else {
893                 for (; y < h; y++) {
894                         b = (unsigned char *)ibuf->rect + (y*ibuf->x + origx)*4;
895                         t = (unsigned char *)texibuf->rect + (y*texibuf->x + origx)*4;
896                         m = (unsigned char *)maskibuf->rect + (y*maskibuf->x + origx)*4;
897
898                         if (dotexold)
899                                 ot = (unsigned char *)oldtexibuf->rect + ((y - origy + yt)*oldtexibuf->x + xt)*4;
900
901                         for (x=origx; x < w; x++, b+=4, m+=4, t+=4) {
902                                 if (dotexold) {
903                                         t[0] = ot[0];
904                                         t[1] = ot[1];
905                                         t[2] = ot[2];
906                                         t[3] = ot[3];
907                                         ot += 4;
908                                 }
909                                 else {
910                                         xy[0] = x + xoff;
911                                         xy[1] = y + yoff;
912
913                                         brush_sample_tex(scene, brush, xy, rgba, 0);
914                                         rgba_float_to_uchar(t, rgba);
915                                 }
916
917                                 b[0] = t[0]*m[0]/255;
918                                 b[1] = t[1]*m[1]/255;
919                                 b[2] = t[2]*m[2]/255;
920                                 b[3] = t[3]*m[3]/255;
921                         }
922                 }
923         }
924 }
925
926 static void brush_painter_fixed_tex_partial_update(BrushPainter *painter, const float pos[2])
927 {
928         const Scene *scene= painter->scene;
929         Brush *brush= painter->brush;
930         BrushPainterCache *cache= &painter->cache;
931         ImBuf *oldtexibuf, *ibuf;
932         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
933         const int diameter= 2*brush_size(scene, brush);
934
935         imbflag= (cache->flt)? IB_rectfloat: IB_rect;
936         if (!cache->ibuf)
937                 cache->ibuf= IMB_allocImBuf(diameter, diameter, 32, imbflag);
938         ibuf= cache->ibuf;
939
940         oldtexibuf= cache->texibuf;
941         cache->texibuf= IMB_allocImBuf(diameter, diameter, 32, imbflag);
942
943         if (oldtexibuf) {
944                 srcx= srcy= 0;
945                 destx= (int)painter->lastpaintpos[0] - (int)pos[0];
946                 desty= (int)painter->lastpaintpos[1] - (int)pos[1];
947                 w= oldtexibuf->x;
948                 h= oldtexibuf->y;
949
950                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
951         }
952         else {
953                 srcx= srcy= 0;
954                 destx= desty= 0;
955                 w= h= 0;
956         }
957         
958         x1= destx;
959         y1= desty;
960         x2= destx+w;
961         y2= desty+h;
962
963         /* blend existing texture in new position */
964         if ((x1 < x2) && (y1 < y2))
965                 brush_painter_do_partial(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy, pos);
966
967         if (oldtexibuf)
968                 IMB_freeImBuf(oldtexibuf);
969
970         /* sample texture in new areas */
971         if ((0 < x1) && (0 < ibuf->y))
972                 brush_painter_do_partial(painter, NULL, 0, 0, x1, ibuf->y, 0, 0, pos);
973         if ((x2 < ibuf->x) && (0 < ibuf->y))
974                 brush_painter_do_partial(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0, pos);
975         if ((x1 < x2) && (0 < y1))
976                 brush_painter_do_partial(painter, NULL, x1, 0, x2, y1, 0, 0, pos);
977         if ((x1 < x2) && (y2 < ibuf->y))
978                 brush_painter_do_partial(painter, NULL, x1, y2, x2, ibuf->y, 0, 0, pos);
979 }
980
981 static void brush_painter_refresh_cache(BrushPainter *painter, const float pos[2], int use_color_correction)
982 {
983         const Scene *scene= painter->scene;
984         Brush *brush= painter->brush;
985         BrushPainterCache *cache= &painter->cache;
986         MTex *mtex= &brush->mtex;
987         int size;
988         short flt;
989         const int diameter= 2*brush_size(scene, brush);
990         const float alpha= brush_alpha(scene, brush);
991
992         if (diameter != cache->lastsize ||
993                 alpha != cache->lastalpha ||
994                 brush->jitter != cache->lastjitter)
995         {
996                 if (cache->ibuf) {
997                         IMB_freeImBuf(cache->ibuf);
998                         cache->ibuf= NULL;
999                 }
1000                 if (cache->maskibuf) {
1001                         IMB_freeImBuf(cache->maskibuf);
1002                         cache->maskibuf= NULL;
1003                 }
1004
1005                 flt= cache->flt;
1006                 size= (cache->size)? cache->size: diameter;
1007
1008                 if (brush->flag & BRUSH_FIXED_TEX) {
1009                         brush_imbuf_new(scene, brush, flt, 3, size, &cache->maskibuf, use_color_correction);
1010                         brush_painter_fixed_tex_partial_update(painter, pos);
1011                 }
1012                 else
1013                         brush_imbuf_new(scene, brush, flt, 2, size, &cache->ibuf, use_color_correction);
1014
1015                 cache->lastsize= diameter;
1016                 cache->lastalpha= alpha;
1017                 cache->lastjitter= brush->jitter;
1018         }
1019         else if ((brush->flag & BRUSH_FIXED_TEX) && mtex && mtex->tex) {
1020                 int dx = (int)painter->lastpaintpos[0] - (int)pos[0];
1021                 int dy = (int)painter->lastpaintpos[1] - (int)pos[1];
1022
1023                 if ((dx != 0) || (dy != 0))
1024                         brush_painter_fixed_tex_partial_update(painter, pos);
1025         }
1026 }
1027
1028 void brush_painter_break_stroke(BrushPainter *painter)
1029 {
1030         painter->firsttouch= 1;
1031 }
1032
1033 static void brush_apply_pressure(BrushPainter *painter, Brush *brush, float pressure)
1034 {
1035         if (brush_use_alpha_pressure(painter->scene, brush)) 
1036                 brush_set_alpha(painter->scene, brush, MAX2(0.0f, painter->startalpha*pressure));
1037         if (brush_use_size_pressure(painter->scene, brush))
1038                 brush_set_size(painter->scene, brush, MAX2(1.0f, painter->startsize*pressure));
1039         if (brush->flag & BRUSH_JITTER_PRESSURE)
1040                 brush->jitter = MAX2(0.0f, painter->startjitter*pressure);
1041         if (brush->flag & BRUSH_SPACING_PRESSURE)
1042                 brush->spacing = MAX2(1.0f, painter->startspacing*(1.5f-pressure));
1043 }
1044
1045 void brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
1046 {
1047         int use_jitter= brush->jitter != 0;
1048
1049         /* jitter-ed brush gives weird and unpredictable result for this
1050          * kinds of stroke, so manyally disable jitter usage (sergey) */
1051         use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH|BRUSH_ANCHORED)) == 0;
1052
1053         if (use_jitter) {
1054                 float rand_pos[2];
1055                 const int radius= brush_size(scene, brush);
1056                 const int diameter= 2*radius;
1057
1058                 // find random position within a circle of diameter 1
1059                 do {
1060                         rand_pos[0] = BLI_frand()-0.5f;
1061                         rand_pos[1] = BLI_frand()-0.5f;
1062                 } while (len_v2(rand_pos) > 0.5f);
1063
1064                 jitterpos[0] = pos[0] + 2*rand_pos[0]*diameter*brush->jitter;
1065                 jitterpos[1] = pos[1] + 2*rand_pos[1]*diameter*brush->jitter;
1066         }
1067         else {
1068                 copy_v2_v2(jitterpos, pos);
1069         }
1070 }
1071
1072 int brush_painter_paint(BrushPainter *painter, BrushFunc func, const float pos[2], double time, float pressure,
1073                         void *user, int use_color_correction)
1074 {
1075         Scene *scene= painter->scene;
1076         Brush *brush= painter->brush;
1077         int totpaintops= 0;
1078
1079         if (pressure == 0.0f) {
1080                 if(painter->lastpressure) // XXX - hack, operator misses
1081                         pressure= painter->lastpressure;
1082                 else
1083                         pressure = 1.0f;        /* zero pressure == not using tablet */
1084         }
1085         if (painter->firsttouch) {
1086                 /* paint exactly once on first touch */
1087                 painter->startpaintpos[0]= pos[0];
1088                 painter->startpaintpos[1]= pos[1];
1089
1090                 brush_apply_pressure(painter, brush, pressure);
1091                 if (painter->cache.enabled)
1092                         brush_painter_refresh_cache(painter, pos, use_color_correction);
1093                 totpaintops += func(user, painter->cache.ibuf, pos, pos);
1094                 
1095                 painter->lasttime= time;
1096                 painter->firsttouch= 0;
1097                 painter->lastpaintpos[0]= pos[0];
1098                 painter->lastpaintpos[1]= pos[1];
1099         }
1100 #if 0
1101         else if (painter->brush->flag & BRUSH_AIRBRUSH) {
1102                 float spacing, step, paintpos[2], dmousepos[2], len;
1103                 double starttime, curtime= time;
1104
1105                 /* compute brush spacing adapted to brush size */
1106                 spacing= brush->rate; //radius*brush->spacing*0.01f;
1107
1108                 /* setup starting time, direction vector and accumulated time */
1109                 starttime= painter->accumtime;
1110                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
1111                 len= normalize_v2(dmousepos);
1112                 painter->accumtime += curtime - painter->lasttime;
1113
1114                 /* do paint op over unpainted time distance */
1115                 while (painter->accumtime >= spacing) {
1116                         step= (spacing - starttime)*len;
1117                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
1118                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
1119
1120                         if (painter->cache.enabled)
1121                                 brush_painter_refresh_cache(painter);
1122                         totpaintops += func(user, painter->cache.ibuf,
1123                                 painter->lastpaintpos, paintpos);
1124
1125                         painter->lastpaintpos[0]= paintpos[0];
1126                         painter->lastpaintpos[1]= paintpos[1];
1127                         painter->accumtime -= spacing;
1128                         starttime -= spacing;
1129                 }
1130                 
1131                 painter->lasttime= curtime;
1132         }
1133 #endif
1134         else {
1135                 float startdistance, spacing, step, paintpos[2], dmousepos[2], finalpos[2];
1136                 float t, len, press;
1137                 const int radius= brush_size(scene, brush);
1138
1139                 /* compute brush spacing adapted to brush radius, spacing may depend
1140                  * on pressure, so update it */
1141                 brush_apply_pressure(painter, brush, painter->lastpressure);
1142                 spacing= MAX2(1.0f, radius)*brush->spacing*0.01f;
1143
1144                 /* setup starting distance, direction vector and accumulated distance */
1145                 startdistance= painter->accumdistance;
1146                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
1147                 len= normalize_v2(dmousepos);
1148                 painter->accumdistance += len;
1149
1150                 if (brush->flag & BRUSH_SPACE) {
1151                         /* do paint op over unpainted distance */
1152                         while ((len > 0.0f) && (painter->accumdistance >= spacing)) {
1153                                 step= spacing - startdistance;
1154                                 paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
1155                                 paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
1156
1157                                 t = step/len;
1158                                 press= (1.0f-t)*painter->lastpressure + t*pressure;
1159                                 brush_apply_pressure(painter, brush, press);
1160                                 spacing= MAX2(1.0f, radius)*brush->spacing*0.01f;
1161
1162                                 brush_jitter_pos(scene, brush, paintpos, finalpos);
1163
1164                                 if (painter->cache.enabled)
1165                                         brush_painter_refresh_cache(painter, finalpos, use_color_correction);
1166
1167                                 totpaintops +=
1168                                         func(user, painter->cache.ibuf, painter->lastpaintpos, finalpos);
1169
1170                                 painter->lastpaintpos[0]= paintpos[0];
1171                                 painter->lastpaintpos[1]= paintpos[1];
1172                                 painter->accumdistance -= spacing;
1173                                 startdistance -= spacing;
1174                         }
1175                 } else {
1176                         brush_jitter_pos(scene, brush, pos, finalpos);
1177
1178                         if (painter->cache.enabled)
1179                                 brush_painter_refresh_cache(painter, finalpos, use_color_correction);
1180
1181                         totpaintops += func(user, painter->cache.ibuf, pos, finalpos);
1182
1183                         painter->lastpaintpos[0]= pos[0];
1184                         painter->lastpaintpos[1]= pos[1];
1185                         painter->accumdistance= 0;
1186                 }
1187
1188                 /* do airbrush paint ops, based on the number of paint ops left over
1189                  * from regular painting. this is a temporary solution until we have
1190                  * accurate time stamps for mouse move events */
1191                 if (brush->flag & BRUSH_AIRBRUSH) {
1192                         double curtime= time;
1193                         double painttime= brush->rate*totpaintops;
1194
1195                         painter->accumtime += curtime - painter->lasttime;
1196                         if (painter->accumtime <= painttime)
1197                                 painter->accumtime= 0.0;
1198                         else
1199                                 painter->accumtime -= painttime;
1200
1201                         while (painter->accumtime >= (double)brush->rate) {
1202                                 brush_apply_pressure(painter, brush, pressure);
1203
1204                                 brush_jitter_pos(scene, brush, pos, finalpos);
1205
1206                                 if (painter->cache.enabled)
1207                                         brush_painter_refresh_cache(painter, finalpos, use_color_correction);
1208
1209                                 totpaintops +=
1210                                         func(user, painter->cache.ibuf, painter->lastmousepos, finalpos);
1211                                 painter->accumtime -= (double)brush->rate;
1212                         }
1213
1214                         painter->lasttime= curtime;
1215                 }
1216         }
1217
1218         painter->lastmousepos[0]= pos[0];
1219         painter->lastmousepos[1]= pos[1];
1220         painter->lastpressure= pressure;
1221
1222         brush_set_alpha(scene, brush, painter->startalpha);
1223         brush_set_size(scene, brush, painter->startsize);
1224         brush->jitter = painter->startjitter;
1225         brush->spacing = painter->startspacing;
1226
1227         return totpaintops;
1228 }
1229
1230 /* Uses the brush curve control to find a strength value between 0 and 1 */
1231 float brush_curve_strength_clamp(Brush *br, float p, const float len)
1232 {
1233         if(p >= len)    return 0;
1234         else                    p= p/len;
1235
1236         p= curvemapping_evaluateF(br->curve, 0, p);
1237         if(p < 0.0f)            p= 0.0f;
1238         else if(p > 1.0f)       p= 1.0f;
1239         return p;
1240 }
1241 /* same as above but can return negative values if the curve enables
1242  * used for sculpt only */
1243 float brush_curve_strength(Brush *br, float p, const float len)
1244 {
1245         if(p >= len)
1246                 p= 1.0f;
1247         else
1248                 p= p/len;
1249
1250         return curvemapping_evaluateF(br->curve, 0, p);
1251 }
1252
1253 /* TODO: should probably be unified with BrushPainter stuff? */
1254 unsigned int *brush_gen_texture_cache(Brush *br, int half_side)
1255 {
1256         unsigned int *texcache = NULL;
1257         MTex *mtex = &br->mtex;
1258         TexResult texres= {0};
1259         int hasrgb, ix, iy;
1260         int side = half_side * 2;
1261         
1262         if(mtex->tex) {
1263                 float x, y, step = 2.0 / side, co[3];
1264
1265                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1266
1267                 BKE_image_get_ibuf(mtex->tex->ima, NULL);
1268                 
1269                 /*do normalized cannonical view coords for texture*/
1270                 for (y=-1.0, iy=0; iy<side; iy++, y += step) {
1271                         for (x=-1.0, ix=0; ix<side; ix++, x += step) {
1272                                 co[0]= x;
1273                                 co[1]= y;
1274                                 co[2]= 0.0f;
1275                                 
1276                                 /* This is copied from displace modifier code */
1277                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres);
1278                         
1279                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1280                                  * intensity, so calculate one (formula from do_material_tex).
1281                                  * if the texture didn't give an RGB value, copy the intensity across
1282                                  */
1283                                 if(hasrgb & TEX_RGB)
1284                                         texres.tin = (0.35f * texres.tr + 0.45f *
1285                                                                   texres.tg + 0.2f * texres.tb);
1286
1287                                 texres.tin = texres.tin * 255.0f;
1288                                 ((char*)texcache)[(iy*side+ix)*4] = (char)texres.tin;
1289                                 ((char*)texcache)[(iy*side+ix)*4+1] = (char)texres.tin;
1290                                 ((char*)texcache)[(iy*side+ix)*4+2] = (char)texres.tin;
1291                                 ((char*)texcache)[(iy*side+ix)*4+3] = (char)texres.tin;
1292                         }
1293                 }
1294         }
1295
1296         return texcache;
1297 }
1298
1299 /**** Radial Control ****/
1300 struct ImBuf *brush_gen_radial_control_imbuf(Brush *br)
1301 {
1302         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1303         unsigned int *texcache;
1304         int side = 128;
1305         int half = side / 2;
1306         int i, j;
1307
1308         texcache = brush_gen_texture_cache(br, half);
1309         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1310         im->x = im->y = side;
1311
1312         for(i=0; i<side; ++i) {
1313                 for(j=0; j<side; ++j) {
1314                         float magn= sqrt(pow(i - half, 2) + pow(j - half, 2));
1315                         im->rect_float[i*side + j]= brush_curve_strength_clamp(br, magn, half);
1316                 }
1317         }
1318
1319         /* Modulate curve with texture */
1320         if(texcache) {
1321                 for(i=0; i<side; ++i) {
1322                         for(j=0; j<side; ++j) {
1323                                 const int col= texcache[i*side+j];
1324                                 im->rect_float[i*side+j]*= (((char*)&col)[0]+((char*)&col)[1]+((char*)&col)[2])/3.0f/255.0f;
1325                         }
1326                 }
1327
1328                 MEM_freeN(texcache);
1329         }
1330
1331         return im;
1332 }