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