17973Patch by dfelinto, and also fixed a bug in 2d-filters
[blender.git] / source / blender / src / imagepaint.c
1 /**
2  * $Id$
3  * imagepaint.c
4  *
5  * Functions to paint images in 2D and 3D.
6  * 
7  * ***** BEGIN GPL LICENSE BLOCK *****
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA        02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): Jens Ole Wund (bjornmose)
29  *
30  * ***** END GPL LICENSE BLOCK *****
31  */
32
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include "MEM_guardedalloc.h"
42
43 #ifdef WIN32
44 #include "BLI_winstuff.h"
45 #endif
46 #include "BLI_arithb.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_dynstr.h"
49 #include "PIL_time.h"
50
51 #include "IMB_imbuf.h"
52 #include "IMB_imbuf_types.h"
53
54 #include "DNA_brush_types.h"
55 #include "DNA_image_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_node_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_userdef_types.h"
64 #include "DNA_view3d_types.h"
65
66 #include "BKE_brush.h"
67 #include "BKE_global.h"
68 #include "BKE_image.h"
69 #include "BKE_main.h"
70 #include "BKE_mesh.h"
71 #include "BKE_node.h"
72 #include "BKE_utildefines.h"
73
74 #include "BIF_interface.h"
75 #include "BIF_mywindow.h"
76 #include "BIF_screen.h"
77 #include "BIF_space.h"
78 #include "BIF_toolbox.h"
79
80 #include "BSE_drawipo.h"
81 #include "BSE_node.h"
82 #include "BSE_trans_types.h"
83 #include "BSE_view.h"
84
85 #include "BDR_imagepaint.h"
86 #include "BDR_vpaint.h"
87
88 #include "GPU_draw.h"
89
90 #include "GHOST_Types.h"
91
92 #include "blendef.h"
93 #include "butspace.h"
94 #include "mydevice.h"
95
96 /* Defines and Structs */
97
98 #define IMAPAINT_CHAR_TO_FLOAT(c) (c/255.0f)
99
100 #define IMAPAINT_FLOAT_RGB_TO_CHAR(c, f) { c[0]=FTOCHAR(f[0]); \
101         c[1]=FTOCHAR(f[1]); c[2]=FTOCHAR(f[2]); }
102 #define IMAPAINT_CHAR_RGB_TO_FLOAT(f, c) { f[0]=IMAPAINT_CHAR_TO_FLOAT(c[0]); \
103         f[1]=IMAPAINT_CHAR_TO_FLOAT(c[1]); f[2]=IMAPAINT_CHAR_TO_FLOAT(c[2]); }
104 #define IMAPAINT_FLOAT_RGB_COPY(a, b) VECCOPY(a, b)
105
106 #define IMAPAINT_TILE_BITS                      6
107 #define IMAPAINT_TILE_SIZE                      (1 << IMAPAINT_TILE_BITS)
108 #define IMAPAINT_TILE_NUMBER(size)      (((size)+IMAPAINT_TILE_SIZE-1) >> IMAPAINT_TILE_BITS)
109
110 #define MAXUNDONAME     64
111
112 typedef struct ImagePaintState {
113         Brush *brush;
114         short tool, blend;
115         Image *image;
116         ImBuf *canvas;
117         ImBuf *clonecanvas;
118         short clonefreefloat;
119         char *warnpackedfile;
120         char *warnmultifile;
121
122         /* texture paint only */
123         Object *ob;
124         Mesh *me;
125         int faceindex;
126         float uv[2];
127 } ImagePaintState;
128
129 typedef struct UndoTile {
130         struct UndoTile *next, *prev;
131         ID id;
132         void *rect;
133         int x, y;
134 } UndoTile;
135
136 typedef struct UndoElem {
137         struct UndoElem *next, *prev;
138         char name[MAXUNDONAME];
139         unsigned long undosize;
140
141         ImBuf *ibuf;
142         ListBase tiles;
143 } UndoElem;
144
145 typedef struct ImagePaintPartialRedraw {
146         int x1, y1, x2, y2;
147         int enabled;
148 } ImagePaintPartialRedraw;
149
150 static ListBase undobase = {NULL, NULL};
151 static UndoElem *curundo = NULL;
152 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
153
154 /* UNDO */
155
156 /* internal functions */
157
158 static void undo_copy_tile(UndoTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, int restore)
159 {
160         /* copy or swap contents of tile->rect and region in ibuf->rect */
161         IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x*IMAPAINT_TILE_SIZE,
162                 tile->y*IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
163
164         if(ibuf->rect_float) SWAP(void*, tmpibuf->rect_float, tile->rect)
165         else SWAP(void*, tmpibuf->rect, tile->rect)
166         
167         if(restore)
168                 IMB_rectcpy(ibuf, tmpibuf, tile->x*IMAPAINT_TILE_SIZE,
169                         tile->y*IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
170 }
171
172 static void undo_restore(UndoElem *undo)
173 {
174         Image *ima = NULL;
175         ImBuf *ibuf, *tmpibuf;
176         UndoTile *tile;
177
178         if(!undo)
179                 return;
180
181         tmpibuf= IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
182                                 IB_rectfloat|IB_rect, 0);
183         
184         for(tile=undo->tiles.first; tile; tile=tile->next) {
185                 /* find image based on name, pointer becomes invalid with global undo */
186                 if(ima && strcmp(tile->id.name, ima->id.name)==0);
187                 else {
188                         for(ima=G.main->image.first; ima; ima=ima->id.next)
189                                 if(strcmp(tile->id.name, ima->id.name)==0)
190                                         break;
191                 }
192
193                 ibuf= BKE_image_get_ibuf(ima, NULL);
194
195                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float))
196                         continue;
197
198                 undo_copy_tile(tile, tmpibuf, ibuf, 1);
199
200                 GPU_free_image(ima); /* force OpenGL reload */
201                 if(ibuf->rect_float)
202                         imb_freerectImBuf(ibuf); /* force recreate of char rect */
203         }
204
205         IMB_freeImBuf(tmpibuf);
206 }
207
208 static void undo_free(UndoElem *undo)
209 {
210         UndoTile *tile;
211
212         for(tile=undo->tiles.first; tile; tile=tile->next)
213                 MEM_freeN(tile->rect);
214         BLI_freelistN(&undo->tiles);
215 }
216
217 static void undo_imagepaint_push_begin(char *name)
218 {
219         UndoElem *uel;
220         int nr;
221         
222         /* Undo push is split up in begin and end, the reason is that as painting
223          * happens more tiles are added to the list, and at the very end we know
224          * how much memory the undo used to remove old undo elements */
225
226         /* remove all undos after (also when curundo==NULL) */
227         while(undobase.last != curundo) {
228                 uel= undobase.last;
229                 undo_free(uel);
230                 BLI_freelinkN(&undobase, uel);
231         }
232         
233         /* make new */
234         curundo= uel= MEM_callocN(sizeof(UndoElem), "undo file");
235         BLI_addtail(&undobase, uel);
236
237         /* name can be a dynamic string */
238         strncpy(uel->name, name, MAXUNDONAME-1);
239         
240         /* limit amount to the maximum amount*/
241         nr= 0;
242         uel= undobase.last;
243         while(uel) {
244                 nr++;
245                 if(nr==U.undosteps) break;
246                 uel= uel->prev;
247         }
248         if(uel) {
249                 while(undobase.first!=uel) {
250                         UndoElem *first= undobase.first;
251                         undo_free(first);
252                         BLI_freelinkN(&undobase, first);
253                 }
254         }
255 }
256
257 static void undo_imagepaint_push_end()
258 {
259         UndoElem *uel;
260         unsigned long totmem, maxmem;
261
262         if(U.undomemory != 0) {
263                 /* limit to maximum memory (afterwards, we can't know in advance) */
264                 totmem= 0;
265                 maxmem= ((unsigned long)U.undomemory)*1024*1024;
266
267                 uel= undobase.last;
268                 while(uel) {
269                         totmem+= uel->undosize;
270                         if(totmem>maxmem) break;
271                         uel= uel->prev;
272                 }
273
274                 if(uel) {
275                         while(undobase.first!=uel) {
276                                 UndoElem *first= undobase.first;
277                                 undo_free(first);
278                                 BLI_freelinkN(&undobase, first);
279                         }
280                 }
281         }
282 }
283
284 /* external functions */
285
286 /* 1= an undo, -1 is a redo. */
287 void undo_imagepaint_step(int step)
288 {
289         UndoElem *undo;
290
291         if(step==1) {
292                 if(curundo==NULL) error("No more steps to undo");
293                 else {
294                         if(G.f & G_DEBUG) printf("undo %s\n", curundo->name);
295                         undo_restore(curundo);
296                         curundo= curundo->prev;
297                 }
298         }
299         else if(step==-1) {
300                 if((curundo!=NULL && curundo->next==NULL) || undobase.first==NULL) error("No more steps to redo");
301                 else {
302                         undo= (curundo && curundo->next)? curundo->next: undobase.first;
303                         undo_restore(undo);
304                         curundo= undo;
305                         if(G.f & G_DEBUG) printf("redo %s\n", undo->name);
306                 }
307         }
308
309         allqueue(REDRAWVIEW3D, 0);
310         allqueue(REDRAWIMAGE, 0);
311 }
312
313 void undo_imagepaint_clear(void)
314 {
315         UndoElem *uel;
316         
317         uel= undobase.first;
318         while(uel) {
319                 undo_free(uel);
320                 uel= uel->next;
321         }
322
323         BLI_freelistN(&undobase);
324         curundo= NULL;
325 }
326
327 /* Imagepaint Partial Redraw & Dirty Region */
328
329 static void imapaint_clear_partial_redraw()
330 {
331         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
332 }
333
334 static void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h)
335 {
336         ImBuf *tmpibuf;
337         UndoTile *tile;
338         int srcx= 0, srcy= 0, origx, allocsize;
339
340         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
341
342         if (w == 0 || h == 0)
343                 return;
344         
345         if (!imapaintpartial.enabled) {
346                 imapaintpartial.x1 = x;
347                 imapaintpartial.y1 = y;
348                 imapaintpartial.x2 = x+w;
349                 imapaintpartial.y2 = y+h;
350                 imapaintpartial.enabled = 1;
351         }
352         else {
353                 imapaintpartial.x1 = MIN2(imapaintpartial.x1, x);
354                 imapaintpartial.y1 = MIN2(imapaintpartial.y1, y);
355                 imapaintpartial.x2 = MAX2(imapaintpartial.x2, x+w);
356                 imapaintpartial.y2 = MAX2(imapaintpartial.y2, y+h);
357         }
358
359         w = ((x + w - 1) >> IMAPAINT_TILE_BITS);
360         h = ((y + h - 1) >> IMAPAINT_TILE_BITS);
361         origx = (x >> IMAPAINT_TILE_BITS);
362         y = (y >> IMAPAINT_TILE_BITS);
363
364         tmpibuf= IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
365                                 IB_rectfloat|IB_rect, 0);
366         
367         for (; y <= h; y++) {
368                 for (x=origx; x <= w; x++) {
369                         for(tile=curundo->tiles.first; tile; tile=tile->next)
370                                 if(tile->x == x && tile->y == y && strcmp(tile->id.name, ima->id.name)==0)
371                                         break;
372
373                         if(!tile) {
374                                 tile= MEM_callocN(sizeof(UndoTile), "ImaUndoTile");
375                                 tile->id= ima->id;
376                                 tile->x= x;
377                                 tile->y= y;
378
379                                 allocsize= IMAPAINT_TILE_SIZE*IMAPAINT_TILE_SIZE*4;
380                                 allocsize *= (ibuf->rect_float)? sizeof(float): sizeof(char);
381                                 tile->rect= MEM_mapallocN(allocsize, "ImaUndoRect");
382
383                                 undo_copy_tile(tile, tmpibuf, ibuf, 0);
384                                 curundo->undosize += allocsize;
385
386                                 BLI_addtail(&curundo->tiles, tile);
387                         }
388                 }
389         }
390
391         ibuf->userflags |= IB_BITMAPDIRTY;
392
393         IMB_freeImBuf(tmpibuf);
394 }
395
396 static void imapaint_image_update(Image *image, ImBuf *ibuf, short texpaint)
397 {
398         if(ibuf->rect_float)
399                 imb_freerectImBuf(ibuf); /* force recreate of char rect */
400         if(ibuf->mipmap[0])
401                 imb_freemipmapImBuf(ibuf);
402
403         /* todo: should set_tpage create ->rect? */
404         if(texpaint || G.sima->lock) {
405                 int w = imapaintpartial.x2 - imapaintpartial.x1;
406                 int h = imapaintpartial.y2 - imapaintpartial.y1;
407                 GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h);
408         }
409 }
410
411 /* note; gets called for both 2d image paint and 3d texture paint. in the
412    latter case image may be NULL and G.sima may not exist */
413 static void imapaint_redraw(int final, int texpaint, Image *image)
414 {
415         if(final) {
416                 if(texpaint)
417                         allqueue(REDRAWIMAGE, 0);
418                 else if(!G.sima->lock) {
419                         if(image)
420                                 GPU_free_image(image); /* force OpenGL reload */
421                         allqueue(REDRAWVIEW3D, 0);
422                 }
423                 allqueue(REDRAWHEADERS, 0);
424                 
425                 if(!texpaint && image) {
426                         /* after paint, tag Image or RenderResult nodes changed */
427                         if(G.scene->nodetree) {
428                                 imagepaint_composite_tags(G.scene->nodetree, image, &G.sima->iuser);
429                         }
430                         /* signal composite (hurmf, need an allqueue?) */
431                         if(G.sima->lock) {
432                                 ScrArea *sa;
433                                 for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
434                                         if(sa->spacetype==SPACE_NODE) {
435                                                 if(((SpaceNode *)sa->spacedata.first)->treetype==NTREE_COMPOSIT) {
436                                                         addqueue(sa->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
437                                                         break;
438                                                 }
439                                         }
440                                 }
441                         }
442                 }               
443         }
444         else if(!texpaint && G.sima->lock)
445                 force_draw_plus(SPACE_VIEW3D, 0);
446         else
447                 force_draw(0);
448 }
449
450 /* Image Paint Operations */
451
452 static void imapaint_ibuf_get_set_rgb(ImBuf *ibuf, int x, int y, short torus, short set, float *rgb)
453 {
454         if (torus) {
455                 x %= ibuf->x;
456                 if (x < 0) x += ibuf->x;
457                 y %= ibuf->y;
458                 if (y < 0) y += ibuf->y;
459         }
460
461         if (ibuf->rect_float) {
462                 float *rrgbf = ibuf->rect_float + (ibuf->x*y + x)*4;
463
464                 if (set) IMAPAINT_FLOAT_RGB_COPY(rrgbf, rgb)
465                 else IMAPAINT_FLOAT_RGB_COPY(rgb, rrgbf)
466         }
467         else {
468                 char *rrgb = (char*)ibuf->rect + (ibuf->x*y + x)*4;
469
470                 if (set) IMAPAINT_FLOAT_RGB_TO_CHAR(rrgb, rgb)
471                 else IMAPAINT_CHAR_RGB_TO_FLOAT(rgb, rrgb)
472         }
473 }
474
475 static int imapaint_ibuf_add_if(ImBuf *ibuf, unsigned int x, unsigned int y, float *outrgb, short torus)
476 {
477         float inrgb[3];
478
479         if ((x >= ibuf->x) || (y >= ibuf->y)) {
480                 if (torus) imapaint_ibuf_get_set_rgb(ibuf, x, y, 1, 0, inrgb);
481                 else return 0;
482         }
483         else imapaint_ibuf_get_set_rgb(ibuf, x, y, 0, 0, inrgb);
484
485         outrgb[0] += inrgb[0];
486         outrgb[1] += inrgb[1];
487         outrgb[2] += inrgb[2];
488
489         return 1;
490 }
491
492 static void imapaint_lift_soften(ImBuf *ibuf, ImBuf *ibufb, int *pos, short torus)
493 {
494         int x, y, count, xi, yi, xo, yo;
495         int out_off[2], in_off[2], dim[2];
496         float outrgb[3];
497
498         dim[0] = ibufb->x;
499         dim[1] = ibufb->y;
500         in_off[0] = pos[0];
501         in_off[1] = pos[1];
502         out_off[0] = out_off[1] = 0;
503
504         if (!torus) {
505                 IMB_rectclip(ibuf, ibufb, &in_off[0], &in_off[1], &out_off[0],
506                         &out_off[1], &dim[0], &dim[1]);
507
508                 if ((dim[0] == 0) || (dim[1] == 0))
509                         return;
510         }
511
512         for (y=0; y < dim[1]; y++) {
513                 for (x=0; x < dim[0]; x++) {
514                         /* get input pixel */
515                         xi = in_off[0] + x;
516                         yi = in_off[1] + y;
517
518                         count = 1;
519                         imapaint_ibuf_get_set_rgb(ibuf, xi, yi, torus, 0, outrgb);
520
521                         count += imapaint_ibuf_add_if(ibuf, xi-1, yi-1, outrgb, torus);
522                         count += imapaint_ibuf_add_if(ibuf, xi-1, yi  , outrgb, torus);
523                         count += imapaint_ibuf_add_if(ibuf, xi-1, yi+1, outrgb, torus);
524
525                         count += imapaint_ibuf_add_if(ibuf, xi  , yi-1, outrgb, torus);
526                         count += imapaint_ibuf_add_if(ibuf, xi  , yi+1, outrgb, torus);
527
528                         count += imapaint_ibuf_add_if(ibuf, xi+1, yi-1, outrgb, torus);
529                         count += imapaint_ibuf_add_if(ibuf, xi+1, yi  , outrgb, torus);
530                         count += imapaint_ibuf_add_if(ibuf, xi+1, yi+1, outrgb, torus);
531
532                         outrgb[0] /= count;
533                         outrgb[1] /= count;
534                         outrgb[2] /= count;
535
536                         /* write into brush buffer */
537                         xo = out_off[0] + x;
538                         yo = out_off[1] + y;
539                         imapaint_ibuf_get_set_rgb(ibufb, xo, yo, 0, 1, outrgb);
540                 }
541         }
542 }
543
544 static void imapaint_lift_smear(ImBuf *ibuf, ImBuf *ibufb, int *pos)
545 {
546         IMB_rectblend_torus(ibufb, ibuf, 0, 0, pos[0], pos[1],
547                 ibufb->x, ibufb->y, IMB_BLEND_COPY_RGB);
548 }
549
550 static ImBuf *imapaint_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos)
551 {
552         /* note: allocImbuf returns zero'd memory, so regions outside image will
553            have zero alpha, and hence not be blended onto the image */
554         int w=ibufb->x, h=ibufb->y, destx=0, desty=0, srcx=pos[0], srcy=pos[1];
555         ImBuf *clonebuf= IMB_allocImBuf(w, h, ibufb->depth, ibufb->flags, 0);
556
557         IMB_rectclip(clonebuf, ibuf, &destx, &desty, &srcx, &srcy, &w, &h);
558         IMB_rectblend(clonebuf, ibuf, destx, desty, srcx, srcy, w, h,
559                 IMB_BLEND_COPY_RGB);
560         IMB_rectblend(clonebuf, ibufb, destx, desty, destx, desty, w, h,
561                 IMB_BLEND_COPY_ALPHA);
562
563         return clonebuf;
564 }
565
566 static void imapaint_convert_brushco(ImBuf *ibufb, float *pos, int *ipos)
567 {
568         ipos[0]= (int)(pos[0] - ibufb->x/2);
569         ipos[1]= (int)(pos[1] - ibufb->y/2);
570 }
571
572 static int imapaint_paint_op(void *state, ImBuf *ibufb, float *lastpos, float *pos)
573 {
574         ImagePaintState *s= ((ImagePaintState*)state);
575         ImBuf *clonebuf= NULL;
576         short torus= s->brush->flag & BRUSH_TORUS;
577         short blend= s->blend;
578         float *offset= s->brush->clone.offset;
579         float liftpos[2];
580         int bpos[2], blastpos[2], bliftpos[2];
581
582         imapaint_convert_brushco(ibufb, pos, bpos);
583
584         /* lift from canvas */
585         if(s->tool == PAINT_TOOL_SOFTEN) {
586                 imapaint_lift_soften(s->canvas, ibufb, bpos, torus);
587         }
588         else if(s->tool == PAINT_TOOL_SMEAR) {
589                 if (lastpos[0]==pos[0] && lastpos[1]==pos[1])
590                         return 0;
591
592                 imapaint_convert_brushco(ibufb, lastpos, blastpos);
593                 imapaint_lift_smear(s->canvas, ibufb, blastpos);
594         }
595         else if(s->tool == PAINT_TOOL_CLONE && s->clonecanvas) {
596                 liftpos[0]= pos[0] - offset[0]*s->canvas->x;
597                 liftpos[1]= pos[1] - offset[1]*s->canvas->y;
598
599                 imapaint_convert_brushco(ibufb, liftpos, bliftpos);
600                 clonebuf= imapaint_lift_clone(s->clonecanvas, ibufb, bliftpos);
601         }
602
603         imapaint_dirty_region(s->image, s->canvas, bpos[0], bpos[1], ibufb->x, ibufb->y);
604
605         /* blend into canvas */
606         if(torus)
607                 IMB_rectblend_torus(s->canvas, (clonebuf)? clonebuf: ibufb,
608                         bpos[0], bpos[1], 0, 0, ibufb->x, ibufb->y, blend);
609         else
610                 IMB_rectblend(s->canvas, (clonebuf)? clonebuf: ibufb,
611                         bpos[0], bpos[1], 0, 0, ibufb->x, ibufb->y, blend);
612                         
613         if(clonebuf) IMB_freeImBuf(clonebuf);
614
615         return 1;
616 }
617
618 /* 2D ImagePaint */
619
620 static void imapaint_compute_uvco(short *mval, float *uv)
621 {
622         areamouseco_to_ipoco(G.v2d, mval, &uv[0], &uv[1]);
623 }
624
625 /* 3D TexturePaint */
626
627 int facesel_face_pick(Mesh *me, short *mval, unsigned int *index, short rect);
628 void texpaint_pick_uv(Object *ob, Mesh *mesh, unsigned int faceindex, short *xy, float *mousepos);
629
630 static int texpaint_break_stroke(float *prevuv, float *fwuv, float *bkuv, float *uv)
631 {
632         float d1[2], d2[2];
633         float mismatch = Vec2Lenf(fwuv, uv);
634         float len1 = Vec2Lenf(prevuv, fwuv);
635         float len2 = Vec2Lenf(bkuv, uv);
636
637         Vec2Subf(d1, fwuv, prevuv);
638         Vec2Subf(d2, uv, bkuv);
639
640         return ((Inp2f(d1, d2) < 0.0f) || (mismatch > MAX2(len1, len2)*2));
641 }
642
643 /* ImagePaint Common */
644
645 static int imapaint_canvas_set(ImagePaintState *s, Image *ima)
646 {
647         ImBuf *ibuf= BKE_image_get_ibuf(ima, G.sima?&G.sima->iuser:NULL);
648         
649         /* verify that we can paint and set canvas */
650         if(ima->packedfile && ima->rr) {
651                 s->warnpackedfile = ima->id.name + 2;
652                 return 0;
653         }       
654         else if(ibuf && ibuf->channels!=4) {
655                 s->warnmultifile = ima->id.name + 2;
656                 return 0;
657         }
658         else if(!ima || !ibuf || !(ibuf->rect || ibuf->rect_float))
659                 return 0;
660
661         s->image= ima;
662         s->canvas= ibuf;
663
664         /* set clone canvas */
665         if(s->tool == PAINT_TOOL_CLONE) {
666                 ima= s->brush->clone.image;
667                 ibuf= BKE_image_get_ibuf(ima, G.sima?&G.sima->iuser:NULL);
668                 
669                 if(!ima || !ibuf || !(ibuf->rect || ibuf->rect_float))
670                         return 0;
671
672                 s->clonecanvas= ibuf;
673
674                 if(s->canvas->rect_float && !s->clonecanvas->rect_float) {
675                         /* temporarily add float rect for cloning */
676                         IMB_float_from_rect(s->clonecanvas);
677                         s->clonefreefloat= 1;
678                 }
679                 else if(!s->canvas->rect_float && !s->clonecanvas->rect)
680                         IMB_rect_from_float(s->clonecanvas);
681         }
682
683         return 1;
684 }
685
686 static void imapaint_canvas_free(ImagePaintState *s)
687 {
688         if (s->clonefreefloat)
689                 imb_freerectfloatImBuf(s->clonecanvas);
690 }
691
692 static int imapaint_paint_sub_stroke(ImagePaintState *s, BrushPainter *painter, Image *image, short texpaint, float *uv, double time, int update, float pressure)
693 {
694         ImBuf *ibuf= BKE_image_get_ibuf(image, G.sima?&G.sima->iuser:NULL);
695         float pos[2];
696
697         if(!ibuf)
698                 return 0;
699
700         pos[0] = uv[0]*ibuf->x;
701         pos[1] = uv[1]*ibuf->y;
702
703         brush_painter_require_imbuf(painter, ((ibuf->rect_float)? 1: 0), 0, 0);
704
705         if (brush_painter_paint(painter, imapaint_paint_op, pos, time, pressure, s)) {
706                 if (update)
707                         imapaint_image_update(image, ibuf, texpaint);
708                 return 1;
709         }
710         else return 0;
711 }
712
713 static void imapaint_paint_stroke(ImagePaintState *s, BrushPainter *painter, short texpaint, short *prevmval, short *mval, double time, float pressure)
714 {
715         Image *newimage = NULL;
716         float fwuv[2], bkuv[2], newuv[2];
717         unsigned int newfaceindex;
718         int breakstroke = 0, redraw = 0;
719
720         if (texpaint) {
721                 /* pick new face and image */
722                 if (    facesel_face_pick(s->me, mval, &newfaceindex, 0) &&
723                                 ((G.f & G_FACESELECT)==0 || (s->me->mface+newfaceindex)->flag & ME_FACE_SEL)
724                 ) {
725                         ImBuf *ibuf;
726                         
727                         newimage = (Image*)((s->me->mtface+newfaceindex)->tpage);
728                         ibuf= BKE_image_get_ibuf(newimage, G.sima?&G.sima->iuser:NULL);
729
730                         if(ibuf && ibuf->rect)
731                                 texpaint_pick_uv(s->ob, s->me, newfaceindex, mval, newuv);
732                         else {
733                                 newimage = NULL;
734                                 newuv[0] = newuv[1] = 0.0f;
735                         }
736                 }
737                 else
738                         newuv[0] = newuv[1] = 0.0f;
739
740                 /* see if stroke is broken, and if so finish painting in old position */
741                 if (s->image) {
742                         texpaint_pick_uv(s->ob, s->me, s->faceindex, mval, fwuv);
743                         texpaint_pick_uv(s->ob, s->me, newfaceindex, prevmval, bkuv);
744
745                         if (newimage == s->image)
746                                 breakstroke= texpaint_break_stroke(s->uv, fwuv, bkuv, newuv);
747                         else
748                                 breakstroke= 1;
749                 }
750                 else
751                         fwuv[0]= fwuv[1]= 0.0f;
752
753                 if (breakstroke) {
754                         texpaint_pick_uv(s->ob, s->me, s->faceindex, mval, fwuv);
755                         redraw |= imapaint_paint_sub_stroke(s, painter, s->image, texpaint,
756                                 fwuv, time, 1, pressure);
757                         imapaint_clear_partial_redraw();
758                         brush_painter_break_stroke(painter);
759                 }
760
761                 /* set new canvas */
762                 if (newimage && (newimage != s->image))
763                         if (!imapaint_canvas_set(s, newimage))
764                                 newimage = NULL;
765
766                 /* paint in new image */
767                 if (newimage) {
768                         if (breakstroke)
769                                 redraw|= imapaint_paint_sub_stroke(s, painter, newimage,
770                                         texpaint, bkuv, time, 0, pressure);
771                         redraw|= imapaint_paint_sub_stroke(s, painter, newimage, texpaint,
772                                 newuv, time, 1, pressure);
773                 }
774
775                 /* update state */
776                 s->image = newimage;
777                 s->faceindex = newfaceindex;
778                 s->uv[0] = newuv[0];
779                 s->uv[1] = newuv[1];
780         }
781         else {
782                 imapaint_compute_uvco(mval, newuv);
783                 redraw |= imapaint_paint_sub_stroke(s, painter, s->image, texpaint, newuv,
784                         time, 1, pressure);
785         }
786
787         if (redraw) {
788                 imapaint_redraw(0, texpaint, NULL);
789                 imapaint_clear_partial_redraw();
790         }
791 }
792
793 void imagepaint_paint(short mousebutton, short texpaint)
794 {
795         ImagePaintState s;
796         BrushPainter *painter;
797         ToolSettings *settings= G.scene->toolsettings;
798         short prevmval[2], mval[2];
799         double time;
800         float pressure;
801
802         if(!settings->imapaint.brush)
803                 return;
804
805         /* initialize state */
806         memset(&s, 0, sizeof(s));
807         s.brush = settings->imapaint.brush;
808         s.tool = settings->imapaint.tool;
809         if(texpaint && (s.tool == PAINT_TOOL_CLONE))
810                 s.tool = PAINT_TOOL_DRAW;
811         s.blend = s.brush->blend;
812
813         if(texpaint) {
814                 s.ob = OBACT;
815                 if (!s.ob || !(s.ob->lay & G.vd->lay)) return;
816                 s.me = get_mesh(s.ob);
817                 if (!s.me) return;
818
819                 persp(PERSP_VIEW);
820         }
821         else {
822                 s.image = G.sima->image;
823
824                 if(!imapaint_canvas_set(&s, G.sima->image)) {
825                         if(s.warnmultifile)
826                                 error("Image requires 4 color channels to paint");
827                         if(s.warnpackedfile)
828                                 error("Packed MultiLayer files cannot be painted");
829                         return;
830                 }
831         }
832
833         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
834         undo_imagepaint_push_begin("Image Paint");
835
836         /* create painter and paint once */
837         painter= brush_painter_new(s.brush);
838
839         getmouseco_areawin(mval);
840
841         pressure = get_pressure();
842         s.blend = (get_activedevice() == 2)? BRUSH_BLEND_ERASE_ALPHA: s.brush->blend;
843         
844         time= PIL_check_seconds_timer();
845         prevmval[0]= mval[0];
846         prevmval[1]= mval[1];
847
848         /* special exception here for too high pressure values on first touch in
849            windows for some tablets */
850     if (!((s.brush->flag & (BRUSH_ALPHA_PRESSURE|BRUSH_SIZE_PRESSURE|
851                 BRUSH_SPACING_PRESSURE|BRUSH_RAD_PRESSURE)) && (get_activedevice() != 0) && (pressure >= 0.99f)))
852                 imapaint_paint_stroke(&s, painter, texpaint, prevmval, mval, time, pressure);
853
854         /* paint loop */
855         do {
856                 getmouseco_areawin(mval);
857
858                 pressure = get_pressure();
859                 s.blend = (get_activedevice() == 2)? BRUSH_BLEND_ERASE_ALPHA: s.brush->blend;
860                         
861                 time= PIL_check_seconds_timer();
862
863                 if((mval[0] != prevmval[0]) || (mval[1] != prevmval[1])) {
864                         imapaint_paint_stroke(&s, painter, texpaint, prevmval, mval, time, pressure);
865                         prevmval[0]= mval[0];
866                         prevmval[1]= mval[1];
867                 }
868                 else if (s.brush->flag & BRUSH_AIRBRUSH)
869                         imapaint_paint_stroke(&s, painter, texpaint, prevmval, mval, time, pressure);
870                 else
871                         BIF_wait_for_statechange();
872
873                 /* do mouse checking at the end, so don't check twice, and potentially
874                    miss a short tap */
875         } while(get_mbut() & mousebutton);
876
877         /* clean up */
878         settings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
879         imapaint_canvas_free(&s);
880         brush_painter_free(painter);
881
882         imapaint_redraw(1, texpaint, s.image);
883         undo_imagepaint_push_end();
884         
885         if (texpaint) {
886                 if (s.warnmultifile)
887                         error("Image requires 4 color channels to paint: %s", s.warnmultifile);
888                 if(s.warnpackedfile)
889                         error("Packed MultiLayer files cannot be painted %s", s.warnpackedfile);
890
891                 persp(PERSP_WIN);
892         }
893 }
894
895 void imagepaint_pick(short mousebutton)
896 {
897         ToolSettings *settings= G.scene->toolsettings;
898         Brush *brush= settings->imapaint.brush;
899
900         if(brush && (settings->imapaint.tool == PAINT_TOOL_CLONE)) {
901                 if(brush->clone.image) {
902                         short prevmval[2], mval[2];
903                         float lastmousepos[2], mousepos[2];
904                 
905                         getmouseco_areawin(prevmval);
906
907                         while(get_mbut() & mousebutton) {
908                                 getmouseco_areawin(mval);
909
910                                 if((prevmval[0] != mval[0]) || (prevmval[1] != mval[1]) ) {
911                                         /* mouse moved, so move the clone image */
912                                         imapaint_compute_uvco(prevmval, lastmousepos);
913                                         imapaint_compute_uvco(mval, mousepos);
914
915                                         brush->clone.offset[0] += mousepos[0] - lastmousepos[0];
916                                         brush->clone.offset[1] += mousepos[1] - lastmousepos[1];
917
918                                         force_draw(0);
919
920                                         prevmval[0]= mval[0];
921                                         prevmval[1]= mval[1];
922                                 }
923                         }
924                 }
925         }
926         else if(brush)
927                 sample_vpaint();
928 }
929