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