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