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