* Removed tablet pressure sensitive number field widget scrubbing, wasn't that useful...
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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_image_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_texture_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_windowmanager_types.h"
42
43 #include "RNA_access.h"
44
45 #include "BLI_math.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_rand.h"
48
49 #include "BKE_brush.h"
50 #include "BKE_colortools.h"
51 #include "BKE_global.h"
52 #include "BKE_image.h"
53 #include "BKE_library.h"
54 #include "BKE_main.h"
55 #include "BKE_paint.h"
56 #include "BKE_texture.h"
57 #include "BKE_utildefines.h"
58
59 #include "IMB_imbuf.h"
60 #include "IMB_imbuf_types.h"
61
62 #include "RE_render_ext.h" /* externtex */
63 #include "RE_shader_ext.h"
64
65 /* Datablock add/copy/free/make_local */
66
67 Brush *add_brush(const char *name)
68 {
69         Brush *brush;
70
71         brush= alloc_libblock(&G.main->brush, ID_BR, name);
72
73         brush->rgb[0]= 1.0f;
74         brush->rgb[1]= 1.0f;
75         brush->rgb[2]= 1.0f;
76         brush->alpha= 0.2f;
77         brush->size= 25;
78         brush->spacing= 10.0f;
79         brush->smooth_stroke_radius= 75;
80         brush->smooth_stroke_factor= 0.9;
81         brush->rate= 0.1f;
82         brush->jitter= 0.0f;
83         brush->clone.alpha= 0.5;
84         brush->sculpt_tool = SCULPT_TOOL_DRAW;
85
86         brush_curve_preset(brush, BRUSH_PRESET_SMOOTH);
87
88         /* enable fake user by default */
89         brush->id.flag |= LIB_FAKEUSER;
90         brush_toggled_fake_user(brush);
91         
92         return brush;   
93 }
94
95 Brush *copy_brush(Brush *brush)
96 {
97         Brush *brushn;
98         MTex *mtex;
99         int a;
100         
101         brushn= copy_libblock(brush);
102
103         for(a=0; a<MAX_MTEX; a++) {
104                 mtex= brush->mtex[a];
105                 if(mtex) {
106                         brushn->mtex[a]= MEM_dupallocN(mtex);
107                         if(mtex->tex) id_us_plus((ID*)mtex->tex);
108                 }
109         }
110
111         brushn->curve= curvemapping_copy(brush->curve);
112
113         /* enable fake user by default */
114         if (!(brushn->id.flag & LIB_FAKEUSER)) {
115                 brushn->id.flag |= LIB_FAKEUSER;
116                 brush_toggled_fake_user(brushn);
117         }
118         
119         return brushn;
120 }
121
122 /* not brush itself */
123 void free_brush(Brush *brush)
124 {
125         MTex *mtex;
126         int a;
127
128         for(a=0; a<MAX_MTEX; a++) {
129                 mtex= brush->mtex[a];
130                 if(mtex) {
131                         if(mtex->tex) mtex->tex->id.us--;
132                         MEM_freeN(mtex);
133                 }
134         }
135
136         curvemapping_free(brush->curve);
137 }
138
139 void make_local_brush(Brush *brush)
140 {
141         /* - only lib users: do nothing
142                 * - only local users: set flag
143                 * - mixed: make copy
144                 */
145         
146         Brush *brushn;
147         Scene *scene;
148         int local= 0, lib= 0;
149
150         if(brush->id.lib==0) return;
151
152         if(brush->clone.image) {
153                 /* special case: ima always local immediately */
154                 brush->clone.image->id.lib= 0;
155                 brush->clone.image->id.flag= LIB_LOCAL;
156                 new_id(0, (ID *)brush->clone.image, 0);
157         }
158
159         for(scene= G.main->scene.first; scene; scene=scene->id.next)
160                 if(paint_brush(&scene->toolsettings->imapaint.paint)==brush) {
161                         if(scene->id.lib) lib= 1;
162                         else local= 1;
163                 }
164         
165         if(local && lib==0) {
166                 brush->id.lib= 0;
167                 brush->id.flag= LIB_LOCAL;
168                 new_id(0, (ID *)brush, 0);
169
170                 /* enable fake user by default */
171                 if (!(brush->id.flag & LIB_FAKEUSER)) {
172                         brush->id.flag |= LIB_FAKEUSER;
173                         brush_toggled_fake_user(brush);
174                 }
175         }
176         else if(local && lib) {
177                 brushn= copy_brush(brush);
178                 brushn->id.us= 1; /* only keep fake user */
179                 brushn->id.flag |= LIB_FAKEUSER;
180                 
181                 for(scene= G.main->scene.first; scene; scene=scene->id.next)
182                         if(paint_brush(&scene->toolsettings->imapaint.paint)==brush)
183                                 if(scene->id.lib==0) {
184                                         paint_brush_set(&scene->toolsettings->imapaint.paint, brushn);
185                                         brushn->id.us++;
186                                         brush->id.us--;
187                                 }
188         }
189 }
190
191 /* Library Operations */
192
193 int brush_set_nr(Brush **current_brush, int nr, const char *name)
194 {
195         ID *idtest, *id;
196         
197         id= (ID*)(*current_brush);
198         idtest= (ID*)BLI_findlink(&G.main->brush, nr-1);
199         
200         if(idtest==0) { /* new brush */
201                 if(id) idtest= (ID *)copy_brush((Brush *)id);
202                 else idtest= (ID *)add_brush(name);
203                 idtest->us--;
204         }
205         if(idtest!=id) {
206                 brush_delete(current_brush);
207                 *current_brush= (Brush *)idtest;
208                 id_us_plus(idtest);
209
210                 return 1;
211         }
212
213         return 0;
214 }
215
216 int brush_delete(Brush **current_brush)
217 {
218         if (*current_brush) {
219                 (*current_brush)->id.us--;
220                 *current_brush= NULL;
221
222                 return 1;
223         }
224
225         return 0;
226 }
227
228 void brush_toggled_fake_user(Brush *brush)
229 {
230         ID *id= (ID*)brush;
231         if(id) {
232                 if(id->flag & LIB_FAKEUSER) {
233                         id_us_plus(id);
234                 } else {
235                         id->us--;
236                 }
237         }
238 }
239
240 void brush_curve_preset(Brush *b, BrushCurvePreset preset)
241 {
242         CurveMap *cm = NULL;
243
244         if(!b->curve)
245                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
246
247         cm = b->curve->cm;
248
249         if(cm->curve)
250                 MEM_freeN(cm->curve);
251
252         if(preset == BRUSH_PRESET_SHARP)
253                 cm->totpoint= 3;
254         if(preset == BRUSH_PRESET_SMOOTH)
255                 cm->totpoint= 6;
256         if(preset == BRUSH_PRESET_MAX)
257                 cm->totpoint= 2;
258
259
260         cm->curve= MEM_callocN(cm->totpoint*sizeof(CurveMapPoint), "curve points");
261         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
262
263         if(preset == BRUSH_PRESET_SHARP) {
264                 cm->curve[0].x= 0;
265                 cm->curve[0].y= 1;
266                 cm->curve[1].x= 0.33;
267                 cm->curve[1].y= 0.33;
268                 cm->curve[2].x= 1;
269                 cm->curve[2].y= 0;
270         }
271         else if(preset == BRUSH_PRESET_SMOOTH) {
272                 cm->curve[0].x= 0;
273                 cm->curve[0].y= 1;
274                 cm->curve[1].x= 0.1;
275                 cm->curve[1].y= 0.97553;
276                 cm->curve[2].x= 0.3;
277                 cm->curve[2].y= 0.79389;
278                 cm->curve[3].x= 0.9;
279                 cm->curve[3].y= 0.02447;
280                 cm->curve[4].x= 0.7;
281                 cm->curve[4].y= 0.20611;
282                 cm->curve[5].x= 1;
283                 cm->curve[5].y= 0;
284         }
285         else if(preset == BRUSH_PRESET_MAX) {
286                 cm->curve[0].x= 0;
287                 cm->curve[0].y= 1;
288                 cm->curve[1].x= 1;
289                 cm->curve[1].y= 1;
290         }
291
292         curvemapping_changed(b->curve, 0);
293 }
294
295 static MTex *brush_active_texture(Brush *brush)
296 {
297         if(brush && brush->texact >= 0)
298                 return brush->mtex[brush->texact];
299         return NULL;
300 }
301
302 int brush_texture_set_nr(Brush *brush, int nr)
303 {
304         ID *idtest, *id=NULL;
305
306         if(brush->mtex[brush->texact])
307                 id= (ID *)brush->mtex[brush->texact]->tex;
308
309         idtest= (ID*)BLI_findlink(&G.main->tex, nr-1);
310         if(idtest==0) { /* new tex */
311                 if(id) idtest= (ID *)copy_texture((Tex *)id);
312                 else idtest= (ID *)add_texture("Tex");
313                 idtest->us--;
314         }
315         if(idtest!=id) {
316                 brush_texture_delete(brush);
317
318                 if(brush->mtex[brush->texact]==NULL) {
319                         brush->mtex[brush->texact]= add_mtex();
320                         brush->mtex[brush->texact]->r = 1.0f;
321                         brush->mtex[brush->texact]->g = 1.0f;
322                         brush->mtex[brush->texact]->b = 1.0f;
323                 }
324                 brush->mtex[brush->texact]->tex= (Tex*)idtest;
325                 id_us_plus(idtest);
326
327                 return 1;
328         }
329
330         return 0;
331 }
332
333 int brush_texture_delete(Brush *brush)
334 {
335         if(brush->mtex[brush->texact]) {
336                 if(brush->mtex[brush->texact]->tex)
337                         brush->mtex[brush->texact]->tex->id.us--;
338                 MEM_freeN(brush->mtex[brush->texact]);
339                 brush->mtex[brush->texact]= NULL;
340
341                 return 1;
342         }
343
344         return 0;
345 }
346
347 int brush_clone_image_set_nr(Brush *brush, int nr)
348 {
349         if(brush && nr > 0) {
350                 Image *ima= (Image*)BLI_findlink(&G.main->image, nr-1);
351
352                 if(ima) {
353                         brush_clone_image_delete(brush);
354                         brush->clone.image= ima;
355                         id_us_plus(&ima->id);
356                         brush->clone.offset[0]= brush->clone.offset[1]= 0.0f;
357
358                         return 1;
359                 }
360         }
361
362         return 0;
363 }
364
365 int brush_clone_image_delete(Brush *brush)
366 {
367         if (brush && brush->clone.image) {
368                 brush->clone.image->id.us--;
369                 brush->clone.image= NULL;
370                 return 1;
371         }
372
373         return 0;
374 }
375
376 void brush_check_exists(Brush **brush, const char *name)
377 {
378         if(*brush==NULL)
379                 brush_set_nr(brush, 1, name);
380 }
381
382 /* Brush Sampling */
383 void brush_sample_tex(Brush *brush, float *xy, float *rgba)
384 {
385         MTex *mtex= brush->mtex[brush->texact];
386
387         if (mtex && mtex->tex) {
388                 float co[3], tin, tr, tg, tb, ta;
389                 int hasrgb;
390                 
391                 co[0]= xy[0]/(brush->size >> 1);
392                 co[1]= xy[1]/(brush->size >> 1);
393                 co[2]= 0.0f;
394
395                 hasrgb= externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
396
397                 if (hasrgb) {
398                         rgba[0]= tr;
399                         rgba[1]= tg;
400                         rgba[2]= tb;
401                         rgba[3]= ta;
402                 }
403                 else {
404                         rgba[0]= tin;
405                         rgba[1]= tin;
406                         rgba[2]= tin;
407                         rgba[3]= 1.0f;
408                 }
409         }
410         else if (rgba)
411                 rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
412 }
413
414
415 void brush_imbuf_new(Brush *brush, short flt, short texfall, int size, ImBuf **outbuf)
416 {
417         ImBuf *ibuf;
418         float xy[2], dist, rgba[4], *dstf;
419         int x, y, rowbytes, xoff, yoff, imbflag;
420         int maxsize = brush->size >> 1;
421         char *dst, crgb[3];
422
423         imbflag= (flt)? IB_rectfloat: IB_rect;
424         xoff = -size/2.0f + 0.5f;
425         yoff = -size/2.0f + 0.5f;
426         rowbytes= size*4;
427
428         if (*outbuf)
429                 ibuf= *outbuf;
430         else
431                 ibuf= IMB_allocImBuf(size, size, 32, imbflag, 0);
432
433         if (flt) {
434                 for (y=0; y < ibuf->y; y++) {
435                         dstf = ibuf->rect_float + y*rowbytes;
436
437                         for (x=0; x < ibuf->x; x++, dstf+=4) {
438                                 xy[0] = x + xoff;
439                                 xy[1] = y + yoff;
440
441                                 if (texfall == 0) {
442                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
443
444                                         VECCOPY(dstf, brush->rgb);
445                                         dstf[3]= brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize);
446                                 }
447                                 else if (texfall == 1) {
448                                         brush_sample_tex(brush, xy, dstf);
449                                 }
450                                 else {
451                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
452
453                                         brush_sample_tex(brush, xy, rgba);
454
455                                         dstf[0] = rgba[0]*brush->rgb[0];
456                                         dstf[1] = rgba[1]*brush->rgb[1];
457                                         dstf[2] = rgba[2]*brush->rgb[2];
458                                         dstf[3] = rgba[3]*brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize);
459                                 }
460                         }
461                 }
462         }
463         else {
464                 crgb[0]= FTOCHAR(brush->rgb[0]);
465                 crgb[1]= FTOCHAR(brush->rgb[1]);
466                 crgb[2]= FTOCHAR(brush->rgb[2]);
467
468                 for (y=0; y < ibuf->y; y++) {
469                         dst = (char*)ibuf->rect + y*rowbytes;
470
471                         for (x=0; x < ibuf->x; x++, dst+=4) {
472                                 xy[0] = x + xoff;
473                                 xy[1] = y + yoff;
474
475                                 if (texfall == 0) {
476                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
477
478                                         dst[0]= crgb[0];
479                                         dst[1]= crgb[1];
480                                         dst[2]= crgb[2];
481                                         dst[3]= FTOCHAR(brush->alpha*brush_curve_strength(brush, dist, maxsize));
482                                 }
483                                 else if (texfall == 1) {
484                                         brush_sample_tex(brush, xy, rgba);
485                                         dst[0]= FTOCHAR(rgba[0]);
486                                         dst[1]= FTOCHAR(rgba[1]);
487                                         dst[2]= FTOCHAR(rgba[2]);
488                                         dst[3]= FTOCHAR(rgba[3]);
489                                 }
490                                 else {
491                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
492
493                                         brush_sample_tex(brush, xy, rgba);
494                                         dst[0] = FTOCHAR(rgba[0]*brush->rgb[0]);
495                                         dst[1] = FTOCHAR(rgba[1]*brush->rgb[1]);
496                                         dst[2] = FTOCHAR(rgba[2]*brush->rgb[2]);
497                                         dst[3] = FTOCHAR(rgba[3]*brush->alpha*brush_curve_strength_clamp(brush, dist, maxsize));
498                                 }
499                         }
500                 }
501         }
502
503         *outbuf= ibuf;
504 }
505
506 /* Brush Painting */
507
508 typedef struct BrushPainterCache {
509         short enabled;
510
511         int size;                       /* size override, if 0 uses brush->size */
512         short flt;                      /* need float imbuf? */
513         short texonly;          /* no alpha, color or fallof, only texture in imbuf */
514
515         int lastsize;
516         float lastalpha;
517         float lastjitter;
518
519         ImBuf *ibuf;
520         ImBuf *texibuf;
521         ImBuf *maskibuf;
522 } BrushPainterCache;
523
524 struct BrushPainter {
525         Brush *brush;
526
527         float lastmousepos[2];  /* mouse position of last paint call */
528
529         float accumdistance;    /* accumulated distance of brush since last paint op */
530         float lastpaintpos[2];  /* position of last paint op */
531         float startpaintpos[2]; /* position of first paint */
532
533         double accumtime;               /* accumulated time since last paint op (airbrush) */
534         double lasttime;                /* time of last update */
535
536         float lastpressure;
537
538         short firsttouch;               /* first paint op */
539
540         float startsize;
541         float startalpha;
542         float startjitter;
543         float startspacing;
544
545         BrushPainterCache cache;
546 };
547
548 BrushPainter *brush_painter_new(Brush *brush)
549 {
550         BrushPainter *painter= MEM_callocN(sizeof(BrushPainter), "BrushPainter");
551
552         painter->brush= brush;
553         painter->firsttouch= 1;
554         painter->cache.lastsize= -1; /* force ibuf create in refresh */
555
556         painter->startsize = brush->size;
557         painter->startalpha = brush->alpha;
558         painter->startjitter = brush->jitter;
559         painter->startspacing = brush->spacing;
560
561         return painter;
562 }
563
564 void brush_painter_require_imbuf(BrushPainter *painter, short flt, short texonly, int size)
565 {
566         if ((painter->cache.flt != flt) || (painter->cache.size != size) ||
567                 ((painter->cache.texonly != texonly) && texonly)) {
568                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
569                 if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
570                 painter->cache.ibuf= painter->cache.maskibuf= NULL;
571                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
572         }
573
574         if (painter->cache.flt != flt) {
575                 if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
576                 painter->cache.texibuf= NULL;
577                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
578         }
579
580         painter->cache.size= size;
581         painter->cache.flt= flt;
582         painter->cache.texonly= texonly;
583         painter->cache.enabled= 1;
584 }
585
586 void brush_painter_free(BrushPainter *painter)
587 {
588         Brush *brush = painter->brush;
589
590         brush->size = painter->startsize;
591         brush->alpha = painter->startalpha;
592         brush->jitter = painter->startjitter;
593         brush->spacing = painter->startspacing;
594
595         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
596         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
597         if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
598         MEM_freeN(painter);
599 }
600
601 static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf, int x, int y, int w, int h, int xt, int yt, float *pos)
602 {
603         Brush *brush= painter->brush;
604         ImBuf *ibuf, *maskibuf, *texibuf;
605         float *bf, *mf, *tf, *otf=NULL, xoff, yoff, xy[2], rgba[4];
606         char *b, *m, *t, *ot= NULL;
607         int dotexold, origx= x, origy= y;
608
609         xoff = -brush->size/2.0f + 0.5f;
610         yoff = -brush->size/2.0f + 0.5f;
611         xoff += (int)pos[0] - (int)painter->startpaintpos[0];
612         yoff += (int)pos[1] - (int)painter->startpaintpos[1];
613
614         ibuf = painter->cache.ibuf;
615         texibuf = painter->cache.texibuf;
616         maskibuf = painter->cache.maskibuf;
617
618         dotexold = (oldtexibuf != NULL);
619
620         if (painter->cache.flt) {
621                 for (; y < h; y++) {
622                         bf = ibuf->rect_float + (y*ibuf->x + origx)*4;
623                         tf = texibuf->rect_float + (y*texibuf->x + origx)*4;
624                         mf = maskibuf->rect_float + (y*maskibuf->x + origx)*4;
625
626                         if (dotexold)
627                                 otf = oldtexibuf->rect_float + ((y - origy + yt)*oldtexibuf->x + xt)*4;
628
629                         for (x=origx; x < w; x++, bf+=4, mf+=4, tf+=4) {
630                                 if (dotexold) {
631                                         VECCOPY(tf, otf);
632                                         tf[3] = otf[3];
633                                         otf += 4;
634                                 }
635                                 else {
636                                         xy[0] = x + xoff;
637                                         xy[1] = y + yoff;
638
639                                         brush_sample_tex(brush, xy, tf);
640                                 }
641
642                                 bf[0] = tf[0]*mf[0];
643                                 bf[1] = tf[1]*mf[1];
644                                 bf[2] = tf[2]*mf[2];
645                                 bf[3] = tf[3]*mf[3];
646                         }
647                 }
648         }
649         else {
650                 for (; y < h; y++) {
651                         b = (char*)ibuf->rect + (y*ibuf->x + origx)*4;
652                         t = (char*)texibuf->rect + (y*texibuf->x + origx)*4;
653                         m = (char*)maskibuf->rect + (y*maskibuf->x + origx)*4;
654
655                         if (dotexold)
656                                 ot = (char*)oldtexibuf->rect + ((y - origy + yt)*oldtexibuf->x + xt)*4;
657
658                         for (x=origx; x < w; x++, b+=4, m+=4, t+=4) {
659                                 if (dotexold) {
660                                         t[0] = ot[0];
661                                         t[1] = ot[1];
662                                         t[2] = ot[2];
663                                         t[3] = ot[3];
664                                         ot += 4;
665                                 }
666                                 else {
667                                         xy[0] = x + xoff;
668                                         xy[1] = y + yoff;
669
670                                         brush_sample_tex(brush, xy, rgba);
671                                         t[0]= FTOCHAR(rgba[0]);
672                                         t[1]= FTOCHAR(rgba[1]);
673                                         t[2]= FTOCHAR(rgba[2]);
674                                         t[3]= FTOCHAR(rgba[3]);
675                                 }
676
677                                 b[0] = t[0]*m[0]/255;
678                                 b[1] = t[1]*m[1]/255;
679                                 b[2] = t[2]*m[2]/255;
680                                 b[3] = t[3]*m[3]/255;
681                         }
682                 }
683         }
684 }
685
686 static void brush_painter_fixed_tex_partial_update(BrushPainter *painter, float *pos)
687 {
688         Brush *brush= painter->brush;
689         BrushPainterCache *cache= &painter->cache;
690         ImBuf *oldtexibuf, *ibuf;
691         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
692
693         imbflag= (cache->flt)? IB_rectfloat: IB_rect;
694         if (!cache->ibuf)
695                 cache->ibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
696         ibuf= cache->ibuf;
697
698         oldtexibuf= cache->texibuf;
699         cache->texibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
700
701         if (oldtexibuf) {
702                 srcx= srcy= 0;
703                 destx= (int)painter->lastpaintpos[0] - (int)pos[0];
704                 desty= (int)painter->lastpaintpos[1] - (int)pos[1];
705                 w= oldtexibuf->x;
706                 h= oldtexibuf->y;
707
708                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
709         }
710         else {
711                 srcx= srcy= 0;
712                 destx= desty= 0;
713                 w= h= 0;
714         }
715         
716         x1= destx;
717         y1= desty;
718         x2= destx+w;
719         y2= desty+h;
720
721         /* blend existing texture in new position */
722         if ((x1 < x2) && (y1 < y2))
723                 brush_painter_do_partial(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy, pos);
724
725         if (oldtexibuf)
726                 IMB_freeImBuf(oldtexibuf);
727
728         /* sample texture in new areas */
729         if ((0 < x1) && (0 < ibuf->y))
730                 brush_painter_do_partial(painter, NULL, 0, 0, x1, ibuf->y, 0, 0, pos);
731         if ((x2 < ibuf->x) && (0 < ibuf->y))
732                 brush_painter_do_partial(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0, pos);
733         if ((x1 < x2) && (0 < y1))
734                 brush_painter_do_partial(painter, NULL, x1, 0, x2, y1, 0, 0, pos);
735         if ((x1 < x2) && (y2 < ibuf->y))
736                 brush_painter_do_partial(painter, NULL, x1, y2, x2, ibuf->y, 0, 0, pos);
737 }
738
739 static void brush_painter_refresh_cache(BrushPainter *painter, float *pos)
740 {
741         Brush *brush= painter->brush;
742         BrushPainterCache *cache= &painter->cache;
743         MTex *mtex= brush->mtex[brush->texact];
744         int size;
745         short flt;
746
747         if ((brush->size != cache->lastsize) || (brush->alpha != cache->lastalpha)
748             || (brush->jitter != cache->lastjitter)) {
749                 if (cache->ibuf) {
750                         IMB_freeImBuf(cache->ibuf);
751                         cache->ibuf= NULL;
752                 }
753                 if (cache->maskibuf) {
754                         IMB_freeImBuf(cache->maskibuf);
755                         cache->maskibuf= NULL;
756                 }
757
758                 flt= cache->flt;
759                 size= (cache->size)? cache->size: brush->size;
760
761                 if (!(mtex && mtex->tex) || (mtex->tex->type==0)) {
762                         brush_imbuf_new(brush, flt, 0, size, &cache->ibuf);
763                 }
764                 else if (brush->flag & BRUSH_FIXED_TEX) {
765                         brush_imbuf_new(brush, flt, 0, size, &cache->maskibuf);
766                         brush_painter_fixed_tex_partial_update(painter, pos);
767                 }
768                 else
769                         brush_imbuf_new(brush, flt, 2, size, &cache->ibuf);
770
771                 cache->lastsize= brush->size;
772                 cache->lastalpha= brush->alpha;
773                 cache->lastjitter= brush->jitter;
774         }
775         else if ((brush->flag & BRUSH_FIXED_TEX) && mtex && mtex->tex) {
776                 int dx = (int)painter->lastpaintpos[0] - (int)pos[0];
777                 int dy = (int)painter->lastpaintpos[1] - (int)pos[1];
778
779                 if ((dx != 0) || (dy != 0))
780                         brush_painter_fixed_tex_partial_update(painter, pos);
781         }
782 }
783
784 void brush_painter_break_stroke(BrushPainter *painter)
785 {
786         painter->firsttouch= 1;
787 }
788
789 static void brush_apply_pressure(BrushPainter *painter, Brush *brush, float pressure)
790 {
791         if (brush->flag & BRUSH_ALPHA_PRESSURE) 
792                 brush->alpha = MAX2(0.0, painter->startalpha*pressure);
793         if (brush->flag & BRUSH_SIZE_PRESSURE)
794                 brush->size = MAX2(1.0, painter->startsize*pressure);
795         if (brush->flag & BRUSH_JITTER_PRESSURE)
796                 brush->jitter = MAX2(0.0, painter->startjitter*pressure);
797         if (brush->flag & BRUSH_SPACING_PRESSURE)
798                 brush->spacing = MAX2(1.0, painter->startspacing*(1.5f-pressure));
799 }
800
801 static void brush_jitter_pos(Brush *brush, float *pos, float *jitterpos)
802 {
803         if(brush->jitter){
804                 jitterpos[0] = pos[0] + ((BLI_frand()-0.5f) * brush->size * brush->jitter * 2);
805                 jitterpos[1] = pos[1] + ((BLI_frand()-0.5f) * brush->size * brush->jitter * 2);
806         }
807         else {
808                 VECCOPY2D(jitterpos, pos);
809         }
810 }
811
812 int brush_painter_paint(BrushPainter *painter, BrushFunc func, float *pos, double time, float pressure, void *user)
813 {
814         Brush *brush= painter->brush;
815         int totpaintops= 0;
816
817         if (pressure == 0.0f) {
818                 if(painter->lastpressure) // XXX - hack, operator misses
819                         pressure= painter->lastpressure;
820                 else
821                         pressure = 1.0f;        /* zero pressure == not using tablet */
822         }
823         if (painter->firsttouch) {
824                 /* paint exactly once on first touch */
825                 painter->startpaintpos[0]= pos[0];
826                 painter->startpaintpos[1]= pos[1];
827
828                 brush_apply_pressure(painter, brush, pressure);
829                 if (painter->cache.enabled)
830                         brush_painter_refresh_cache(painter, pos);
831                 totpaintops += func(user, painter->cache.ibuf, pos, pos);
832                 
833                 painter->lasttime= time;
834                 painter->firsttouch= 0;
835                 painter->lastpaintpos[0]= pos[0];
836                 painter->lastpaintpos[1]= pos[1];
837         }
838 #if 0
839         else if (painter->brush->flag & BRUSH_AIRBRUSH) {
840                 float spacing, step, paintpos[2], dmousepos[2], len;
841                 double starttime, curtime= time;
842
843                 /* compute brush spacing adapted to brush size */
844                 spacing= brush->rate; //brush->size*brush->spacing*0.01f;
845
846                 /* setup starting time, direction vector and accumulated time */
847                 starttime= painter->accumtime;
848                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
849                 len= normalize_v2(dmousepos);
850                 painter->accumtime += curtime - painter->lasttime;
851
852                 /* do paint op over unpainted time distance */
853                 while (painter->accumtime >= spacing) {
854                         step= (spacing - starttime)*len;
855                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
856                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
857
858                         if (painter->cache.enabled)
859                                 brush_painter_refresh_cache(painter);
860                         totpaintops += func(user, painter->cache.ibuf,
861                                 painter->lastpaintpos, paintpos);
862
863                         painter->lastpaintpos[0]= paintpos[0];
864                         painter->lastpaintpos[1]= paintpos[1];
865                         painter->accumtime -= spacing;
866                         starttime -= spacing;
867                 }
868                 
869                 painter->lasttime= curtime;
870         }
871 #endif
872         else {
873                 float startdistance, spacing, step, paintpos[2], dmousepos[2], finalpos[2];
874                 float t, len, press;
875
876                 /* compute brush spacing adapted to brush size, spacing may depend
877                    on pressure, so update it */
878                 brush_apply_pressure(painter, brush, painter->lastpressure);
879                 spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
880
881                 /* setup starting distance, direction vector and accumulated distance */
882                 startdistance= painter->accumdistance;
883                 sub_v2_v2v2(dmousepos, pos, painter->lastmousepos);
884                 len= normalize_v2(dmousepos);
885                 painter->accumdistance += len;
886
887                 /* do paint op over unpainted distance */
888                 while ((len > 0.0f) && (painter->accumdistance >= spacing)) {
889                         step= spacing - startdistance;
890                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
891                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
892
893                         t = step/len;
894                         press= (1.0f-t)*painter->lastpressure + t*pressure;
895                         brush_apply_pressure(painter, brush, press);
896                         spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
897
898                         brush_jitter_pos(brush, paintpos, finalpos);
899
900                         if (painter->cache.enabled)
901                                 brush_painter_refresh_cache(painter, finalpos);
902
903                         totpaintops +=
904                                 func(user, painter->cache.ibuf, painter->lastpaintpos, finalpos);
905
906                         painter->lastpaintpos[0]= paintpos[0];
907                         painter->lastpaintpos[1]= paintpos[1];
908                         painter->accumdistance -= spacing;
909                         startdistance -= spacing;
910                 }
911
912                 /* do airbrush paint ops, based on the number of paint ops left over
913                    from regular painting. this is a temporary solution until we have
914                    accurate time stamps for mouse move events */
915                 if (brush->flag & BRUSH_AIRBRUSH) {
916                         double curtime= time;
917                         double painttime= brush->rate*totpaintops;
918
919                         painter->accumtime += curtime - painter->lasttime;
920                         if (painter->accumtime <= painttime)
921                                 painter->accumtime= 0.0;
922                         else
923                                 painter->accumtime -= painttime;
924
925                         while (painter->accumtime >= brush->rate) {
926                                 brush_apply_pressure(painter, brush, pressure);
927
928                                 brush_jitter_pos(brush, pos, finalpos);
929
930                                 if (painter->cache.enabled)
931                                         brush_painter_refresh_cache(painter, finalpos);
932
933                                 totpaintops +=
934                                         func(user, painter->cache.ibuf, painter->lastmousepos, finalpos);
935                                 painter->accumtime -= brush->rate;
936                         }
937
938                         painter->lasttime= curtime;
939                 }
940         }
941
942         painter->lastmousepos[0]= pos[0];
943         painter->lastmousepos[1]= pos[1];
944         painter->lastpressure= pressure;
945
946         brush->alpha = painter->startalpha;
947         brush->size = painter->startsize;
948         brush->jitter = painter->startjitter;
949         brush->spacing = painter->startspacing;
950
951         return totpaintops;
952 }
953
954 /* Uses the brush curve control to find a strength value between 0 and 1 */
955 float brush_curve_strength_clamp(Brush *br, float p, const float len)
956 {
957         if(p >= len)    p= 1.0f;
958         else                    p= p/len;
959
960         p= curvemapping_evaluateF(br->curve, 0, p);
961         if(p < 0.0)                     p= 0.0f;
962         else if(p > 1.0f)       p= 1.0f;
963         return p;
964 }
965 /* same as above but can return negative values if the curve enables
966  * used for sculpt only */
967 float brush_curve_strength(Brush *br, float p, const float len)
968 {
969         if(p >= len)    p= 1.0f;
970         else                    p= p/len;
971         return curvemapping_evaluateF(br->curve, 0, p);
972 }
973
974 /* TODO: should probably be unified with BrushPainter stuff? */
975 unsigned int *brush_gen_texture_cache(Brush *br, int half_side)
976 {
977         unsigned int *texcache = NULL;
978         MTex *mtex = br->mtex[br->texact];
979         TexResult texres;
980         int hasrgb, ix, iy;
981         int side = half_side * 2;
982
983         memset(&texres, 0, sizeof(TexResult));
984         
985         if(mtex && mtex->tex) {
986                 float x, y, step = 2.0 / side, co[3];
987
988                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
989
990                 BKE_image_get_ibuf(mtex->tex->ima, NULL);
991                 
992                 /*do normalized cannonical view coords for texture*/
993                 for (y=-1.0, iy=0; iy<side; iy++, y += step) {
994                         for (x=-1.0, ix=0; ix<side; ix++, x += step) {
995                                 co[0]= x;
996                                 co[1]= y;
997                                 co[2]= 0.0f;
998                                 
999                                 /* This is copied from displace modifier code */
1000                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 1, &texres);
1001                         
1002                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1003                                  * intensity, so calculate one (formula from do_material_tex).
1004                                  * if the texture didn't give an RGB value, copy the intensity across
1005                                  */
1006                                 if(hasrgb & TEX_RGB)
1007                                         texres.tin = (0.35 * texres.tr + 0.45 *
1008                                                       texres.tg + 0.2 * texres.tb);
1009
1010                                 texres.tin = texres.tin * 255.0;
1011                                 ((char*)texcache)[(iy*side+ix)*4] = (char)texres.tin;
1012                                 ((char*)texcache)[(iy*side+ix)*4+1] = (char)texres.tin;
1013                                 ((char*)texcache)[(iy*side+ix)*4+2] = (char)texres.tin;
1014                                 ((char*)texcache)[(iy*side+ix)*4+3] = (char)texres.tin;
1015                         }
1016                 }
1017         }
1018
1019         return texcache;
1020 }
1021
1022 /**** Radial Control ****/
1023 static struct ImBuf *brush_gen_radial_control_imbuf(Brush *br)
1024 {
1025         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1026         unsigned int *texcache;
1027         int side = 128;
1028         int half = side / 2;
1029         int i, j;
1030
1031         texcache = brush_gen_texture_cache(br, half);
1032         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1033         im->x = im->y = side;
1034
1035         for(i=0; i<side; ++i) {
1036                 for(j=0; j<side; ++j) {
1037                         float magn= sqrt(pow(i - half, 2) + pow(j - half, 2));
1038                         im->rect_float[i*side + j]= brush_curve_strength_clamp(br, magn, half);
1039                 }
1040         }
1041
1042         /* Modulate curve with texture */
1043         if(texcache) {
1044                 for(i=0; i<side; ++i) {
1045                         for(j=0; j<side; ++j) {
1046                                 const int col= texcache[i*side+j];
1047                                 im->rect_float[i*side+j]*= (((char*)&col)[0]+((char*)&col)[1]+((char*)&col)[2])/3.0f/255.0f;
1048                         }
1049                 }
1050
1051                 MEM_freeN(texcache);
1052         }
1053
1054         return im;
1055 }
1056
1057 void brush_radial_control_invoke(wmOperator *op, Brush *br, float size_weight)
1058 {
1059         int mode = RNA_int_get(op->ptr, "mode");
1060         float original_value= 0;
1061
1062         if(mode == WM_RADIALCONTROL_SIZE)
1063                 original_value = br->size * size_weight;
1064         else if(mode == WM_RADIALCONTROL_STRENGTH)
1065                 original_value = br->alpha;
1066         else if(mode == WM_RADIALCONTROL_ANGLE) {
1067                 MTex *mtex = brush_active_texture(br);
1068                 if(mtex)
1069                         original_value = mtex->rot;
1070         }
1071
1072         RNA_float_set(op->ptr, "initial_value", original_value);
1073         op->customdata = brush_gen_radial_control_imbuf(br);
1074 }
1075
1076 int brush_radial_control_exec(wmOperator *op, Brush *br, float size_weight)
1077 {
1078         int mode = RNA_int_get(op->ptr, "mode");
1079         float new_value = RNA_float_get(op->ptr, "new_value");
1080         const float conv = 0.017453293;
1081
1082         if(mode == WM_RADIALCONTROL_SIZE)
1083                 br->size = new_value * size_weight;
1084         else if(mode == WM_RADIALCONTROL_STRENGTH)
1085                 br->alpha = new_value;
1086         else if(mode == WM_RADIALCONTROL_ANGLE) {
1087                 MTex *mtex = brush_active_texture(br);
1088                 if(mtex)
1089                         mtex->rot = new_value * conv;
1090         }
1091
1092         return OPERATOR_FINISHED;
1093 }