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