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