* Made the default sculpt icons an internal part of the executable
[blender.git] / source / blender / blenkernel / intern / brush.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <math.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_brush_types.h"
36 #include "DNA_color_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_windowmanager_types.h"
39
40 #include "WM_types.h"
41
42 #include "RNA_access.h"
43
44 #include "BLI_math.h"
45 #include "BLI_blenlib.h"
46 #include "BLI_rand.h"
47
48 #include "BKE_brush.h"
49 #include "BKE_colortools.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_paint.h"
55 #include "BKE_texture.h"
56 #include "BKE_icons.h"
57
58 #include "IMB_imbuf.h"
59 #include "IMB_imbuf_types.h"
60
61 #include "RE_render_ext.h" /* externtex */
62 #include "RE_shader_ext.h"
63
64 /* Datablock add/copy/free/make_local */
65
66 Brush *add_brush(const char *name)
67 {
68         Brush *brush;
69
70         brush= alloc_libblock(&G.main->brush, ID_BR, name);
71
72         /* BRUSH SCULPT TOOL SETTINGS */
73         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
74         brush->size= 35; /* radius of the brush in pixels */
75         brush->alpha= 0.5f; /* brush strength/intensity probably variable should be renamed? */
76         brush->autosmooth_factor= 0.0f;
77         brush->crease_pinch_factor= 0.5f;
78         brush->sculpt_plane = SCULPT_DISP_DIR_VIEW;
79         brush->plane_offset= 0.0f; /* how far above or below the plane that is found by averaging the faces */
80         brush->plane_trim= 0.5f;
81         brush->clone.alpha= 0.5f;
82         brush->normal_weight= 0.0f;
83
84         /* BRUSH PAINT TOOL SETTINGS */
85         brush->rgb[0]= 1.0f; /* default rgb color of the brush when painting - white */
86         brush->rgb[1]= 1.0f;
87         brush->rgb[2]= 1.0f;
88
89         /* BRUSH STROKE SETTINGS */
90         brush->flag |= (BRUSH_SPACE|BRUSH_SPACE_ATTEN);
91         brush->spacing= 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
92
93         brush->smooth_stroke_radius= 75;
94         brush->smooth_stroke_factor= 0.9f;
95
96         brush->rate= 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
97
98         brush->jitter= 0.0f;
99
100         /* BRUSH TEXTURE SETTINGS */
101         default_mtex(&brush->mtex);
102
103         brush->texture_sample_bias= 0; /* value to added to texture samples */
104
105         /* brush appearance  */
106
107         brush->icon_imbuf= get_brush_icon(brush);
108
109         brush->add_col[0]= 1.00; /* add mode color is light red */
110         brush->add_col[1]= 0.39;
111         brush->add_col[2]= 0.39;
112
113         brush->sub_col[0]= 0.39; /* subtract mode color is light blue */
114         brush->sub_col[1]= 0.39;
115         brush->sub_col[2]= 1.00;
116
117          /* the default alpha falloff curve */
118         brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
119
120         /* enable fake user by default */
121         brush->id.flag |= LIB_FAKEUSER;
122         brush_toggled_fake_user(brush);
123
124         return brush;
125 }
126
127 Brush *copy_brush(Brush *brush)
128 {
129         Brush *brushn;
130         
131         brushn= copy_libblock(brush);
132
133         if(brush->mtex.tex) id_us_plus((ID*)brush->mtex.tex);
134
135         IMB_refImBuf(brushn->icon_imbuf);
136
137         brushn->curve= curvemapping_copy(brush->curve);
138
139         /* enable fake user by default */
140         if (!(brushn->id.flag & LIB_FAKEUSER)) {
141                 brushn->id.flag |= LIB_FAKEUSER;
142                 brush_toggled_fake_user(brushn);
143         }
144         
145         return brushn;
146 }
147
148 /* not brush itself */
149 void free_brush(Brush *brush)
150 {
151         if (brush->mtex.tex)
152                 brush->mtex.tex->id.us--;
153
154         if (brush->icon==BRUSH_ICON_FILE && brush->icon_imbuf)
155                 IMB_freeImBuf(brush->icon_imbuf);
156
157         BKE_previewimg_free(&(brush->preview));
158
159         curvemapping_free(brush->curve);
160 }
161
162 void make_local_brush(Brush *brush)
163 {
164         /* - only lib users: do nothing
165                 * - only local users: set flag
166                 * - mixed: make copy
167                 */
168         
169         Brush *brushn;
170         Scene *scene;
171         int local= 0, lib= 0;
172
173         if(brush->id.lib==0) return;
174
175         if(brush->clone.image) {
176                 /* special case: ima always local immediately */
177                 brush->clone.image->id.lib= 0;
178                 brush->clone.image->id.flag= LIB_LOCAL;
179                 new_id(0, (ID *)brush->clone.image, 0);
180         }
181
182         for(scene= G.main->scene.first; scene; scene=scene->id.next)
183                 if(paint_brush(&scene->toolsettings->imapaint.paint)==brush) {
184                         if(scene->id.lib) lib= 1;
185                         else local= 1;
186                 }
187
188         if(local && lib==0) {
189                 brush->id.lib= 0;
190                 brush->id.flag= LIB_LOCAL;
191                 new_id(0, (ID *)brush, 0);
192
193                 /* enable fake user by default */
194                 if (!(brush->id.flag & LIB_FAKEUSER)) {
195                         brush->id.flag |= LIB_FAKEUSER;
196                         brush_toggled_fake_user(brush);
197                 }
198         }
199         else if(local && lib) {
200                 brushn= copy_brush(brush);
201                 brushn->id.us= 1; /* only keep fake user */
202                 brushn->id.flag |= LIB_FAKEUSER;
203                 
204                 for(scene= G.main->scene.first; scene; scene=scene->id.next)
205                         if(paint_brush(&scene->toolsettings->imapaint.paint)==brush)
206                                 if(scene->id.lib==0) {
207                                         paint_brush_set(&scene->toolsettings->imapaint.paint, brushn);
208                                         brushn->id.us++;
209                                         brush->id.us--;
210                                 }
211         }
212 }
213
214 /* image icon function */
215 ImBuf* get_brush_icon(Brush *brush)
216 {
217         extern char datatoc_blob_png;
218         extern char datatoc_clay_png;
219         extern char datatoc_crease_png;
220         extern char datatoc_draw_png;
221         extern char datatoc_fill_png;
222         extern char datatoc_flatten_png;
223         extern char datatoc_grab_png;
224         extern char datatoc_inflate_png;
225         extern char datatoc_layer_png;
226         extern char datatoc_nudge_png;
227         extern char datatoc_pinch_png;
228         extern char datatoc_scrape_png;
229         extern char datatoc_smooth_png;
230         extern char datatoc_snake_hook_png;
231         extern char datatoc_thumb_png;
232         extern char datatoc_twist_png;
233
234         extern int datatoc_blob_png_size;
235         extern int datatoc_clay_png_size;
236         extern int datatoc_crease_png_size;
237         extern int datatoc_draw_png_size;
238         extern int datatoc_fill_png_size;
239         extern int datatoc_flatten_png_size;
240         extern int datatoc_grab_png_size;
241         extern int datatoc_inflate_png_size;
242         extern int datatoc_layer_png_size;
243         extern int datatoc_nudge_png_size;
244         extern int datatoc_pinch_png_size;
245         extern int datatoc_scrape_png_size;
246         extern int datatoc_smooth_png_size;
247         extern int datatoc_snake_hook_png_size;
248         extern int datatoc_thumb_png_size;
249         extern int datatoc_twist_png_size;
250
251         void *icon_data[]= {
252                 0,
253                 &datatoc_blob_png,
254                 &datatoc_clay_png,
255                 &datatoc_crease_png,
256                 &datatoc_draw_png,
257                 &datatoc_fill_png,
258                 &datatoc_flatten_png,
259                 &datatoc_grab_png,
260                 &datatoc_inflate_png,
261                 &datatoc_layer_png,
262                 &datatoc_nudge_png,
263                 &datatoc_pinch_png,
264                 &datatoc_scrape_png,
265                 &datatoc_smooth_png,
266                 &datatoc_snake_hook_png,
267                 &datatoc_thumb_png,
268                 &datatoc_twist_png,
269         };
270
271         size_t icon_size[]= {
272                 0,
273                 datatoc_blob_png_size,
274                 datatoc_clay_png_size,
275                 datatoc_crease_png_size,
276                 datatoc_draw_png_size,
277                 datatoc_fill_png_size,
278                 datatoc_flatten_png_size,
279                 datatoc_grab_png_size,
280                 datatoc_inflate_png_size,
281                 datatoc_layer_png_size,
282                 datatoc_nudge_png_size,
283                 datatoc_pinch_png_size,
284                 datatoc_scrape_png_size,
285                 datatoc_smooth_png_size,
286                 datatoc_snake_hook_png_size,
287                 datatoc_thumb_png_size,
288                 datatoc_twist_png_size,
289         };
290
291         static ImBuf  *icon_imbuf[BRUSH_ICON_COUNT]= { 0 };
292
293         static const int flags = IB_rect|IB_multilayer|IB_metadata;
294
295         static const int default_icon = BRUSH_ICON_DRAW;
296
297         char path[240];
298         char *folder;
299
300         if (!(brush->icon_imbuf)) {
301                 if (brush->icon==BRUSH_ICON_FILE) {
302
303                         if (brush->icon_filepath[0]) {
304                                 // first use the path directly to try and load the file
305
306                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
307                                 BLI_path_abs(path, G.sce);
308
309                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
310
311                                 // otherwise lets try to find it in other directories
312                                 if (!(brush->icon_imbuf)) {
313                                         folder= BLI_get_folder(BLENDER_DATAFILES, "brushicons");
314
315                                         path[0]= 0;
316
317                                         BLI_make_file_string(G.sce, path, folder, brush->icon_filepath);
318
319                                         if (path[0])
320                                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
321                                 }
322                         }
323
324                         // if all else fails use a default image
325                         if (!(brush->icon_imbuf)) {
326                                 if (!icon_imbuf[default_icon])
327                                         icon_imbuf[default_icon]= IMB_ibImageFromMemory(icon_data[default_icon], icon_size[default_icon], flags);
328
329                                 brush->icon_imbuf= icon_imbuf[default_icon];
330                         }
331                 }
332                 else {
333                         if (!icon_imbuf[brush->icon])
334                                 icon_imbuf[brush->icon]= IMB_ibImageFromMemory(icon_data[brush->icon], icon_size[brush->icon], flags);
335
336                         brush->icon_imbuf= icon_imbuf[brush->icon];
337                 }
338
339                 BKE_icon_changed(BKE_icon_getid(&(brush->id)));
340         }
341
342         if (!(brush->icon_imbuf))
343                 printf("get_brush_icon: unable to resolve brush icon imbuf\n");
344
345         return brush->icon_imbuf;
346 }
347
348 /* Library Operations */
349
350 int brush_set_nr(Brush **current_brush, int nr, const char *name)
351 {
352         ID *idtest, *id;
353         
354         id= (ID*)(*current_brush);
355         idtest= (ID*)BLI_findlink(&G.main->brush, nr-1);
356         
357         if(idtest==0) { /* new brush */
358                 if(id) idtest= (ID *)copy_brush((Brush *)id);
359                 else idtest= (ID *)add_brush(name);
360                 idtest->us--;
361         }
362         if(idtest!=id) {
363                 brush_delete(current_brush);
364                 *current_brush= (Brush *)idtest;
365                 id_us_plus(idtest);
366
367                 return 1;
368         }
369
370         return 0;
371 }
372
373 int brush_delete(Brush **current_brush)
374 {
375         if (*current_brush) {
376                 (*current_brush)->id.us--;
377                 *current_brush= NULL;
378
379                 return 1;
380         }
381
382         return 0;
383 }
384
385 void brush_toggled_fake_user(Brush *brush)
386 {
387         ID *id= (ID*)brush;
388         if(id) {
389                 if(id->flag & LIB_FAKEUSER) {
390                         id_us_plus(id);
391                 } else {
392                         id->us--;
393                 }
394         }
395 }
396
397 void brush_curve_preset(Brush *b, /*CurveMappingPreset*/int preset)
398 {
399         CurveMap *cm = NULL;
400
401         if(!b->curve)
402                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
403
404         cm = b->curve->cm;
405         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
406
407         b->curve->preset = preset;
408         curvemap_reset(cm, &b->curve->clipr, b->curve->preset);
409         curvemapping_changed(b->curve, 0);
410 }
411
412 static MTex *brush_active_texture(Brush *brush)
413 {
414         if(brush)
415                 return &brush->mtex;
416         return NULL;
417 }
418
419 int brush_texture_set_nr(Brush *brush, int nr)
420 {
421         ID *idtest, *id=NULL;
422
423         id= (ID *)brush->mtex.tex;
424
425         idtest= (ID*)BLI_findlink(&G.main->tex, nr-1);
426         if(idtest==0) { /* new tex */
427                 if(id) idtest= (ID *)copy_texture((Tex *)id);
428                 else idtest= (ID *)add_texture("Tex");
429                 idtest->us--;
430         }
431         if(idtest!=id) {
432                 brush_texture_delete(brush);
433
434                 brush->mtex.tex= (Tex*)idtest;
435                 id_us_plus(idtest);
436
437                 return 1;
438         }
439
440         return 0;
441 }
442
443 int brush_texture_delete(Brush *brush)
444 {
445         if(brush->mtex.tex)
446                 brush->mtex.tex->id.us--;
447
448         return 1;
449 }
450
451 int brush_clone_image_set_nr(Brush *brush, int nr)
452 {
453         if(brush && nr > 0) {
454                 Image *ima= (Image*)BLI_findlink(&G.main->image, nr-1);
455
456                 if(ima) {
457                         brush_clone_image_delete(brush);
458                         brush->clone.image= ima;
459                         id_us_plus(&ima->id);
460                         brush->clone.offset[0]= brush->clone.offset[1]= 0.0f;
461
462                         return 1;
463                 }
464         }
465
466         return 0;
467 }
468
469 int brush_clone_image_delete(Brush *brush)
470 {
471         if (brush && brush->clone.image) {
472                 brush->clone.image->id.us--;
473                 brush->clone.image= NULL;
474                 return 1;
475         }
476
477         return 0;
478 }
479
480 void brush_check_exists(Brush **brush, const char *name)
481 {
482         if(*brush==NULL)
483                 brush_set_nr(brush, 1, name);
484 }
485
486 /* Brush Sampling */
487 void brush_sample_tex(Brush *brush, float *xy, float *rgba)
488 {
489         MTex *mtex= &brush->mtex;
490
491         if (mtex && mtex->tex) {
492                 float co[3], tin, tr, tg, tb, ta;
493                 int hasrgb;
494                 
495                 co[0]= xy[0]/(brush->size >> 1);
496                 co[1]= xy[1]/(brush->size >> 1);
497                 co[2]= 0.0f;
498
499                 hasrgb= externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
500
501                 if (hasrgb) {
502                         rgba[0]= tr;
503                         rgba[1]= tg;
504                         rgba[2]= tb;
505                         rgba[3]= ta;
506                 }
507                 else {
508                         rgba[0]= tin;
509                         rgba[1]= tin;
510                         rgba[2]= tin;
511                         rgba[3]= 1.0f;
512                 }
513         }
514         else if (rgba)
515                 rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
516 }
517
518
519 void brush_imbuf_new(Brush *brush, short flt, short texfall, int size, ImBuf **outbuf)
520 {
521         ImBuf *ibuf;
522         float xy[2], dist, rgba[4], *dstf;
523         int x, y, rowbytes, xoff, yoff, imbflag;
524         int maxsize = brush->size >> 1;
525         char *dst, crgb[3];
526
527         imbflag= (flt)? IB_rectfloat: IB_rect;
528         xoff = -size/2.0f + 0.5f;
529         yoff = -size/2.0f + 0.5f;
530         rowbytes= size*4;
531
532         if (*outbuf)
533                 ibuf= *outbuf;
534         else
535                 ibuf= IMB_allocImBuf(size, size, 32, imbflag, 0);
536
537         if (flt) {
538                 for (y=0; y < ibuf->y; y++) {
539                         dstf = ibuf->rect_float + y*rowbytes;
540
541                         for (x=0; x < ibuf->x; x++, dstf+=4) {
542                                 xy[0] = x + xoff;
543                                 xy[1] = y + yoff;
544
545                                 if (texfall == 0) {
546                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
547
548                                         VECCOPY(dstf, brush->rgb);
549                                         dstf[3]= brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize);
550                                 }
551                                 else if (texfall == 1) {
552                                         brush_sample_tex(brush, xy, dstf);
553                                 }
554                                 else {
555                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
556
557                                         brush_sample_tex(brush, xy, rgba);
558
559                                         dstf[0] = rgba[0]*brush->rgb[0];
560                                         dstf[1] = rgba[1]*brush->rgb[1];
561                                         dstf[2] = rgba[2]*brush->rgb[2];
562                                         dstf[3] = rgba[3]*brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize);
563                                 }
564                         }
565                 }
566         }
567         else {
568                 crgb[0]= FTOCHAR(brush->rgb[0]);
569                 crgb[1]= FTOCHAR(brush->rgb[1]);
570                 crgb[2]= FTOCHAR(brush->rgb[2]);
571
572                 for (y=0; y < ibuf->y; y++) {
573                         dst = (char*)ibuf->rect + y*rowbytes;
574
575                         for (x=0; x < ibuf->x; x++, dst+=4) {
576                                 xy[0] = x + xoff;
577                                 xy[1] = y + yoff;
578
579                                 if (texfall == 0) {
580                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
581
582                                         dst[0]= crgb[0];
583                                         dst[1]= crgb[1];
584                                         dst[2]= crgb[2];
585                                         dst[3]= FTOCHAR(brush->alpha*brush_curve_strength(brush, dist, maxsize));
586                                 }
587                                 else if (texfall == 1) {
588                                         brush_sample_tex(brush, xy, rgba);
589                                         dst[0]= FTOCHAR(rgba[0]);
590                                         dst[1]= FTOCHAR(rgba[1]);
591                                         dst[2]= FTOCHAR(rgba[2]);
592                                         dst[3]= FTOCHAR(rgba[3]);
593                                 }
594                                 else {
595                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
596
597                                         brush_sample_tex(brush, xy, rgba);
598                                         dst[0] = FTOCHAR(rgba[0]*brush->rgb[0]);
599                                         dst[1] = FTOCHAR(rgba[1]*brush->rgb[1]);
600                                         dst[2] = FTOCHAR(rgba[2]*brush->rgb[2]);
601                                         dst[3] = FTOCHAR(rgba[3]*brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize));
602                                 }
603                         }
604                 }
605         }
606
607         *outbuf= ibuf;
608 }
609
610 /* Brush Painting */
611
612 typedef struct BrushPainterCache {
613         short enabled;
614
615         int size;                       /* size override, if 0 uses brush->size */
616         short flt;                      /* need float imbuf? */
617         short texonly;          /* no alpha, color or fallof, only texture in imbuf */
618
619         int lastsize;
620         float lastalpha;
621         float lastjitter;
622
623         ImBuf *ibuf;
624         ImBuf *texibuf;
625         ImBuf *maskibuf;
626 } BrushPainterCache;
627
628 struct BrushPainter {
629         Brush *brush;
630
631         float lastmousepos[2];  /* mouse position of last paint call */
632
633         float accumdistance;    /* accumulated distance of brush since last paint op */
634         float lastpaintpos[2];  /* position of last paint op */
635         float startpaintpos[2]; /* position of first paint */
636
637         double accumtime;               /* accumulated time since last paint op (airbrush) */
638         double lasttime;                /* time of last update */
639
640         float lastpressure;
641
642         short firsttouch;               /* first paint op */
643
644         float startsize;
645         float startalpha;
646         float startjitter;
647         float startspacing;
648
649         BrushPainterCache cache;
650 };
651
652 BrushPainter *brush_painter_new(Brush *brush)
653 {
654         BrushPainter *painter= MEM_callocN(sizeof(BrushPainter), "BrushPainter");
655
656         painter->brush= brush;
657         painter->firsttouch= 1;
658         painter->cache.lastsize= -1; /* force ibuf create in refresh */
659
660         painter->startsize = brush->size;
661         painter->startalpha = brush->alpha;
662         painter->startjitter = brush->jitter;
663         painter->startspacing = brush->spacing;
664
665         return painter;
666 }
667
668 void brush_painter_require_imbuf(BrushPainter *painter, short flt, short texonly, int size)
669 {
670         if ((painter->cache.flt != flt) || (painter->cache.size != size) ||
671                 ((painter->cache.texonly != texonly) && texonly)) {
672                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
673                 if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
674                 painter->cache.ibuf= painter->cache.maskibuf= NULL;
675                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
676         }
677
678         if (painter->cache.flt != flt) {
679                 if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
680                 painter->cache.texibuf= NULL;
681                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
682         }
683
684         painter->cache.size= size;
685         painter->cache.flt= flt;
686         painter->cache.texonly= texonly;
687         painter->cache.enabled= 1;
688 }
689
690 void brush_painter_free(BrushPainter *painter)
691 {
692         Brush *brush = painter->brush;
693
694         brush->size = painter->startsize;
695         brush->alpha = painter->startalpha;
696         brush->jitter = painter->startjitter;
697         brush->spacing = painter->startspacing;
698
699         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
700         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
701         if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
702         MEM_freeN(painter);
703 }
704
705 static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf, int x, int y, int w, int h, int xt, int yt, float *pos)
706 {
707         Brush *brush= painter->brush;
708         ImBuf *ibuf, *maskibuf, *texibuf;
709         float *bf, *mf, *tf, *otf=NULL, xoff, yoff, xy[2], rgba[4];
710         char *b, *m, *t, *ot= NULL;
711         int dotexold, origx= x, origy= y;
712
713         xoff = -brush->size/2.0f + 0.5f;
714         yoff = -brush->size/2.0f + 0.5f;
715         xoff += (int)pos[0] - (int)painter->startpaintpos[0];
716         yoff += (int)pos[1] - (int)painter->startpaintpos[1];
717
718         ibuf = painter->cache.ibuf;
719         texibuf = painter->cache.texibuf;
720         maskibuf = painter->cache.maskibuf;
721
722         dotexold = (oldtexibuf != NULL);
723
724         if (painter->cache.flt) {
725                 for (; y < h; y++) {
726                         bf = ibuf->rect_float + (y*ibuf->x + origx)*4;
727                         tf = texibuf->rect_float + (y*texibuf->x + origx)*4;
728                         mf = maskibuf->rect_float + (y*maskibuf->x + origx)*4;
729
730                         if (dotexold)
731                                 otf = oldtexibuf->rect_float + ((y - origy + yt)*oldtexibuf->x + xt)*4;
732
733                         for (x=origx; x < w; x++, bf+=4, mf+=4, tf+=4) {
734                                 if (dotexold) {
735                                         VECCOPY(tf, otf);
736                                         tf[3] = otf[3];
737                                         otf += 4;
738                                 }
739                                 else {
740                                         xy[0] = x + xoff;
741                                         xy[1] = y + yoff;
742
743                                         brush_sample_tex(brush, xy, tf);
744                                 }
745
746                                 bf[0] = tf[0]*mf[0];
747                                 bf[1] = tf[1]*mf[1];
748                                 bf[2] = tf[2]*mf[2];
749                                 bf[3] = tf[3]*mf[3];
750                         }
751                 }
752         }
753         else {
754                 for (; y < h; y++) {
755                         b = (char*)ibuf->rect + (y*ibuf->x + origx)*4;
756                         t = (char*)texibuf->rect + (y*texibuf->x + origx)*4;
757                         m = (char*)maskibuf->rect + (y*maskibuf->x + origx)*4;
758
759                         if (dotexold)
760                                 ot = (char*)oldtexibuf->rect + ((y - origy + yt)*oldtexibuf->x + xt)*4;
761
762                         for (x=origx; x < w; x++, b+=4, m+=4, t+=4) {
763                                 if (dotexold) {
764                                         t[0] = ot[0];
765                                         t[1] = ot[1];
766                                         t[2] = ot[2];
767                                         t[3] = ot[3];
768                                         ot += 4;
769                                 }
770                                 else {
771                                         xy[0] = x + xoff;
772                                         xy[1] = y + yoff;
773
774                                         brush_sample_tex(brush, xy, rgba);
775                                         t[0]= FTOCHAR(rgba[0]);
776                                         t[1]= FTOCHAR(rgba[1]);
777                                         t[2]= FTOCHAR(rgba[2]);
778                                         t[3]= FTOCHAR(rgba[3]);
779                                 }
780
781                                 b[0] = t[0]*m[0]/255;
782                                 b[1] = t[1]*m[1]/255;
783                                 b[2] = t[2]*m[2]/255;
784                                 b[3] = t[3]*m[3]/255;
785                         }
786                 }
787         }
788 }
789
790 static void brush_painter_fixed_tex_partial_update(BrushPainter *painter, float *pos)
791 {
792         Brush *brush= painter->brush;
793         BrushPainterCache *cache= &painter->cache;
794         ImBuf *oldtexibuf, *ibuf;
795         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
796
797         imbflag= (cache->flt)? IB_rectfloat: IB_rect;
798         if (!cache->ibuf)
799                 cache->ibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
800         ibuf= cache->ibuf;
801
802         oldtexibuf= cache->texibuf;
803         cache->texibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
804
805         if (oldtexibuf) {
806                 srcx= srcy= 0;
807                 destx= (int)painter->lastpaintpos[0] - (int)pos[0];
808                 desty= (int)painter->lastpaintpos[1] - (int)pos[1];
809                 w= oldtexibuf->x;
810                 h= oldtexibuf->y;
811
812                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
813         }
814         else {
815                 srcx= srcy= 0;
816                 destx= desty= 0;
817                 w= h= 0;
818         }
819         
820         x1= destx;
821         y1= desty;
822         x2= destx+w;
823         y2= desty+h;
824
825         /* blend existing texture in new position */
826         if ((x1 < x2) && (y1 < y2))
827                 brush_painter_do_partial(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy, pos);
828
829         if (oldtexibuf)
830                 IMB_freeImBuf(oldtexibuf);
831
832         /* sample texture in new areas */
833         if ((0 < x1) && (0 < ibuf->y))
834                 brush_painter_do_partial(painter, NULL, 0, 0, x1, ibuf->y, 0, 0, pos);
835         if ((x2 < ibuf->x) && (0 < ibuf->y))
836                 brush_painter_do_partial(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0, pos);
837         if ((x1 < x2) && (0 < y1))
838                 brush_painter_do_partial(painter, NULL, x1, 0, x2, y1, 0, 0, pos);
839         if ((x1 < x2) && (y2 < ibuf->y))
840                 brush_painter_do_partial(painter, NULL, x1, y2, x2, ibuf->y, 0, 0, pos);
841 }
842
843 static void brush_painter_refresh_cache(BrushPainter *painter, float *pos)
844 {
845         Brush *brush= painter->brush;
846         BrushPainterCache *cache= &painter->cache;
847         MTex *mtex= &brush->mtex;
848         int size;
849         short flt;
850
851         if ((brush->size != cache->lastsize) || (brush->alpha != cache->lastalpha)
852                 || (brush->jitter != cache->lastjitter)) {
853                 if (cache->ibuf) {
854                         IMB_freeImBuf(cache->ibuf);
855                         cache->ibuf= NULL;
856                 }
857                 if (cache->maskibuf) {
858                         IMB_freeImBuf(cache->maskibuf);
859                         cache->maskibuf= NULL;
860                 }
861
862                 flt= cache->flt;
863                 size= (cache->size)? cache->size: brush->size;
864
865                 if (!(mtex && mtex->tex) || (mtex->tex->type==0)) {
866                         brush_imbuf_new(brush, flt, 0, size, &cache->ibuf);
867                 }
868                 else if (brush->flag & BRUSH_FIXED_TEX) {
869                         brush_imbuf_new(brush, flt, 0, size, &cache->maskibuf);
870                         brush_painter_fixed_tex_partial_update(painter, pos);
871                 }
872                 else
873                         brush_imbuf_new(brush, flt, 2, size, &cache->ibuf);
874
875                 cache->lastsize= brush->size;
876                 cache->lastalpha= brush->alpha;
877                 cache->lastjitter= brush->jitter;
878         }
879         else if ((brush->flag & BRUSH_FIXED_TEX) && mtex && mtex->tex) {
880                 int dx = (int)painter->lastpaintpos[0] - (int)pos[0];
881                 int dy = (int)painter->lastpaintpos[1] - (int)pos[1];
882
883                 if ((dx != 0) || (dy != 0))
884                         brush_painter_fixed_tex_partial_update(painter, pos);
885         }
886 }
887
888 void brush_painter_break_stroke(BrushPainter *painter)
889 {
890         painter->firsttouch= 1;
891 }
892
893 static void brush_apply_pressure(BrushPainter *painter, Brush *brush, float pressure)
894 {
895         if (brush->flag & BRUSH_ALPHA_PRESSURE) 
896                 brush->alpha = MAX2(0.0, painter->startalpha*pressure);
897         if (brush->flag & BRUSH_SIZE_PRESSURE)
898                 brush->size = MAX2(1.0, painter->startsize*pressure);
899         if (brush->flag & BRUSH_JITTER_PRESSURE)
900                 brush->jitter = MAX2(0.0, painter->startjitter*pressure);
901         if (brush->flag & BRUSH_SPACING_PRESSURE)
902                 brush->spacing = MAX2(1.0, painter->startspacing*(1.5f-pressure));
903 }
904
905 void brush_jitter_pos(Brush *brush, float *pos, float *jitterpos)
906 {
907         if(brush->jitter){
908                 float rand_pos[2];
909
910                 // find random position within a circle of diameter 1
911                 do {
912                         rand_pos[0] = BLI_frand()-0.5f;
913                         rand_pos[1] = BLI_frand()-0.5f;
914                 } while (len_v2(rand_pos) > 0.5f);
915
916                 jitterpos[0] = pos[0] + 2*rand_pos[0]*brush->size*brush->jitter;
917                 jitterpos[1] = pos[1] + 2*rand_pos[1]*brush->size*brush->jitter;
918         }
919         else {
920                 VECCOPY2D(jitterpos, pos);
921         }
922 }
923
924 int brush_painter_paint(BrushPainter *painter, BrushFunc func, float *pos, double time, float pressure, void *user)
925 {
926         Brush *brush= painter->brush;
927         int totpaintops= 0;
928
929         if (pressure == 0.0f) {
930                 if(painter->lastpressure) // XXX - hack, operator misses
931                         pressure= painter->lastpressure;
932                 else
933                         pressure = 1.0f;        /* zero pressure == not using tablet */
934         }
935         if (painter->firsttouch) {
936                 /* paint exactly once on first touch */
937                 painter->startpaintpos[0]= pos[0];
938                 painter->startpaintpos[1]= pos[1];
939
940                 brush_apply_pressure(painter, brush, pressure);
941                 if (painter->cache.enabled)
942                         brush_painter_refresh_cache(painter, pos);
943                 totpaintops += func(user, painter->cache.ibuf, pos, pos);
944                 
945                 painter->lasttime= time;
946                 painter->firsttouch= 0;
947                 painter->lastpaintpos[0]= pos[0];
948                 painter->lastpaintpos[1]= pos[1];
949         }
950 #if 0
951         else if (painter->brush->flag & BRUSH_AIRBRUSH) {
952                 float spacing, step, paintpos[2], dmousepos[2], len;
953                 double starttime, curtime= time;
954
955                 /* compute brush spacing adapted to brush size */
956                 spacing= brush->rate; //brush->size*brush->spacing*0.01f;
957
958                 /* setup starting time, direction vector and accumulated time */
959                 starttime= painter->accumtime;
960                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
961                 len= normalize_v2(dmousepos);
962                 painter->accumtime += curtime - painter->lasttime;
963
964                 /* do paint op over unpainted time distance */
965                 while (painter->accumtime >= spacing) {
966                         step= (spacing - starttime)*len;
967                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
968                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
969
970                         if (painter->cache.enabled)
971                                 brush_painter_refresh_cache(painter);
972                         totpaintops += func(user, painter->cache.ibuf,
973                                 painter->lastpaintpos, paintpos);
974
975                         painter->lastpaintpos[0]= paintpos[0];
976                         painter->lastpaintpos[1]= paintpos[1];
977                         painter->accumtime -= spacing;
978                         starttime -= spacing;
979                 }
980                 
981                 painter->lasttime= curtime;
982         }
983 #endif
984         else {
985                 float startdistance, spacing, step, paintpos[2], dmousepos[2], finalpos[2];
986                 float t, len, press;
987
988                 /* compute brush spacing adapted to brush size, spacing may depend
989                    on pressure, so update it */
990                 brush_apply_pressure(painter, brush, painter->lastpressure);
991                 spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
992
993                 /* setup starting distance, direction vector and accumulated distance */
994                 startdistance= painter->accumdistance;
995                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
996                 len= normalize_v2(dmousepos);
997                 painter->accumdistance += len;
998
999                 /* do paint op over unpainted distance */
1000                 while ((len > 0.0f) && (painter->accumdistance >= spacing)) {
1001                         step= spacing - startdistance;
1002                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
1003                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
1004
1005                         t = step/len;
1006                         press= (1.0f-t)*painter->lastpressure + t*pressure;
1007                         brush_apply_pressure(painter, brush, press);
1008                         spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
1009
1010                         brush_jitter_pos(brush, paintpos, finalpos);
1011
1012                         if (painter->cache.enabled)
1013                                 brush_painter_refresh_cache(painter, finalpos);
1014
1015                         totpaintops +=
1016                                 func(user, painter->cache.ibuf, painter->lastpaintpos, finalpos);
1017
1018                         painter->lastpaintpos[0]= paintpos[0];
1019                         painter->lastpaintpos[1]= paintpos[1];
1020                         painter->accumdistance -= spacing;
1021                         startdistance -= spacing;
1022                 }
1023
1024                 /* do airbrush paint ops, based on the number of paint ops left over
1025                    from regular painting. this is a temporary solution until we have
1026                    accurate time stamps for mouse move events */
1027                 if (brush->flag & BRUSH_AIRBRUSH) {
1028                         double curtime= time;
1029                         double painttime= brush->rate*totpaintops;
1030
1031                         painter->accumtime += curtime - painter->lasttime;
1032                         if (painter->accumtime <= painttime)
1033                                 painter->accumtime= 0.0;
1034                         else
1035                                 painter->accumtime -= painttime;
1036
1037                         while (painter->accumtime >= brush->rate) {
1038                                 brush_apply_pressure(painter, brush, pressure);
1039
1040                                 brush_jitter_pos(brush, pos, finalpos);
1041
1042                                 if (painter->cache.enabled)
1043                                         brush_painter_refresh_cache(painter, finalpos);
1044
1045                                 totpaintops +=
1046                                         func(user, painter->cache.ibuf, painter->lastmousepos, finalpos);
1047                                 painter->accumtime -= brush->rate;
1048                         }
1049
1050                         painter->lasttime= curtime;
1051                 }
1052         }
1053
1054         painter->lastmousepos[0]= pos[0];
1055         painter->lastmousepos[1]= pos[1];
1056         painter->lastpressure= pressure;
1057
1058         brush->alpha = painter->startalpha;
1059         brush->size = painter->startsize;
1060         brush->jitter = painter->startjitter;
1061         brush->spacing = painter->startspacing;
1062
1063         return totpaintops;
1064 }
1065
1066 /* Uses the brush curve control to find a strength value between 0 and 1 */
1067 float brush_curve_strength_clamp(Brush *br, float p, const float len)
1068 {
1069         if(p >= len)    return 0;
1070         else                    p= p/len;
1071
1072         p= curvemapping_evaluateF(br->curve, 0, p);
1073         if(p < 0.0)                     p= 0.0f;
1074         else if(p > 1.0f)       p= 1.0f;
1075         return p;
1076 }
1077 /* same as above but can return negative values if the curve enables
1078  * used for sculpt only */
1079 float brush_curve_strength(Brush *br, float p, const float len)
1080 {
1081     if(p >= len)
1082         p= 1.0f;
1083     else
1084         p= p/len;
1085
1086     return curvemapping_evaluateF(br->curve, 0, p);
1087 }
1088
1089 /* TODO: should probably be unified with BrushPainter stuff? */
1090 unsigned int *brush_gen_texture_cache(Brush *br, int half_side)
1091 {
1092         unsigned int *texcache = NULL;
1093         MTex *mtex = &br->mtex;
1094         TexResult texres;
1095         int hasrgb, ix, iy;
1096         int side = half_side * 2;
1097
1098         memset(&texres, 0, sizeof(TexResult));
1099         
1100         if(mtex->tex) {
1101                 float x, y, step = 2.0 / side, co[3];
1102
1103                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1104
1105                 BKE_image_get_ibuf(mtex->tex->ima, NULL);
1106                 
1107                 /*do normalized cannonical view coords for texture*/
1108                 for (y=-1.0, iy=0; iy<side; iy++, y += step) {
1109                         for (x=-1.0, ix=0; ix<side; ix++, x += step) {
1110                                 co[0]= x;
1111                                 co[1]= y;
1112                                 co[2]= 0.0f;
1113                                 
1114                                 /* This is copied from displace modifier code */
1115                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres);
1116                         
1117                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1118                                  * intensity, so calculate one (formula from do_material_tex).
1119                                  * if the texture didn't give an RGB value, copy the intensity across
1120                                  */
1121                                 if(hasrgb & TEX_RGB)
1122                                         texres.tin = (0.35 * texres.tr + 0.45 *
1123                                                                   texres.tg + 0.2 * texres.tb);
1124
1125                                 texres.tin = texres.tin * 255.0;
1126                                 ((char*)texcache)[(iy*side+ix)*4] = (char)texres.tin;
1127                                 ((char*)texcache)[(iy*side+ix)*4+1] = (char)texres.tin;
1128                                 ((char*)texcache)[(iy*side+ix)*4+2] = (char)texres.tin;
1129                                 ((char*)texcache)[(iy*side+ix)*4+3] = (char)texres.tin;
1130                         }
1131                 }
1132         }
1133
1134         return texcache;
1135 }
1136
1137 /**** Radial Control ****/
1138 static struct ImBuf *brush_gen_radial_control_imbuf(Brush *br)
1139 {
1140         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1141         unsigned int *texcache;
1142         int side = 128;
1143         int half = side / 2;
1144         int i, j;
1145
1146         texcache = brush_gen_texture_cache(br, half);
1147         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1148         im->x = im->y = side;
1149
1150         for(i=0; i<side; ++i) {
1151                 for(j=0; j<side; ++j) {
1152                         float magn= sqrt(pow(i - half, 2) + pow(j - half, 2));
1153                         im->rect_float[i*side + j]= brush_curve_strength_clamp(br, magn, half);
1154                 }
1155         }
1156
1157         /* Modulate curve with texture */
1158         if(texcache) {
1159                 for(i=0; i<side; ++i) {
1160                         for(j=0; j<side; ++j) {
1161                                 const int col= texcache[i*side+j];
1162                                 im->rect_float[i*side+j]*= (((char*)&col)[0]+((char*)&col)[1]+((char*)&col)[2])/3.0f/255.0f;
1163                         }
1164                 }
1165
1166                 MEM_freeN(texcache);
1167         }
1168
1169         return im;
1170 }
1171
1172 void brush_radial_control_invoke(wmOperator *op, Brush *br, float size_weight)
1173 {
1174         int mode = RNA_int_get(op->ptr, "mode");
1175         float original_value= 0;
1176
1177         if(mode == WM_RADIALCONTROL_SIZE)
1178                 original_value = sculpt_get_brush_size(br) * size_weight;
1179         else if(mode == WM_RADIALCONTROL_STRENGTH)
1180                 original_value = sculpt_get_brush_alpha(br);
1181         else if(mode == WM_RADIALCONTROL_ANGLE) {
1182                 MTex *mtex = brush_active_texture(br);
1183                 if(mtex)
1184                         original_value = mtex->rot;
1185         }
1186
1187         RNA_float_set(op->ptr, "initial_value", original_value);
1188         op->customdata = brush_gen_radial_control_imbuf(br);
1189 }
1190
1191 int brush_radial_control_exec(wmOperator *op, Brush *br, float size_weight)
1192 {
1193         int mode = RNA_int_get(op->ptr, "mode");
1194         float new_value = RNA_float_get(op->ptr, "new_value");
1195         const float conv = 0.017453293;
1196
1197         if(mode == WM_RADIALCONTROL_SIZE)
1198                 if (sculpt_get_lock_brush_size(br)) {
1199                         float initial_value = RNA_float_get(op->ptr, "initial_value");
1200                         const float unprojected_radius = sculpt_get_brush_unprojected_radius(br);
1201                         sculpt_set_brush_unprojected_radius(br, unprojected_radius * new_value/initial_value * size_weight);
1202                 }
1203                 else
1204                         sculpt_set_brush_size(br, new_value * size_weight);
1205         else if(mode == WM_RADIALCONTROL_STRENGTH)
1206                 sculpt_set_brush_alpha(br, new_value);
1207         else if(mode == WM_RADIALCONTROL_ANGLE) {
1208                 MTex *mtex = brush_active_texture(br);
1209                 if(mtex)
1210                         mtex->rot = new_value * conv;
1211         }
1212
1213         return OPERATOR_FINISHED;
1214 }