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