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