Tool System: per space/mode tool support
[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
43 #include "BLT_translation.h"
44
45 #include "IMB_imbuf.h"
46 #include "IMB_imbuf_types.h"
47
48 #include "DNA_brush_types.h"
49 #include "DNA_node_types.h"
50 #include "DNA_object_types.h"
51
52 #include "BKE_colorband.h"
53 #include "BKE_context.h"
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_brush.h"
56 #include "BKE_main.h"
57 #include "BKE_material.h"
58 #include "BKE_node.h"
59 #include "BKE_paint.h"
60 #include "BKE_undo_system.h"
61
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 #include "WM_message.h"
77
78 #include "RNA_access.h"
79 #include "RNA_define.h"
80
81 #include "GPU_draw.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 /* this is a static resource for non-globality,
91  * Maybe it should be exposed as part of the
92  * paint operation, but for now just give a public interface */
93 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
94
95 ImagePaintPartialRedraw *get_imapaintpartial(void)
96 {
97         return &imapaintpartial;
98 }
99
100 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
101 {
102         imapaintpartial = *ippr;
103 }
104
105 /* Imagepaint Partial Redraw & Dirty Region */
106
107 void ED_imapaint_clear_partial_redraw(void)
108 {
109         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
110 }
111
112 void imapaint_region_tiles(ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th)
113 {
114         int srcx = 0, srcy = 0;
115
116         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
117
118         *tw = ((x + w - 1) >> IMAPAINT_TILE_BITS);
119         *th = ((y + h - 1) >> IMAPAINT_TILE_BITS);
120         *tx = (x >> IMAPAINT_TILE_BITS);
121         *ty = (y >> IMAPAINT_TILE_BITS);
122 }
123
124 void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h, bool find_old)
125 {
126         ImBuf *tmpibuf = NULL;
127         int tilex, tiley, tilew, tileh, tx, ty;
128         int srcx = 0, srcy = 0;
129
130         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
131
132         if (w == 0 || h == 0)
133                 return;
134
135         if (!imapaintpartial.enabled) {
136                 imapaintpartial.x1 = x;
137                 imapaintpartial.y1 = y;
138                 imapaintpartial.x2 = x + w;
139                 imapaintpartial.y2 = y + h;
140                 imapaintpartial.enabled = 1;
141         }
142         else {
143                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
144                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
145                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
146                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
147         }
148
149         imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
150
151         ListBase *undo_tiles = ED_image_undo_get_tiles();
152
153         for (ty = tiley; ty <= tileh; ty++)
154                 for (tx = tilex; tx <= tilew; tx++)
155                         image_undo_push_tile(undo_tiles, ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
156
157         ibuf->userflags |= IB_BITMAPDIRTY;
158
159         if (tmpibuf)
160                 IMB_freeImBuf(tmpibuf);
161 }
162
163 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
164 {
165         if (imapaintpartial.x1 != imapaintpartial.x2 &&
166             imapaintpartial.y1 != imapaintpartial.y2)
167         {
168                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
169                                                           imapaintpartial.x2, imapaintpartial.y2);
170         }
171         
172         if (ibuf->mipmap[0])
173                 ibuf->userflags |= IB_MIPMAP_INVALID;
174
175         /* todo: should set_tpage create ->rect? */
176         if (texpaint || (sima && sima->lock)) {
177                 int w = imapaintpartial.x2 - imapaintpartial.x1;
178                 int h = imapaintpartial.y2 - imapaintpartial.y1;
179                 if (w && h) {
180                         /* Testing with partial update in uv editor too */
181                         GPU_paint_update_image(image, (sima ? &sima->iuser : NULL), imapaintpartial.x1, imapaintpartial.y1, w, h);
182                 }
183         }
184 }
185
186 /* paint blur kernels. Projective painting enforces use of a 2x2 kernel due to lagging */
187 BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
188 {
189         int i, j;
190         BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
191         float radius;
192         int side;
193         eBlurKernelType type = br->blur_mode;
194
195         if (proj) {
196                 radius = 0.5f;
197                 
198                 side = kernel->side = 2;
199                 kernel->side_squared = kernel->side * kernel->side;
200                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
201                 kernel->pixel_len = radius;
202         }
203         else {
204                 if (br->blur_kernel_radius <= 0)
205                         br->blur_kernel_radius = 1;
206                 
207                 radius = br->blur_kernel_radius;
208                                         
209                 side = kernel->side = radius * 2 + 1;
210                 kernel->side_squared = kernel->side * kernel->side;
211                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
212                 kernel->pixel_len = br->blur_kernel_radius;
213         }
214         
215         switch (type) {
216                 case KERNEL_BOX:
217                         for (i = 0; i < kernel->side_squared; i++)
218                                 kernel->wdata[i] = 1.0;
219                         break;
220
221                 case KERNEL_GAUSSIAN:
222                 {
223                         /* at 3.0 standard deviations distance, kernel is about zero */                 
224                         float standard_dev = radius / 3.0f; 
225                         
226                         /* make the necessary adjustment to the value for use in the normal distribution formula */
227                         standard_dev = -standard_dev * standard_dev * 2;
228
229                         for (i = 0; i < side; i++) {
230                                 for (j = 0; j < side; j++) {
231                                         float idist = radius - i;
232                                         float jdist = radius - j;
233                                         float value = exp((idist * idist + jdist * jdist) / standard_dev);
234                                         
235                                         kernel->wdata[i + j * side] = value;
236                                 }
237                         }
238
239                         break;
240                 }
241
242                 default:
243                         printf("unidentified kernel type, aborting\n");
244                         MEM_freeN(kernel->wdata);
245                         MEM_freeN(kernel);
246                         return NULL;
247         }
248
249         return kernel;
250 }
251
252 void paint_delete_blur_kernel(BlurKernel *kernel)
253 {
254         if (kernel->wdata)
255                 MEM_freeN(kernel->wdata);
256 }
257
258 /************************ image paint poll ************************/
259
260 static Brush *image_paint_brush(bContext *C)
261 {
262         Scene *scene = CTX_data_scene(C);
263         ToolSettings *settings = scene->toolsettings;
264
265         return BKE_paint_brush(&settings->imapaint.paint);
266 }
267
268 static int image_paint_poll_ex(bContext *C, bool check_tool)
269 {
270         Object *obact;
271
272         if (!image_paint_brush(C))
273                 return 0;
274
275         obact = CTX_data_active_object(C);
276         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
277                 if (!check_tool || WM_toolsystem_active_tool_is_brush(C)) {
278                         return 1;
279                 }
280         }
281         else {
282                 SpaceImage *sima = CTX_wm_space_image(C);
283
284                 if (sima) {
285                         ARegion *ar = CTX_wm_region(C);
286
287                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
288                                 return 1;
289                         }
290                 }
291         }
292
293         return 0;
294 }
295
296 static int image_paint_poll(bContext *C)
297 {
298         return image_paint_poll_ex(C, true);
299 }
300
301 static int image_paint_poll_ignore_tool(bContext *C)
302 {
303         return image_paint_poll_ex(C, false);
304 }
305
306 static int image_paint_2d_clone_poll(bContext *C)
307 {
308         Brush *brush = image_paint_brush(C);
309
310         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
311                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
312                         if (brush->clone.image)
313                                 return 1;
314         
315         return 0;
316 }
317
318 /************************ paint operator ************************/
319 typedef enum eTexPaintMode {
320         PAINT_MODE_2D,
321         PAINT_MODE_3D_PROJECT
322 } eTexPaintMode;
323
324 typedef struct PaintOperation {
325         eTexPaintMode mode;
326
327         void *custom_paint;
328
329         float prevmouse[2];
330         float startmouse[2];
331         double starttime;
332
333         void *cursor;
334         ViewContext vc;
335 } PaintOperation;
336
337 bool paint_use_opacity_masking(Brush *brush)
338 {
339         return (brush->flag & BRUSH_AIRBRUSH) ||
340                (brush->flag & BRUSH_DRAG_DOT) ||
341                (brush->flag & BRUSH_ANCHORED) ||
342                (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
343                (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
344                (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
345                (brush->flag & BRUSH_USE_GRADIENT) ||
346                (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
347                     false : true;
348 }
349
350 void paint_brush_color_get(
351         struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
352         float pressure, float color[3], struct ColorManagedDisplay *display)
353 {
354         if (invert)
355                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
356         else {
357                 if (br->flag & BRUSH_USE_GRADIENT) {
358                         float color_gr[4];
359                         switch (br->gradient_stroke_mode) {
360                                 case BRUSH_GRADIENT_PRESSURE:
361                                         BKE_colorband_evaluate(br->gradient, pressure, color_gr);
362                                         break;
363                                 case BRUSH_GRADIENT_SPACING_REPEAT:
364                                 {
365                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
366                                         BKE_colorband_evaluate(br->gradient, coord, color_gr);
367                                         break;
368                                 }
369                                 case BRUSH_GRADIENT_SPACING_CLAMP:
370                                 {
371                                         BKE_colorband_evaluate(br->gradient, distance / br->gradient_spacing, color_gr);
372                                         break;
373                                 }
374                         }
375                         copy_v3_v3(color, color_gr);
376                 }
377                 else
378                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
379         }
380         if (color_correction)
381                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
382 }
383
384 void paint_brush_init_tex(Brush *brush)
385 {
386         /* init mtex nodes */
387         if (brush) {
388                 MTex *mtex = &brush->mtex;
389                 if (mtex->tex && mtex->tex->nodetree)
390                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
391                 mtex = &brush->mask_mtex;
392                 if (mtex->tex && mtex->tex->nodetree)
393                         ntreeTexBeginExecTree(mtex->tex->nodetree);
394         }
395 }
396
397 void paint_brush_exit_tex(Brush *brush)
398 {
399         if (brush) {
400                 MTex *mtex = &brush->mtex;
401                 if (mtex->tex && mtex->tex->nodetree)
402                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
403                 mtex = &brush->mask_mtex;
404                 if (mtex->tex && mtex->tex->nodetree)
405                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
406         }
407 }
408
409 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
410 {
411         PaintOperation *pop = (PaintOperation *)customdata;
412
413         if (pop) {
414                 glEnable(GL_LINE_SMOOTH);
415                 glEnable(GL_BLEND);
416
417                 Gwn_VertFormat *format = immVertexFormat();
418                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
419
420                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
421
422                 glLineWidth(4.0);
423                 immUniformColor4ub(0, 0, 0, 255);
424
425                 immBegin(GWN_PRIM_LINES, 2);
426                 immVertex2i(pos, x, y);
427                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
428                 immEnd();
429
430                 glLineWidth(2.0);
431                 immUniformColor4ub(255, 255, 255, 255);
432
433                 immBegin(GWN_PRIM_LINES, 2);
434                 immVertex2i(pos, x, y);
435                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
436                 immEnd();
437
438                 immUnbindProgram();
439
440                 glDisable(GL_BLEND);
441                 glDisable(GL_LINE_SMOOTH);
442         }
443 }
444
445
446 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
447 {
448         Scene *scene = CTX_data_scene(C);
449         ToolSettings *settings = scene->toolsettings;
450         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
451         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
452         int mode = RNA_enum_get(op->ptr, "mode");
453         ED_view3d_viewcontext_init(C, &pop->vc);
454
455         copy_v2_v2(pop->prevmouse, mouse);
456         copy_v2_v2(pop->startmouse, mouse);
457
458         /* initialize from context */
459         if (CTX_wm_region_view3d(C)) {
460                 ViewLayer *view_layer = CTX_data_view_layer(C);
461                 Object *ob = OBACT(view_layer);
462                 bool uvs, mat, tex, stencil;
463                 if (!BKE_paint_proj_mesh_data_check(scene, ob, &uvs, &mat, &tex, &stencil)) {
464                         BKE_paint_data_warning(op->reports, uvs, mat, tex, stencil);
465                         MEM_freeN(pop);
466                         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
467                         return NULL;                    
468                 }
469                 pop->mode = PAINT_MODE_3D_PROJECT;
470                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
471         }
472         else {
473                 pop->mode = PAINT_MODE_2D;
474                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
475         }
476
477         if (!pop->custom_paint) {
478                 MEM_freeN(pop);
479                 return NULL;
480         }
481
482         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
483                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
484         }
485         
486         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
487         ED_image_undo_push_begin(op->type->name);
488
489         return pop;
490 }
491
492 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
493 {
494         PaintOperation *pop = paint_stroke_mode_data(stroke);
495         Scene *scene = CTX_data_scene(C);
496         ToolSettings *toolsettings = CTX_data_tool_settings(C);
497         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
498         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
499
500         float alphafac = (brush->flag & BRUSH_ACCUMULATE) ? ups->overlap_factor : 1.0f;
501
502         /* initial brush values. Maybe it should be considered moving these to stroke system */
503         float startalpha = BKE_brush_alpha_get(scene, brush);
504
505         float mouse[2];
506         float pressure;
507         float size;
508         float distance = paint_stroke_distance_get(stroke);
509         int eraser;
510
511         RNA_float_get_array(itemptr, "mouse", mouse);
512         pressure = RNA_float_get(itemptr, "pressure");
513         eraser = RNA_boolean_get(itemptr, "pen_flip");
514         size = max_ff(1.0f, RNA_float_get(itemptr, "size"));
515
516         /* stroking with fill tool only acts on stroke end */
517         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
518                 copy_v2_v2(pop->prevmouse, mouse);
519                 return;
520         }
521
522         if (BKE_brush_use_alpha_pressure(scene, brush))
523                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure * alphafac));
524         else
525                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
526
527         if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
528                 UndoStack *ustack = CTX_wm_manager(C)->undo_stack;
529                 ED_image_undo_restore(ustack->step_init);
530         }
531
532         if (pop->mode == PAINT_MODE_3D_PROJECT) {
533                 paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
534         }
535         else {
536                 paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
537         }
538
539         copy_v2_v2(pop->prevmouse, mouse);
540
541         /* restore brush values */
542         BKE_brush_alpha_set(scene, brush, startalpha);
543 }
544
545 static void paint_stroke_redraw(const bContext *C, struct PaintStroke *stroke, bool final)
546 {
547         PaintOperation *pop = paint_stroke_mode_data(stroke);
548
549         if (pop->mode == PAINT_MODE_3D_PROJECT) {
550                 paint_proj_redraw(C, pop->custom_paint, final);
551         }
552         else {
553                 paint_2d_redraw(C, pop->custom_paint, final);
554         }
555 }
556
557 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
558 {
559         Scene *scene = CTX_data_scene(C);
560         ToolSettings *toolsettings = scene->toolsettings;
561         PaintOperation *pop = paint_stroke_mode_data(stroke);
562         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
563
564         toolsettings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
565
566         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
567                 if (brush->flag & BRUSH_USE_GRADIENT) {
568                         if (pop->mode == PAINT_MODE_2D) {
569                                 paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint);
570                         }
571                         else {
572                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
573                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
574                                 /* two redraws, one for GPU update, one for notification */
575                                 paint_proj_redraw(C, pop->custom_paint, false);
576                                 paint_proj_redraw(C, pop->custom_paint, true);
577                         }
578                 }
579                 else {
580                         if (pop->mode == PAINT_MODE_2D) {
581                                 float color[3];
582
583                                 srgb_to_linearrgb_v3_v3(color, BKE_brush_color_get(scene, brush));
584                                 paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint);
585                         }
586                         else {
587                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
588                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
589                                 /* two redraws, one for GPU update, one for notification */
590                                 paint_proj_redraw(C, pop->custom_paint, false);
591                                 paint_proj_redraw(C, pop->custom_paint, true);
592                         }
593                 }
594         }
595         if (pop->mode == PAINT_MODE_3D_PROJECT) {
596                 paint_proj_stroke_done(pop->custom_paint);
597         }
598         else {
599                 paint_2d_stroke_done(pop->custom_paint);
600         }
601
602         if (pop->cursor) {
603                 WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
604         }
605
606         ED_image_undo_push_end();
607
608         /* duplicate warning, see texpaint_init */
609 #if 0
610         if (pop->s.warnmultifile)
611                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
612         if (pop->s.warnpackedfile)
613                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
614 #endif
615         MEM_freeN(pop);
616 }
617
618 static bool paint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
619 {
620         PaintOperation *pop;
621
622         /* TODO Should avoid putting this here. Instead, last position should be requested
623          * from stroke system. */
624
625         if (!(pop = texture_paint_init(C, op, mouse))) {
626                 return false;
627         }
628
629         paint_stroke_set_mode_data(op->customdata, pop);
630
631         return true;
632 }
633
634
635 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
636 {
637         int retval;
638
639         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
640                                           paint_stroke_update_step,
641                                           paint_stroke_redraw,
642                                           paint_stroke_done, event->type);
643
644         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
645                 paint_stroke_data_free(op);
646                 return OPERATOR_FINISHED;
647         }
648         /* add modal handler */
649         WM_event_add_modal_handler(C, op);
650
651         OPERATOR_RETVAL_CHECK(retval);
652         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
653
654         return OPERATOR_RUNNING_MODAL;
655 }
656
657 static int paint_exec(bContext *C, wmOperator *op)
658 {
659         PropertyRNA *strokeprop;
660         PointerRNA firstpoint;
661         float mouse[2];
662
663         strokeprop = RNA_struct_find_property(op->ptr, "stroke");
664
665         if (!RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint))
666                 return OPERATOR_CANCELLED;
667
668         RNA_float_get_array(&firstpoint, "mouse", mouse);
669
670         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
671                                           paint_stroke_update_step,
672                                           paint_stroke_redraw,
673                                           paint_stroke_done, 0);
674         /* frees op->customdata */
675         return paint_stroke_exec(C, op);
676 }
677
678 void PAINT_OT_image_paint(wmOperatorType *ot)
679 {
680         /* identifiers */
681         ot->name = "Image Paint";
682         ot->idname = "PAINT_OT_image_paint";
683         ot->description = "Paint a stroke into the image";
684
685         /* api callbacks */
686         ot->invoke = paint_invoke;
687         ot->modal = paint_stroke_modal;
688         ot->exec = paint_exec;
689         ot->poll = image_paint_poll;
690         ot->cancel = paint_stroke_cancel;
691
692         /* flags */
693         ot->flag = OPTYPE_BLOCKING;
694
695         paint_stroke_operator_properties(ot);
696 }
697
698
699 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
700 {
701         RegionView3D *rv3d = CTX_wm_region_view3d(C);
702
703         if (!rv3d) {
704                 SpaceImage *sima = CTX_wm_space_image(C);
705
706                 if (sima->mode == SI_MODE_PAINT) {
707                         ARegion *ar = CTX_wm_region(C);
708                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
709
710                         return 1;
711                 }
712         }
713
714         *zoomx = *zoomy = 1;
715
716         return 0;
717 }
718
719 /************************ cursor drawing *******************************/
720
721 static void toggle_paint_cursor(bContext *C, int enable)
722 {
723         wmWindowManager *wm = CTX_wm_manager(C);
724         Scene *scene = CTX_data_scene(C);
725         ToolSettings *settings = scene->toolsettings;
726
727         if (settings->imapaint.paintcursor && !enable) {
728                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
729                 settings->imapaint.paintcursor = NULL;
730                 paint_cursor_delete_textures();
731         }
732         else if (enable)
733                 paint_cursor_start(C, image_paint_poll);
734 }
735
736 /* enable the paint cursor if it isn't already.
737  *
738  * purpose is to make sure the paint cursor is shown if paint
739  * mode is enabled in the image editor. the paint poll will
740  * ensure that the cursor is hidden when not in paint mode */
741 void ED_space_image_paint_update(wmWindowManager *wm, Scene *scene)
742 {
743         ToolSettings *settings = scene->toolsettings;
744         ImagePaintSettings *imapaint = &settings->imapaint;
745         bool enabled = false;
746
747         for (wmWindow *win = wm->windows.first; win; win = win->next) {
748                 bScreen *screen = WM_window_get_active_screen(win);
749
750                 for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
751                         if (sa->spacetype == SPACE_IMAGE) {
752                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT) {
753                                         enabled = true;
754                                 }
755                         }
756                 }
757         }
758
759         if (enabled) {
760                 BKE_paint_init(scene, ePaintTexture2D, PAINT_CURSOR_TEXTURE_PAINT);
761
762                 paint_cursor_start_explicit(&imapaint->paint, wm, image_paint_poll);
763         }
764         else {
765                 paint_cursor_delete_textures();
766         }
767 }
768
769 /************************ grab clone operator ************************/
770
771 typedef struct GrabClone {
772         float startoffset[2];
773         int startx, starty;
774 } GrabClone;
775
776 static void grab_clone_apply(bContext *C, wmOperator *op)
777 {
778         Brush *brush = image_paint_brush(C);
779         float delta[2];
780
781         RNA_float_get_array(op->ptr, "delta", delta);
782         add_v2_v2(brush->clone.offset, delta);
783         ED_region_tag_redraw(CTX_wm_region(C));
784 }
785
786 static int grab_clone_exec(bContext *C, wmOperator *op)
787 {
788         grab_clone_apply(C, op);
789
790         return OPERATOR_FINISHED;
791 }
792
793 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
794 {
795         Brush *brush = image_paint_brush(C);
796         GrabClone *cmv;
797
798         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
799         copy_v2_v2(cmv->startoffset, brush->clone.offset);
800         cmv->startx = event->x;
801         cmv->starty = event->y;
802         op->customdata = cmv;
803
804         WM_event_add_modal_handler(C, op);
805
806         return OPERATOR_RUNNING_MODAL;
807 }
808
809 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
810 {
811         Brush *brush = image_paint_brush(C);
812         ARegion *ar = CTX_wm_region(C);
813         GrabClone *cmv = op->customdata;
814         float startfx, startfy, fx, fy, delta[2];
815         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
816
817         switch (event->type) {
818                 case LEFTMOUSE:
819                 case MIDDLEMOUSE:
820                 case RIGHTMOUSE: // XXX hardcoded
821                         MEM_freeN(op->customdata);
822                         return OPERATOR_FINISHED;
823                 case MOUSEMOVE:
824                         /* mouse moved, so move the clone image */
825                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
826                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
827
828                         delta[0] = fx - startfx;
829                         delta[1] = fy - startfy;
830                         RNA_float_set_array(op->ptr, "delta", delta);
831
832                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
833
834                         grab_clone_apply(C, op);
835                         break;
836         }
837
838         return OPERATOR_RUNNING_MODAL;
839 }
840
841 static void grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
842 {
843         MEM_freeN(op->customdata);
844 }
845
846 void PAINT_OT_grab_clone(wmOperatorType *ot)
847 {
848         /* identifiers */
849         ot->name = "Grab Clone";
850         ot->idname = "PAINT_OT_grab_clone";
851         ot->description = "Move the clone source image";
852         
853         /* api callbacks */
854         ot->exec = grab_clone_exec;
855         ot->invoke = grab_clone_invoke;
856         ot->modal = grab_clone_modal;
857         ot->cancel = grab_clone_cancel;
858         ot->poll = image_paint_2d_clone_poll;
859
860         /* flags */
861         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
862
863         /* properties */
864         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);
865 }
866
867 /******************** sample color operator ********************/
868 typedef struct {
869         bool show_cursor;
870         short event_type;
871         float initcolor[3];
872         bool sample_palette;
873 }       SampleColorData;
874
875
876 static void sample_color_update_header(SampleColorData *data, bContext *C)
877 {
878         char msg[UI_MAX_DRAW_STR];
879         ScrArea *sa = CTX_wm_area(C);
880
881         if (sa) {
882                 BLI_snprintf(msg, sizeof(msg),
883                              IFACE_("Sample color for %s"),
884                              !data->sample_palette ?
885                              IFACE_("Brush. Use Left Click to sample for palette instead") :
886                              IFACE_("Palette. Use Left Click to sample more colors"));
887                 ED_area_headerprint(sa, msg);
888         }
889 }
890
891 static int sample_color_exec(bContext *C, wmOperator *op)
892 {
893         Paint *paint = BKE_paint_get_active_from_context(C);
894         Brush *brush = BKE_paint_brush(paint);
895         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
896         ARegion *ar = CTX_wm_region(C);
897         wmWindow *win = CTX_wm_window(C);
898         const bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
899         int location[2];
900         paint->flags &= ~PAINT_SHOW_BRUSH;
901
902         /* force redraw without cursor */
903         WM_paint_cursor_tag_redraw(win, ar);
904         WM_redraw_windows(C);
905
906         RNA_int_get_array(op->ptr, "location", location);
907         const bool use_palette = RNA_boolean_get(op->ptr, "palette");
908         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
909
910         paint_sample_color(C, ar, location[0], location[1], use_sample_texture, use_palette);
911
912         if (show_cursor) {
913                 paint->flags |= PAINT_SHOW_BRUSH;
914         }
915
916         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
917         
918         return OPERATOR_FINISHED;
919 }
920
921 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
922 {
923         Scene *scene = CTX_data_scene(C);
924         Paint *paint = BKE_paint_get_active_from_context(C);
925         Brush *brush = BKE_paint_brush(paint);
926         SampleColorData *data = MEM_mallocN(sizeof(SampleColorData), "sample color custom data");
927         ARegion *ar = CTX_wm_region(C);
928         wmWindow *win = CTX_wm_window(C);
929
930         data->event_type = event->type;
931         data->show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
932         copy_v3_v3(data->initcolor, BKE_brush_color_get(scene, brush));
933         data->sample_palette = false;
934         op->customdata = data;
935         paint->flags &= ~PAINT_SHOW_BRUSH;
936
937         sample_color_update_header(data, C);
938
939         WM_event_add_modal_handler(C, op);
940
941         /* force redraw without cursor */
942         WM_paint_cursor_tag_redraw(win, ar);
943         WM_redraw_windows(C);
944
945         RNA_int_set_array(op->ptr, "location", event->mval);
946
947         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
948         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
949
950         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
951         WM_cursor_modal_set(win, BC_EYEDROPPER_CURSOR);
952
953         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
954
955         return OPERATOR_RUNNING_MODAL;
956 }
957
958 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
959 {
960         Scene *scene = CTX_data_scene(C);
961         SampleColorData *data = op->customdata;
962         Paint *paint = BKE_paint_get_active_from_context(C);
963         Brush *brush = BKE_paint_brush(paint);
964
965         if ((event->type == data->event_type) && (event->val == KM_RELEASE)) {
966                 ScrArea *sa = CTX_wm_area(C);
967
968                 if (data->show_cursor) {
969                         paint->flags |= PAINT_SHOW_BRUSH;
970                 }
971
972                 if (data->sample_palette) {
973                         BKE_brush_color_set(scene, brush, data->initcolor);
974                         RNA_boolean_set(op->ptr, "palette", true);
975                 }
976                 WM_cursor_modal_restore(CTX_wm_window(C));
977                 MEM_freeN(data);
978                 ED_area_headerprint(sa, NULL);
979
980                 return OPERATOR_FINISHED;
981         }
982
983         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
984         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
985
986         switch (event->type) {
987                 case MOUSEMOVE:
988                 {
989                         ARegion *ar = CTX_wm_region(C);
990                         RNA_int_set_array(op->ptr, "location", event->mval);
991                         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
992                         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
993                         break;
994                 }
995
996                 case LEFTMOUSE:
997                         if (event->val == KM_PRESS) {
998                                 ARegion *ar = CTX_wm_region(C);
999                                 RNA_int_set_array(op->ptr, "location", event->mval);
1000                                 paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, true);
1001                                 if (!data->sample_palette) {
1002                                         data->sample_palette = true;
1003                                         sample_color_update_header(data, C);
1004                                 }
1005                                 WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1006                         }
1007                         break;
1008         }
1009
1010         return OPERATOR_RUNNING_MODAL;
1011 }
1012
1013 static int sample_color_poll(bContext *C)
1014 {
1015         return (image_paint_poll_ignore_tool(C) || image_paint_poll_ignore_tool(C));
1016 }
1017
1018 void PAINT_OT_sample_color(wmOperatorType *ot)
1019 {
1020         /* identifiers */
1021         ot->name = "Sample Color";
1022         ot->idname = "PAINT_OT_sample_color";
1023         ot->description = "Use the mouse to sample a color in the image";
1024         
1025         /* api callbacks */
1026         ot->exec = sample_color_exec;
1027         ot->invoke = sample_color_invoke;
1028         ot->modal = sample_color_modal;
1029         ot->poll = sample_color_poll;
1030
1031         /* flags */
1032         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1033
1034         /* properties */
1035         PropertyRNA *prop;
1036
1037         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1038         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1039
1040         RNA_def_boolean(ot->srna, "merged", 0, "Sample Merged", "Sample the output display color");
1041         RNA_def_boolean(ot->srna, "palette", 0, "Add to Palette", "");
1042 }
1043
1044 /******************** texture paint toggle operator ********************/
1045
1046 static int texture_paint_toggle_poll(bContext *C)
1047 {
1048         Object *ob = CTX_data_active_object(C);
1049         if (ob == NULL || ob->type != OB_MESH)
1050                 return 0;
1051         if (!ob->data || ID_IS_LINKED(ob->data))
1052                 return 0;
1053         if (CTX_data_edit_object(C))
1054                 return 0;
1055
1056         return 1;
1057 }
1058
1059 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1060 {
1061         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
1062         Scene *scene = CTX_data_scene(C);
1063         Object *ob = CTX_data_active_object(C);
1064         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1065         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1066
1067         if (!is_mode_set) {
1068                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1069                         return OPERATOR_CANCELLED;
1070                 }
1071         }
1072
1073         if (ob->mode & mode_flag) {
1074                 ob->mode &= ~mode_flag;
1075
1076                 if (U.glreslimit != 0)
1077                         GPU_free_images();
1078                 GPU_paint_set_mipmap(1);
1079
1080                 toggle_paint_cursor(C, 0);
1081         }
1082         else {
1083                 bScreen *sc;
1084                 Main *bmain = CTX_data_main(C);
1085                 Image *ima = NULL;
1086                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1087
1088                 /* This has to stay here to regenerate the texture paint
1089                  * cache in case we are loading a file */
1090                 BKE_texpaint_slots_refresh_object(scene, ob);
1091
1092                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
1093                 
1094                 /* entering paint mode also sets image to editors */
1095                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1096                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1097
1098                         if (ma && ma->texpaintslot)
1099                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1100                 }
1101                 else if (imapaint->mode == IMAGEPAINT_MODE_IMAGE) {
1102                         ima = imapaint->canvas;
1103                 }       
1104                 
1105                 if (ima) {
1106                         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1107                                 ScrArea *sa;
1108                                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1109                                         SpaceLink *sl;
1110                                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
1111                                                 if (sl->spacetype == SPACE_IMAGE) {
1112                                                         SpaceImage *sima = (SpaceImage *)sl;
1113                                                         
1114                                                         if (!sima->pin) {
1115                                                                 Object *obedit = CTX_data_edit_object(C);
1116                                                                 ED_space_image_set(sima, scene, obedit, ima);
1117                                                         }
1118                                                 }
1119                                         }
1120                                 }
1121                         }
1122                 }
1123                 
1124                 ob->mode |= mode_flag;
1125
1126                 BKE_paint_init(scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT);
1127
1128                 if (U.glreslimit != 0)
1129                         GPU_free_images();
1130                 GPU_paint_set_mipmap(0);
1131
1132                 toggle_paint_cursor(C, 1);
1133         }
1134
1135         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1136
1137         WM_msg_publish_rna_prop(mbus, &ob->id, ob, Object, mode);
1138
1139         WM_toolsystem_update_from_context_view3d(C);
1140
1141         return OPERATOR_FINISHED;
1142 }
1143
1144 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1145 {
1146         /* identifiers */
1147         ot->name = "Texture Paint Toggle";
1148         ot->idname = "PAINT_OT_texture_paint_toggle";
1149         ot->description = "Toggle texture paint mode in 3D view";
1150         
1151         /* api callbacks */
1152         ot->exec = texture_paint_toggle_exec;
1153         ot->poll = texture_paint_toggle_poll;
1154
1155         /* flags */
1156         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1157 }
1158
1159
1160 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1161 {
1162         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1163
1164         Object *ob = CTX_data_active_object(C);
1165         Brush *br;
1166         if (!(ob && (ob->mode & OB_MODE_VERTEX_PAINT))) {
1167                 br = image_paint_brush(C);
1168         }
1169         else {
1170                 /* At the moment, wpaint does not support the color flipper. 
1171                  * So for now we're only handling vpaint */
1172                 ToolSettings *ts = CTX_data_tool_settings(C);
1173                 VPaint *vp = ts->vpaint;
1174                 br = BKE_paint_brush(&vp->paint);
1175         }
1176
1177         if (ups->flag & UNIFIED_PAINT_COLOR) {
1178                 swap_v3_v3(ups->rgb, ups->secondary_rgb);
1179         }
1180         else if (br) {
1181                 swap_v3_v3(br->rgb, br->secondary_rgb);
1182         }
1183         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, br);
1184
1185         return OPERATOR_FINISHED;
1186 }
1187
1188 static int brush_colors_flip_poll(bContext *C)
1189 {
1190         if (image_paint_poll(C)) {
1191                 Brush *br = image_paint_brush(C);
1192                 if (br->imagepaint_tool == PAINT_TOOL_DRAW)
1193                         return 1;
1194         }
1195         else {
1196                 Object *ob = CTX_data_active_object(C);
1197                 if (ob && (ob->mode & OB_MODE_VERTEX_PAINT)) {
1198                         return 1;
1199                 }
1200         }
1201         return 0;
1202 }
1203
1204 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1205 {
1206         /* identifiers */
1207         ot->name = "Brush Colors Flip";
1208         ot->idname = "PAINT_OT_brush_colors_flip";
1209         ot->description = "Toggle foreground and background brush colors";
1210
1211         /* api callbacks */
1212         ot->exec = brush_colors_flip_exec;
1213         ot->poll = brush_colors_flip_poll;
1214
1215         /* flags */
1216         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1217 }
1218
1219
1220 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1221 {
1222         wmWindowManager *wm = CTX_wm_manager(C);
1223         SpaceImage *sima = CTX_wm_space_image(C);
1224         Image *ima = sima->image;
1225
1226         BKE_undosys_step_push_init_with_type(wm->undo_stack, C, op->type->name, BKE_UNDOSYS_TYPE_IMAGE);
1227
1228         ED_image_undo_push_begin(op->type->name);
1229
1230         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1231
1232         BKE_undosys_step_push(wm->undo_stack, C, op->type->name);
1233
1234         DEG_id_tag_update(&ima->id, 0);
1235 }
1236
1237
1238 static int texture_paint_poll(bContext *C)
1239 {
1240         if (texture_paint_toggle_poll(C))
1241                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1242                         return 1;
1243         
1244         return 0;
1245 }
1246
1247 int image_texture_paint_poll(bContext *C)
1248 {
1249         return (texture_paint_poll(C) || image_paint_poll(C));
1250 }
1251
1252 int facemask_paint_poll(bContext *C)
1253 {
1254         return BKE_paint_select_face_test(CTX_data_active_object(C));
1255 }
1256
1257 int vert_paint_poll(bContext *C)
1258 {
1259         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1260 }
1261
1262 int mask_paint_poll(bContext *C)
1263 {
1264         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1265 }
1266