88b3bc5d8fdb3a50f471207ea188908bfd85d693
[blender-staging.git] / source / blender / editors / sculpt_paint / paint_image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * along with this program; if not, write to the Free Software Foundation,
15  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16  *
17  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
18  * All rights reserved.
19  *
20  * The Original Code is: some of this file.
21  *
22  * Contributor(s): Jens Ole Wund (bjornmose), Campbell Barton (ideasman42)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_image.c
28  *  \ingroup edsculpt
29  *  \brief Functions to paint images in 2D and 3D.
30  */
31
32 #include <float.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_threads.h"
43
44 #include "BLT_translation.h"
45
46 #include "IMB_imbuf.h"
47 #include "IMB_imbuf_types.h"
48
49 #include "DNA_brush_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_object_types.h"
52
53 #include "BKE_context.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_DerivedMesh.h"
56 #include "BKE_brush.h"
57 #include "BKE_image.h"
58 #include "BKE_main.h"
59 #include "BKE_material.h"
60 #include "BKE_node.h"
61 #include "BKE_paint.h"
62 #include "BKE_texture.h"
63
64 #include "UI_interface.h"
65 #include "UI_view2d.h"
66
67 #include "ED_image.h"
68 #include "ED_object.h"
69 #include "ED_paint.h"
70 #include "ED_screen.h"
71 #include "ED_view3d.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75
76 #include "RNA_access.h"
77 #include "RNA_define.h"
78
79 #include "GPU_draw.h"
80 #include "GPU_buffers.h"
81
82 #include "BIF_gl.h"
83 #include "BIF_glutil.h"
84
85 #include "IMB_colormanagement.h"
86
87 #include "paint_intern.h"
88
89 typedef struct UndoImageTile {
90         struct UndoImageTile *next, *prev;
91
92         char idname[MAX_ID_NAME];  /* name instead of pointer*/
93         char ibufname[IMB_FILENAME_SIZE];
94
95         union {
96                 float        *fp;
97                 unsigned int *uint;
98                 void         *pt;
99         } rect;
100
101         unsigned short *mask;
102
103         int x, y;
104
105         Image *ima;
106         short source, use_float;
107         char gen_type;
108         bool valid;
109 } UndoImageTile;
110
111 /* this is a static resource for non-globality,
112  * Maybe it should be exposed as part of the
113  * paint operation, but for now just give a public interface */
114 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
115 static SpinLock undolock;
116
117 void image_undo_init_locks(void)
118 {
119         BLI_spin_init(&undolock);
120 }
121
122 void image_undo_end_locks(void)
123 {
124         BLI_spin_end(&undolock);
125 }
126
127 ImagePaintPartialRedraw *get_imapaintpartial(void)
128 {
129         return &imapaintpartial;
130 }
131
132 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
133 {
134         imapaintpartial = *ippr;
135 }
136
137 /* UNDO */
138 typedef enum {
139         COPY = 0,
140         RESTORE = 1,
141         RESTORE_COPY = 2
142 } CopyMode;
143
144 static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, CopyMode mode)
145 {
146         if (mode == COPY) {
147                 /* copy or swap contents of tile->rect and region in ibuf->rect */
148                 IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
149                             tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
150
151                 if (ibuf->rect_float) {
152                         SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
153                 }
154                 else {
155                         SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
156                 }
157         }
158         else {
159                 if (mode == RESTORE_COPY) {
160                         IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
161                                     tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
162                 }
163                 /* swap to the tmpbuf for easy copying */
164                 if (ibuf->rect_float) {
165                         SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
166                 }
167                 else {
168                         SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
169                 }
170
171                 IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
172                             tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
173
174                 if (mode == RESTORE) {
175                         if (ibuf->rect_float) {
176                                 SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
177                         }
178                         else {
179                                 SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
180                         }
181                 }
182         }
183 }
184
185 void *image_undo_find_tile(Image *ima, ImBuf *ibuf, int x_tile, int y_tile, unsigned short **mask, bool validate)
186 {
187         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
188         UndoImageTile *tile;
189         short use_float = ibuf->rect_float ? 1 : 0;
190
191         for (tile = lb->first; tile; tile = tile->next) {
192                 if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source) {
193                         if (tile->use_float == use_float) {
194                                 if (STREQ(tile->idname, ima->id.name) && STREQ(tile->ibufname, ibuf->name)) {
195                                         if (mask) {
196                                                 /* allocate mask if requested */
197                                                 if (!tile->mask) {
198                                                         tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
199                                                                                  "UndoImageTile.mask");
200                                                 }
201
202                                                 *mask = tile->mask;
203                                         }
204                                         if (validate)
205                                                 tile->valid = true;
206
207                                         return tile->rect.pt;
208                                 }
209                         }
210                 }
211         }
212         
213         return NULL;
214 }
215
216 void *image_undo_push_tile(Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile, unsigned short **mask, bool **valid, bool proj, bool find_prev)
217 {
218         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
219         UndoImageTile *tile;
220         int allocsize;
221         short use_float = ibuf->rect_float ? 1 : 0;
222         void *data;
223
224         /* check if tile is already pushed */
225
226         /* in projective painting we keep accounting of tiles, so if we need one pushed, just push! */
227         if (find_prev) {
228                 data = image_undo_find_tile(ima, ibuf, x_tile, y_tile, mask, true);
229                 if (data)
230                         return data;
231         }
232
233         if (*tmpibuf == NULL)
234                 *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
235         
236         tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
237         BLI_strncpy(tile->idname, ima->id.name, sizeof(tile->idname));
238         tile->x = x_tile;
239         tile->y = y_tile;
240
241         /* add mask explicitly here */
242         if (mask)
243                 *mask = tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
244                                          "UndoImageTile.mask");
245
246         allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
247         allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
248         tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
249
250         BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
251
252         tile->gen_type = ima->gen_type;
253         tile->source = ima->source;
254         tile->use_float = use_float;
255         tile->valid = true;
256         tile->ima = ima;
257
258         if (valid)
259                 *valid = &tile->valid;
260
261         undo_copy_tile(tile, *tmpibuf, ibuf, COPY);
262
263         if (proj)
264                 BLI_spin_lock(&undolock);
265
266         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, allocsize);
267         BLI_addtail(lb, tile);
268
269         if (proj)
270                 BLI_spin_unlock(&undolock);
271
272         return tile->rect.pt;
273 }
274
275 void image_undo_remove_masks(void)
276 {
277         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
278         UndoImageTile *tile;
279
280         for (tile = lb->first; tile; tile = tile->next) {
281                 if (tile->mask) {
282                         MEM_freeN(tile->mask);
283                         tile->mask = NULL;
284                 }
285         }
286 }
287
288 static void image_undo_restore_runtime(ListBase *lb)
289 {
290         ImBuf *ibuf, *tmpibuf;
291         UndoImageTile *tile;
292
293         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
294                                  IB_rectfloat | IB_rect);
295
296         for (tile = lb->first; tile; tile = tile->next) {
297                 Image *ima = tile->ima;
298                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
299
300                 undo_copy_tile(tile, tmpibuf, ibuf, RESTORE);
301
302                 GPU_free_image(ima); /* force OpenGL reload (maybe partial update will operate better?) */
303                 if (ibuf->rect_float)
304                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
305                 if (ibuf->mipmap[0])
306                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
307                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
308
309                 BKE_image_release_ibuf(ima, ibuf, NULL);
310         }
311
312         IMB_freeImBuf(tmpibuf);
313 }
314
315 void ED_image_undo_restore(bContext *C, ListBase *lb)
316 {
317         Main *bmain = CTX_data_main(C);
318         Image *ima = NULL;
319         ImBuf *ibuf, *tmpibuf;
320         UndoImageTile *tile;
321
322         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
323                                  IB_rectfloat | IB_rect);
324
325         for (tile = lb->first; tile; tile = tile->next) {
326                 short use_float;
327
328                 /* find image based on name, pointer becomes invalid with global undo */
329                 if (ima && STREQ(tile->idname, ima->id.name)) {
330                         /* ima is valid */
331                 }
332                 else {
333                         ima = BLI_findstring(&bmain->image, tile->idname, offsetof(ID, name));
334                 }
335
336                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
337
338                 if (ima && ibuf && !STREQ(tile->ibufname, ibuf->name)) {
339                         /* current ImBuf filename was changed, probably current frame
340                          * was changed when painting on image sequence, rather than storing
341                          * full image user (which isn't so obvious, btw) try to find ImBuf with
342                          * matched file name in list of already loaded images */
343
344                         BKE_image_release_ibuf(ima, ibuf, NULL);
345
346                         ibuf = BKE_image_get_ibuf_with_name(ima, tile->ibufname);
347                 }
348
349                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
350                         BKE_image_release_ibuf(ima, ibuf, NULL);
351                         continue;
352                 }
353
354                 if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
355                         BKE_image_release_ibuf(ima, ibuf, NULL);
356                         continue;
357                 }
358
359                 use_float = ibuf->rect_float ? 1 : 0;
360
361                 if (use_float != tile->use_float) {
362                         BKE_image_release_ibuf(ima, ibuf, NULL);
363                         continue;
364                 }
365
366                 undo_copy_tile(tile, tmpibuf, ibuf, RESTORE_COPY);
367
368                 GPU_free_image(ima); /* force OpenGL reload */
369                 if (ibuf->rect_float)
370                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
371                 if (ibuf->mipmap[0])
372                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
373                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
374
375                 DAG_id_tag_update(&ima->id, 0);
376
377                 BKE_image_release_ibuf(ima, ibuf, NULL);
378         }
379
380         IMB_freeImBuf(tmpibuf);
381 }
382
383 void ED_image_undo_free(ListBase *lb)
384 {
385         UndoImageTile *tile;
386
387         for (tile = lb->first; tile; tile = tile->next)
388                 MEM_freeN(tile->rect.pt);
389 }
390
391 static void image_undo_end(void)
392 {
393         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
394         UndoImageTile *tile;
395         int deallocsize = 0;
396         int allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
397
398         /* first dispose of invalid tiles (may happen due to drag dot for instance) */
399         for (tile = lb->first; tile;) {
400                 if (!tile->valid) {
401                         UndoImageTile *tmp_tile = tile->next;
402                         deallocsize += allocsize * ((tile->use_float) ? sizeof(float) : sizeof(char));
403                         MEM_freeN(tile->rect.pt);
404                         BLI_freelinkN (lb, tile);
405                         tile = tmp_tile;
406                 }
407                 else {
408                         tile = tile->next;
409                 }
410         }
411
412         /* don't forget to remove the size of deallocated tiles */
413         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, -deallocsize);
414
415         ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
416 }
417
418 static void image_undo_invalidate(void)
419 {
420         UndoImageTile *tile;
421         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
422
423         for (tile = lb->first; tile; tile = tile->next)
424                 tile->valid = false;
425 }
426
427 /* Imagepaint Partial Redraw & Dirty Region */
428
429 void ED_imapaint_clear_partial_redraw(void)
430 {
431         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
432 }
433
434 void imapaint_region_tiles(ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th)
435 {
436         int srcx = 0, srcy = 0;
437
438         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
439
440         *tw = ((x + w - 1) >> IMAPAINT_TILE_BITS);
441         *th = ((y + h - 1) >> IMAPAINT_TILE_BITS);
442         *tx = (x >> IMAPAINT_TILE_BITS);
443         *ty = (y >> IMAPAINT_TILE_BITS);
444 }
445
446 void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h, bool find_old)
447 {
448         ImBuf *tmpibuf = NULL;
449         int tilex, tiley, tilew, tileh, tx, ty;
450         int srcx = 0, srcy = 0;
451
452         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
453
454         if (w == 0 || h == 0)
455                 return;
456         
457         if (!imapaintpartial.enabled) {
458                 imapaintpartial.x1 = x;
459                 imapaintpartial.y1 = y;
460                 imapaintpartial.x2 = x + w;
461                 imapaintpartial.y2 = y + h;
462                 imapaintpartial.enabled = 1;
463         }
464         else {
465                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
466                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
467                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
468                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
469         }
470
471         imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
472
473         for (ty = tiley; ty <= tileh; ty++)
474                 for (tx = tilex; tx <= tilew; tx++)
475                         image_undo_push_tile(ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
476
477         ibuf->userflags |= IB_BITMAPDIRTY;
478         
479         if (tmpibuf)
480                 IMB_freeImBuf(tmpibuf);
481 }
482
483 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
484 {
485         if (imapaintpartial.x1 != imapaintpartial.x2 &&
486             imapaintpartial.y1 != imapaintpartial.y2)
487         {
488                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
489                                                           imapaintpartial.x2, imapaintpartial.y2);
490         }
491         
492         if (ibuf->mipmap[0])
493                 ibuf->userflags |= IB_MIPMAP_INVALID;
494
495         /* todo: should set_tpage create ->rect? */
496         if (texpaint || (sima && sima->lock)) {
497                 int w = imapaintpartial.x2 - imapaintpartial.x1;
498                 int h = imapaintpartial.y2 - imapaintpartial.y1;
499                 if (w && h) {
500                         /* Testing with partial update in uv editor too */
501                         GPU_paint_update_image(image, (sima ? &sima->iuser : NULL), imapaintpartial.x1, imapaintpartial.y1, w, h);
502                 }
503         }
504 }
505
506 /* paint blur kernels. Projective painting enforces use of a 2x2 kernel due to lagging */
507 BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
508 {
509         int i, j;
510         BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
511         float radius;
512         int side;
513         BlurKernelType type = br->blur_mode;
514
515         if (proj) {
516                 radius = 0.5f;
517                 
518                 side = kernel->side = 2;
519                 kernel->side_squared = kernel->side * kernel->side;
520                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
521                 kernel->pixel_len = radius;
522         }
523         else {
524                 if (br->blur_kernel_radius <= 0)
525                         br->blur_kernel_radius = 1;
526                 
527                 radius = br->blur_kernel_radius;
528                                         
529                 side = kernel->side = radius * 2 + 1;
530                 kernel->side_squared = kernel->side * kernel->side;
531                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
532                 kernel->pixel_len = br->blur_kernel_radius;
533         }
534         
535         switch (type) {
536                 case KERNEL_BOX:
537                         for (i = 0; i < kernel->side_squared; i++)
538                                 kernel->wdata[i] = 1.0;
539                         break;
540
541                 case KERNEL_GAUSSIAN:
542                 {
543                         /* at 3.0 standard deviations distance, kernel is about zero */                 
544                         float standard_dev = radius / 3.0f; 
545                         
546                         /* make the necessary adjustment to the value for use in the normal distribution formula */
547                         standard_dev = -standard_dev * standard_dev * 2;
548
549                         for (i = 0; i < side; i++) {
550                                 for (j = 0; j < side; j++) {
551                                         float idist = radius - i;
552                                         float jdist = radius - j;
553                                         float value = exp((idist * idist + jdist * jdist) / standard_dev);
554                                         
555                                         kernel->wdata[i + j * side] = value;
556                                 }
557                         }
558
559                         break;
560                 }
561
562                 default:
563                         printf("unidentified kernel type, aborting\n");
564                         MEM_freeN(kernel->wdata);
565                         MEM_freeN(kernel);
566                         return NULL;
567         }
568
569         return kernel;
570 }
571
572 void paint_delete_blur_kernel(BlurKernel *kernel)
573 {
574         if (kernel->wdata)
575                 MEM_freeN(kernel->wdata);
576 }
577
578 /************************ image paint poll ************************/
579
580 static Brush *image_paint_brush(bContext *C)
581 {
582         Scene *scene = CTX_data_scene(C);
583         ToolSettings *settings = scene->toolsettings;
584
585         return BKE_paint_brush(&settings->imapaint.paint);
586 }
587
588 static int image_paint_poll(bContext *C)
589 {
590         Object *obact;
591
592         if (!image_paint_brush(C))
593                 return 0;
594
595         obact = CTX_data_active_object(C);
596         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
597                 return 1;
598         }
599         else {
600                 SpaceImage *sima = CTX_wm_space_image(C);
601
602                 if (sima) {
603                         ARegion *ar = CTX_wm_region(C);
604
605                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
606                                 return 1;
607                         }
608                 }
609         }
610
611         return 0;
612 }
613
614 static int image_paint_2d_clone_poll(bContext *C)
615 {
616         Brush *brush = image_paint_brush(C);
617
618         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
619                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
620                         if (brush->clone.image)
621                                 return 1;
622         
623         return 0;
624 }
625
626 /************************ paint operator ************************/
627 typedef enum TexPaintMode {
628         PAINT_MODE_2D,
629         PAINT_MODE_3D_PROJECT
630 } TexPaintMode;
631
632 typedef struct PaintOperation {
633         TexPaintMode mode;
634
635         void *custom_paint;
636
637         float prevmouse[2];
638         float startmouse[2];
639         double starttime;
640
641         void *cursor;
642         ViewContext vc;
643 } PaintOperation;
644
645 bool paint_use_opacity_masking(Brush *brush)
646 {
647         return (brush->flag & BRUSH_AIRBRUSH) ||
648                (brush->flag & BRUSH_DRAG_DOT) ||
649                (brush->flag & BRUSH_ANCHORED) ||
650                (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
651                (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
652                (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
653                (brush->flag & BRUSH_USE_GRADIENT) ||
654                (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
655                     false : true;
656 }
657
658 void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
659                            float pressure, float color[3], struct ColorManagedDisplay *display)
660 {
661         if (invert)
662                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
663         else {
664                 if (br->flag & BRUSH_USE_GRADIENT) {
665                         float color_gr[4];
666                         switch (br->gradient_stroke_mode) {
667                                 case BRUSH_GRADIENT_PRESSURE:
668                                         do_colorband(br->gradient, pressure, color_gr);
669                                         break;
670                                 case BRUSH_GRADIENT_SPACING_REPEAT:
671                                 {
672                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
673                                         do_colorband(br->gradient, coord, color_gr);
674                                         break;
675                                 }
676                                 case BRUSH_GRADIENT_SPACING_CLAMP:
677                                 {
678                                         do_colorband(br->gradient, distance / br->gradient_spacing, color_gr);
679                                         break;
680                                 }
681                         }
682                         copy_v3_v3(color, color_gr);
683                 }
684                 else
685                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
686         }
687         if (color_correction)
688                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
689 }
690
691 void paint_brush_init_tex(Brush *brush)
692 {
693         /* init mtex nodes */
694         if (brush) {
695                 MTex *mtex = &brush->mtex;
696                 if (mtex->tex && mtex->tex->nodetree)
697                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
698                 mtex = &brush->mask_mtex;
699                 if (mtex->tex && mtex->tex->nodetree)
700                         ntreeTexBeginExecTree(mtex->tex->nodetree);
701         }
702 }
703
704 void paint_brush_exit_tex(Brush *brush)
705 {
706         if (brush) {
707                 MTex *mtex = &brush->mtex;
708                 if (mtex->tex && mtex->tex->nodetree)
709                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
710                 mtex = &brush->mask_mtex;
711                 if (mtex->tex && mtex->tex->nodetree)
712                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
713         }
714 }
715
716 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
717 {
718         PaintOperation *pop = (PaintOperation *)customdata;
719
720         if (pop) {
721                 glEnable(GL_LINE_SMOOTH);
722                 glEnable(GL_BLEND);
723
724                 glLineWidth(4.0);
725                 glColor4ub(0, 0, 0, 255);
726                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
727                 glLineWidth(2.0);
728                 glColor4ub(255, 255, 255, 255);
729                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
730
731                 glDisable(GL_BLEND);
732                 glDisable(GL_LINE_SMOOTH);
733         }
734 }
735
736
737 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
738 {
739         Scene *scene = CTX_data_scene(C);
740         ToolSettings *settings = scene->toolsettings;
741         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
742         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
743         int mode = RNA_enum_get(op->ptr, "mode");
744         view3d_set_viewcontext(C, &pop->vc);
745
746         copy_v2_v2(pop->prevmouse, mouse);
747         copy_v2_v2(pop->startmouse, mouse);
748
749         /* initialize from context */
750         if (CTX_wm_region_view3d(C)) {
751                 Object *ob = OBACT;
752                 bool uvs, mat, tex, stencil;
753                 if (!BKE_paint_proj_mesh_data_check(scene, ob, &uvs, &mat, &tex, &stencil)) {
754                         BKE_paint_data_warning(op->reports, uvs, mat, tex, stencil);
755                         MEM_freeN(pop);
756                         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
757                         return NULL;                    
758                 }
759                 pop->mode = PAINT_MODE_3D_PROJECT;
760                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
761         }
762         else {
763                 pop->mode = PAINT_MODE_2D;
764                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
765         }
766
767         if (!pop->custom_paint) {
768                 MEM_freeN(pop);
769                 return NULL;
770         }
771
772         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
773                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
774         }
775         
776         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
777         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
778                                  ED_image_undo_restore, ED_image_undo_free, NULL);
779
780         return pop;
781 }
782
783 /* restore painting image to previous state. Used for anchored and drag-dot style brushes*/
784 static void paint_stroke_restore(void)
785 {
786         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
787         image_undo_restore_runtime(lb);
788         image_undo_invalidate();
789 }
790
791 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
792 {
793         PaintOperation *pop = paint_stroke_mode_data(stroke);
794         Scene *scene = CTX_data_scene(C);
795         ToolSettings *toolsettings = CTX_data_tool_settings(C);
796         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
797         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
798
799         float alphafac = (brush->flag & BRUSH_ACCUMULATE) ? ups->overlap_factor : 1.0f;
800
801         /* initial brush values. Maybe it should be considered moving these to stroke system */
802         float startalpha = BKE_brush_alpha_get(scene, brush);
803
804         float mouse[2];
805         float pressure;
806         float size;
807         float distance = paint_stroke_distance_get(stroke);
808         int eraser;
809
810         RNA_float_get_array(itemptr, "mouse", mouse);
811         pressure = RNA_float_get(itemptr, "pressure");
812         eraser = RNA_boolean_get(itemptr, "pen_flip");
813         size = max_ff(1.0f, RNA_float_get(itemptr, "size"));
814
815         /* stroking with fill tool only acts on stroke end */
816         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
817                 copy_v2_v2(pop->prevmouse, mouse);
818                 return;
819         }
820
821         if (BKE_brush_use_alpha_pressure(scene, brush))
822                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure * alphafac));
823         else
824                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
825
826         if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
827                 paint_stroke_restore();
828         }
829
830         if (pop->mode == PAINT_MODE_3D_PROJECT) {
831                 paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
832         }
833         else {
834                 paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
835         }
836
837         copy_v2_v2(pop->prevmouse, mouse);
838
839         /* restore brush values */
840         BKE_brush_alpha_set(scene, brush, startalpha);
841 }
842
843 static void paint_stroke_redraw(const bContext *C, struct PaintStroke *stroke, bool final)
844 {
845         PaintOperation *pop = paint_stroke_mode_data(stroke);
846
847         if (pop->mode == PAINT_MODE_3D_PROJECT) {
848                 paint_proj_redraw(C, pop->custom_paint, final);
849         }
850         else {
851                 paint_2d_redraw(C, pop->custom_paint, final);
852         }
853 }
854
855 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
856 {
857         Scene *scene = CTX_data_scene(C);
858         ToolSettings *toolsettings = scene->toolsettings;
859         PaintOperation *pop = paint_stroke_mode_data(stroke);
860         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
861
862         toolsettings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
863
864         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
865                 if (brush->flag & BRUSH_USE_GRADIENT) {
866                         if (pop->mode == PAINT_MODE_2D) {
867                                 paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint);
868                         }
869                         else {
870                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
871                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
872                                 /* two redraws, one for GPU update, one for notification */
873                                 paint_proj_redraw(C, pop->custom_paint, false);
874                                 paint_proj_redraw(C, pop->custom_paint, true);
875                         }
876                 }
877                 else {
878                         if (pop->mode == PAINT_MODE_2D) {
879                                 float color[3];
880
881                                 srgb_to_linearrgb_v3_v3(color, BKE_brush_color_get(scene, brush));
882                                 paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint);
883                         }
884                         else {
885                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
886                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
887                                 /* two redraws, one for GPU update, one for notification */
888                                 paint_proj_redraw(C, pop->custom_paint, false);
889                                 paint_proj_redraw(C, pop->custom_paint, true);
890                         }
891                 }
892         }
893         if (pop->mode == PAINT_MODE_3D_PROJECT) {
894                 paint_proj_stroke_done(pop->custom_paint);
895         }
896         else {
897                 paint_2d_stroke_done(pop->custom_paint);
898         }
899
900         if (pop->cursor) {
901                 WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
902         }
903
904         image_undo_end();
905
906         /* duplicate warning, see texpaint_init */
907 #if 0
908         if (pop->s.warnmultifile)
909                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
910         if (pop->s.warnpackedfile)
911                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
912 #endif
913         MEM_freeN(pop);
914 }
915
916 static bool paint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
917 {
918         PaintOperation *pop;
919
920         /* TODO Should avoid putting this here. Instead, last position should be requested
921          * from stroke system. */
922
923         if (!(pop = texture_paint_init(C, op, mouse))) {
924                 return false;
925         }
926
927         paint_stroke_set_mode_data(op->customdata, pop);
928
929         return true;
930 }
931
932
933 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
934 {
935         int retval;
936
937         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
938                                           paint_stroke_update_step,
939                                           paint_stroke_redraw,
940                                           paint_stroke_done, event->type);
941
942         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
943                 paint_stroke_data_free(op);
944                 return OPERATOR_FINISHED;
945         }
946         /* add modal handler */
947         WM_event_add_modal_handler(C, op);
948
949         OPERATOR_RETVAL_CHECK(retval);
950         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
951
952         return OPERATOR_RUNNING_MODAL;
953 }
954
955 static int paint_exec(bContext *C, wmOperator *op)
956 {
957         PropertyRNA *strokeprop;
958         PointerRNA firstpoint;
959         float mouse[2];
960
961         strokeprop = RNA_struct_find_property(op->ptr, "stroke");
962
963         if (!RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint))
964                 return OPERATOR_CANCELLED;
965
966         RNA_float_get_array(&firstpoint, "mouse", mouse);
967
968         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
969                                           paint_stroke_update_step,
970                                           paint_stroke_redraw,
971                                           paint_stroke_done, 0);
972         /* frees op->customdata */
973         return paint_stroke_exec(C, op);
974 }
975
976 void PAINT_OT_image_paint(wmOperatorType *ot)
977 {
978         /* identifiers */
979         ot->name = "Image Paint";
980         ot->idname = "PAINT_OT_image_paint";
981         ot->description = "Paint a stroke into the image";
982
983         /* api callbacks */
984         ot->invoke = paint_invoke;
985         ot->modal = paint_stroke_modal;
986         ot->exec = paint_exec;
987         ot->poll = image_paint_poll;
988         ot->cancel = paint_stroke_cancel;
989
990         /* flags */
991         ot->flag = OPTYPE_BLOCKING;
992
993         paint_stroke_operator_properties(ot);
994 }
995
996
997 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
998 {
999         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1000
1001         if (!rv3d) {
1002                 SpaceImage *sima = CTX_wm_space_image(C);
1003
1004                 if (sima->mode == SI_MODE_PAINT) {
1005                         ARegion *ar = CTX_wm_region(C);
1006                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
1007
1008                         return 1;
1009                 }
1010         }
1011
1012         *zoomx = *zoomy = 1;
1013
1014         return 0;
1015 }
1016
1017 /************************ cursor drawing *******************************/
1018
1019 static void toggle_paint_cursor(bContext *C, int enable)
1020 {
1021         wmWindowManager *wm = CTX_wm_manager(C);
1022         Scene *scene = CTX_data_scene(C);
1023         ToolSettings *settings = scene->toolsettings;
1024
1025         if (settings->imapaint.paintcursor && !enable) {
1026                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
1027                 settings->imapaint.paintcursor = NULL;
1028                 paint_cursor_delete_textures();
1029         }
1030         else if (enable)
1031                 paint_cursor_start(C, image_paint_poll);
1032 }
1033
1034 /* enable the paint cursor if it isn't already.
1035  *
1036  * purpose is to make sure the paint cursor is shown if paint
1037  * mode is enabled in the image editor. the paint poll will
1038  * ensure that the cursor is hidden when not in paint mode */
1039 void ED_space_image_paint_update(wmWindowManager *wm, Scene *scene)
1040 {
1041         ToolSettings *settings = scene->toolsettings;
1042         wmWindow *win;
1043         ScrArea *sa;
1044         ImagePaintSettings *imapaint = &settings->imapaint;
1045         bool enabled = false;
1046
1047         for (win = wm->windows.first; win; win = win->next)
1048                 for (sa = win->screen->areabase.first; sa; sa = sa->next)
1049                         if (sa->spacetype == SPACE_IMAGE)
1050                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
1051                                         enabled = true;
1052
1053         if (enabled) {
1054                 BKE_paint_init(scene, ePaintTexture2D, PAINT_CURSOR_TEXTURE_PAINT);
1055
1056                 paint_cursor_start_explicit(&imapaint->paint, wm, image_paint_poll);
1057         }
1058         else {
1059                 paint_cursor_delete_textures();
1060         }
1061 }
1062
1063 /************************ grab clone operator ************************/
1064
1065 typedef struct GrabClone {
1066         float startoffset[2];
1067         int startx, starty;
1068 } GrabClone;
1069
1070 static void grab_clone_apply(bContext *C, wmOperator *op)
1071 {
1072         Brush *brush = image_paint_brush(C);
1073         float delta[2];
1074
1075         RNA_float_get_array(op->ptr, "delta", delta);
1076         add_v2_v2(brush->clone.offset, delta);
1077         ED_region_tag_redraw(CTX_wm_region(C));
1078 }
1079
1080 static int grab_clone_exec(bContext *C, wmOperator *op)
1081 {
1082         grab_clone_apply(C, op);
1083
1084         return OPERATOR_FINISHED;
1085 }
1086
1087 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1088 {
1089         Brush *brush = image_paint_brush(C);
1090         GrabClone *cmv;
1091
1092         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
1093         copy_v2_v2(cmv->startoffset, brush->clone.offset);
1094         cmv->startx = event->x;
1095         cmv->starty = event->y;
1096         op->customdata = cmv;
1097
1098         WM_event_add_modal_handler(C, op);
1099
1100         return OPERATOR_RUNNING_MODAL;
1101 }
1102
1103 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
1104 {
1105         Brush *brush = image_paint_brush(C);
1106         ARegion *ar = CTX_wm_region(C);
1107         GrabClone *cmv = op->customdata;
1108         float startfx, startfy, fx, fy, delta[2];
1109         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
1110
1111         switch (event->type) {
1112                 case LEFTMOUSE:
1113                 case MIDDLEMOUSE:
1114                 case RIGHTMOUSE: // XXX hardcoded
1115                         MEM_freeN(op->customdata);
1116                         return OPERATOR_FINISHED;
1117                 case MOUSEMOVE:
1118                         /* mouse moved, so move the clone image */
1119                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
1120                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
1121
1122                         delta[0] = fx - startfx;
1123                         delta[1] = fy - startfy;
1124                         RNA_float_set_array(op->ptr, "delta", delta);
1125
1126                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
1127
1128                         grab_clone_apply(C, op);
1129                         break;
1130         }
1131
1132         return OPERATOR_RUNNING_MODAL;
1133 }
1134
1135 static void grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
1136 {
1137         MEM_freeN(op->customdata);
1138 }
1139
1140 void PAINT_OT_grab_clone(wmOperatorType *ot)
1141 {
1142         /* identifiers */
1143         ot->name = "Grab Clone";
1144         ot->idname = "PAINT_OT_grab_clone";
1145         ot->description = "Move the clone source image";
1146         
1147         /* api callbacks */
1148         ot->exec = grab_clone_exec;
1149         ot->invoke = grab_clone_invoke;
1150         ot->modal = grab_clone_modal;
1151         ot->cancel = grab_clone_cancel;
1152         ot->poll = image_paint_2d_clone_poll;
1153
1154         /* flags */
1155         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1156
1157         /* properties */
1158         RNA_def_float_vector(ot->srna, "delta", 2, NULL, -FLT_MAX, FLT_MAX, "Delta", "Delta offset of clone image in 0.0..1.0 coordinates", -1.0f, 1.0f);
1159 }
1160
1161 /******************** sample color operator ********************/
1162 typedef struct {
1163         bool show_cursor;
1164         short event_type;
1165         float initcolor[3];
1166         bool sample_palette;
1167 }       SampleColorData;
1168
1169
1170 static void sample_color_update_header(SampleColorData *data, bContext *C)
1171 {
1172         char msg[UI_MAX_DRAW_STR];
1173         ScrArea *sa = CTX_wm_area(C);
1174
1175         if (sa) {
1176                 BLI_snprintf(msg, sizeof(msg),
1177                              IFACE_("Sample color for %s"),
1178                              !data->sample_palette ?
1179                              IFACE_("Brush. Use Left Click to sample for palette instead") :
1180                              IFACE_("Palette. Use Left Click to sample more colors"));
1181                 ED_area_headerprint(sa, msg);
1182         }
1183 }
1184
1185 static int sample_color_exec(bContext *C, wmOperator *op)
1186 {
1187         Paint *paint = BKE_paint_get_active_from_context(C);
1188         Brush *brush = BKE_paint_brush(paint);
1189         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1190         ARegion *ar = CTX_wm_region(C);
1191         wmWindow *win = CTX_wm_window(C);
1192         const bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1193         int location[2];
1194         paint->flags &= ~PAINT_SHOW_BRUSH;
1195
1196         /* force redraw without cursor */
1197         WM_paint_cursor_tag_redraw(win, ar);
1198         WM_redraw_windows(C);
1199
1200         RNA_int_get_array(op->ptr, "location", location);
1201         const bool use_palette = RNA_boolean_get(op->ptr, "palette");
1202         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
1203
1204         paint_sample_color(C, ar, location[0], location[1], use_sample_texture, use_palette);
1205
1206         if (show_cursor) {
1207                 paint->flags |= PAINT_SHOW_BRUSH;
1208         }
1209
1210         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1211         
1212         return OPERATOR_FINISHED;
1213 }
1214
1215 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1216 {
1217         Scene *scene = CTX_data_scene(C);
1218         Paint *paint = BKE_paint_get_active_from_context(C);
1219         Brush *brush = BKE_paint_brush(paint);
1220         SampleColorData *data = MEM_mallocN(sizeof(SampleColorData), "sample color custom data");
1221         ARegion *ar = CTX_wm_region(C);
1222         wmWindow *win = CTX_wm_window(C);
1223
1224         data->event_type = event->type;
1225         data->show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1226         copy_v3_v3(data->initcolor, BKE_brush_color_get(scene, brush));
1227         data->sample_palette = false;
1228         op->customdata = data;
1229         paint->flags &= ~PAINT_SHOW_BRUSH;
1230
1231         sample_color_update_header(data, C);
1232
1233         WM_event_add_modal_handler(C, op);
1234
1235         /* force redraw without cursor */
1236         WM_paint_cursor_tag_redraw(win, ar);
1237         WM_redraw_windows(C);
1238
1239         RNA_int_set_array(op->ptr, "location", event->mval);
1240
1241         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1242         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
1243
1244         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
1245         WM_cursor_modal_set(win, BC_EYEDROPPER_CURSOR);
1246
1247         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1248
1249         return OPERATOR_RUNNING_MODAL;
1250 }
1251
1252 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
1253 {
1254         Scene *scene = CTX_data_scene(C);
1255         SampleColorData *data = op->customdata;
1256         Paint *paint = BKE_paint_get_active_from_context(C);
1257         Brush *brush = BKE_paint_brush(paint);
1258
1259         if ((event->type == data->event_type) && (event->val == KM_RELEASE)) {
1260                 ScrArea *sa = CTX_wm_area(C);
1261
1262                 if (data->show_cursor) {
1263                         paint->flags |= PAINT_SHOW_BRUSH;
1264                 }
1265
1266                 if (data->sample_palette) {
1267                         BKE_brush_color_set(scene, brush, data->initcolor);
1268                         RNA_boolean_set(op->ptr, "palette", true);
1269                 }
1270                 WM_cursor_modal_restore(CTX_wm_window(C));
1271                 MEM_freeN(data);
1272                 ED_area_headerprint(sa, NULL);
1273
1274                 return OPERATOR_FINISHED;
1275         }
1276
1277         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1278         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
1279
1280         switch (event->type) {
1281                 case MOUSEMOVE:
1282                 {
1283                         ARegion *ar = CTX_wm_region(C);
1284                         RNA_int_set_array(op->ptr, "location", event->mval);
1285                         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
1286                         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1287                         break;
1288                 }
1289
1290                 case LEFTMOUSE:
1291                         if (event->val == KM_PRESS) {
1292                                 ARegion *ar = CTX_wm_region(C);
1293                                 RNA_int_set_array(op->ptr, "location", event->mval);
1294                                 paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, true);
1295                                 if (!data->sample_palette) {
1296                                         data->sample_palette = true;
1297                                         sample_color_update_header(data, C);
1298                                 }
1299                                 WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1300                         }
1301                         break;
1302         }
1303
1304         return OPERATOR_RUNNING_MODAL;
1305 }
1306
1307 static int sample_color_poll(bContext *C)
1308 {
1309         return (image_paint_poll(C) || vertex_paint_poll(C));
1310 }
1311
1312 void PAINT_OT_sample_color(wmOperatorType *ot)
1313 {
1314         /* identifiers */
1315         ot->name = "Sample Color";
1316         ot->idname = "PAINT_OT_sample_color";
1317         ot->description = "Use the mouse to sample a color in the image";
1318         
1319         /* api callbacks */
1320         ot->exec = sample_color_exec;
1321         ot->invoke = sample_color_invoke;
1322         ot->modal = sample_color_modal;
1323         ot->poll = sample_color_poll;
1324
1325         /* flags */
1326         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1327
1328         /* properties */
1329         PropertyRNA *prop;
1330
1331         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1332         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1333
1334         RNA_def_boolean(ot->srna, "merged", 0, "Sample Merged", "Sample the output display color");
1335         RNA_def_boolean(ot->srna, "palette", 0, "Add to Palette", "");
1336 }
1337
1338 /******************** texture paint toggle operator ********************/
1339
1340 static int texture_paint_toggle_poll(bContext *C)
1341 {
1342         Object *ob = CTX_data_active_object(C);
1343         if (ob == NULL || ob->type != OB_MESH)
1344                 return 0;
1345         if (!ob->data || ((ID *)ob->data)->lib)
1346                 return 0;
1347         if (CTX_data_edit_object(C))
1348                 return 0;
1349
1350         return 1;
1351 }
1352
1353 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1354 {
1355         Scene *scene = CTX_data_scene(C);
1356         Object *ob = CTX_data_active_object(C);
1357         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1358         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1359
1360         if (!is_mode_set) {
1361                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1362                         return OPERATOR_CANCELLED;
1363                 }
1364         }
1365
1366         if (ob->mode & mode_flag) {
1367                 ob->mode &= ~mode_flag;
1368
1369                 if (U.glreslimit != 0)
1370                         GPU_free_images();
1371                 GPU_paint_set_mipmap(1);
1372
1373                 toggle_paint_cursor(C, 0);
1374         }
1375         else {
1376                 bScreen *sc;
1377                 Main *bmain = CTX_data_main(C);
1378                 Image *ima = NULL;
1379                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1380
1381                 /* This has to stay here to regenerate the texture paint
1382                  * cache in case we are loading a file */
1383                 BKE_texpaint_slots_refresh_object(scene, ob);
1384
1385                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
1386                 
1387                 /* entering paint mode also sets image to editors */
1388                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1389                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1390
1391                         if (ma && ma->texpaintslot)
1392                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1393                 }
1394                 else if (imapaint->mode == IMAGEPAINT_MODE_IMAGE) {
1395                         ima = imapaint->canvas;
1396                 }       
1397                 
1398                 if (ima) {
1399                         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1400                                 ScrArea *sa;
1401                                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1402                                         SpaceLink *sl;
1403                                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
1404                                                 if (sl->spacetype == SPACE_IMAGE) {
1405                                                         SpaceImage *sima = (SpaceImage *)sl;
1406                                                         
1407                                                         if (!sima->pin)
1408                                                                 ED_space_image_set(sima, scene, scene->obedit, ima);
1409                                                 }
1410                                         }
1411                                 }
1412                         }
1413                 }
1414                 
1415                 ob->mode |= mode_flag;
1416
1417                 BKE_paint_init(scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT);
1418
1419                 if (U.glreslimit != 0)
1420                         GPU_free_images();
1421                 GPU_paint_set_mipmap(0);
1422
1423                 toggle_paint_cursor(C, 1);
1424         }
1425
1426         GPU_drawobject_free(ob->derivedFinal);
1427         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1428
1429         return OPERATOR_FINISHED;
1430 }
1431
1432 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1433 {
1434         /* identifiers */
1435         ot->name = "Texture Paint Toggle";
1436         ot->idname = "PAINT_OT_texture_paint_toggle";
1437         ot->description = "Toggle texture paint mode in 3D view";
1438         
1439         /* api callbacks */
1440         ot->exec = texture_paint_toggle_exec;
1441         ot->poll = texture_paint_toggle_poll;
1442
1443         /* flags */
1444         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1445 }
1446
1447
1448 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1449 {
1450         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1451         Brush *br = image_paint_brush(C);
1452         if (ups->flag & UNIFIED_PAINT_COLOR) {
1453                 swap_v3_v3(ups->rgb, ups->secondary_rgb);
1454         }
1455         else if (br) {
1456                 swap_v3_v3(br->rgb, br->secondary_rgb);
1457         }
1458         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, br);
1459
1460         return OPERATOR_FINISHED;
1461 }
1462
1463 static int brush_colors_flip_poll(bContext *C)
1464 {
1465         if (image_paint_poll(C)) {
1466                 Brush *br = image_paint_brush(C);
1467                 if (br->imagepaint_tool == PAINT_TOOL_DRAW)
1468                         return 1;
1469         }
1470
1471         return 0;
1472 }
1473
1474 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1475 {
1476         /* identifiers */
1477         ot->name = "Brush Colors Flip";
1478         ot->idname = "PAINT_OT_brush_colors_flip";
1479         ot->description = "Toggle foreground and background brush colors";
1480
1481         /* api callbacks */
1482         ot->exec = brush_colors_flip_exec;
1483         ot->poll = brush_colors_flip_poll;
1484
1485         /* flags */
1486         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1487 }
1488
1489
1490 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1491 {
1492         SpaceImage *sima = CTX_wm_space_image(C);
1493         Image *ima = sima->image;
1494
1495         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
1496                               ED_image_undo_restore, ED_image_undo_free, NULL);
1497
1498         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1499
1500         ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
1501
1502         DAG_id_tag_update(&ima->id, 0);
1503 }
1504
1505
1506 static int texture_paint_poll(bContext *C)
1507 {
1508         if (texture_paint_toggle_poll(C))
1509                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1510                         return 1;
1511         
1512         return 0;
1513 }
1514
1515 int image_texture_paint_poll(bContext *C)
1516 {
1517         return (texture_paint_poll(C) || image_paint_poll(C));
1518 }
1519
1520 int facemask_paint_poll(bContext *C)
1521 {
1522         return BKE_paint_select_face_test(CTX_data_active_object(C));
1523 }
1524
1525 int vert_paint_poll(bContext *C)
1526 {
1527         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1528 }
1529
1530 int mask_paint_poll(bContext *C)
1531 {
1532         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1533 }
1534