style cleanup
[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 #ifdef WIN32
40 #  include "BLI_winstuff.h"
41 #endif
42
43 #include "BLI_math.h"
44 #include "BLI_blenlib.h"
45 #include "BLI_linklist.h"
46 #include "BLI_memarena.h"
47 #include "BLI_threads.h"
48 #include "BLI_utildefines.h"
49
50 #include "PIL_time.h"
51
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "DNA_brush_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59
60 #include "BKE_camera.h"
61 #include "BKE_context.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_idprop.h"
65 #include "BKE_brush.h"
66 #include "BKE_image.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_mesh.h"
70 #include "BKE_node.h"
71 #include "BKE_object.h"
72 #include "BKE_paint.h"
73 #include "BKE_report.h"
74 #include "BKE_scene.h"
75 #include "BKE_colortools.h"
76
77 #include "BKE_tessmesh.h"
78
79 #include "BIF_gl.h"
80 #include "BIF_glutil.h"
81
82 #include "UI_view2d.h"
83
84 #include "ED_image.h"
85 #include "ED_screen.h"
86 #include "ED_sculpt.h"
87 #include "ED_uvedit.h"
88 #include "ED_view3d.h"
89 #include "ED_mesh.h"
90
91 #include "WM_api.h"
92 #include "WM_types.h"
93
94 #include "RNA_access.h"
95 #include "RNA_define.h"
96 #include "RNA_enum_types.h"
97
98 #include "GPU_draw.h"
99
100 #include "IMB_colormanagement.h"
101
102 #include "paint_intern.h"
103
104 #define IMAPAINT_TILE_BITS          6
105 #define IMAPAINT_TILE_SIZE          (1 << IMAPAINT_TILE_BITS)
106
107 typedef struct UndoImageTile {
108         struct UndoImageTile *next, *prev;
109
110         char idname[MAX_ID_NAME];  /* name instead of pointer*/
111         char ibufname[IB_FILENAME_SIZE];
112
113         union {
114                 float        *fp;
115                 unsigned int *uint;
116                 void         *pt;
117         } rect;
118         int x, y;
119
120         short source, use_float;
121         char gen_type;
122 } UndoImageTile;
123
124 /* this is a static resource for non-globality,
125  * Maybe it should be exposed as part of the
126  * paint operation, but for now just give a public interface */
127 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
128
129 ImagePaintPartialRedraw *get_imapaintpartial(void)
130 {
131         return &imapaintpartial;
132 }
133
134 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
135 {
136         imapaintpartial = *ippr;
137 }
138
139 /* UNDO */
140
141 static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, int restore)
142 {
143         /* copy or swap contents of tile->rect and region in ibuf->rect */
144         IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
145                     tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
146
147         if (ibuf->rect_float) {
148                 SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
149         }
150         else {
151                 SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
152         }
153         
154         if (restore)
155                 IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
156                             tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
157 }
158
159 void *image_undo_push_tile(Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile)
160 {
161         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
162         UndoImageTile *tile;
163         int allocsize;
164         short use_float = ibuf->rect_float ? 1 : 0;
165
166         for (tile = lb->first; tile; tile = tile->next)
167                 if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source)
168                         if (tile->use_float == use_float)
169                                 if (strcmp(tile->idname, ima->id.name) == 0 && strcmp(tile->ibufname, ibuf->name) == 0)
170                                         return tile->rect.pt;
171         
172         if (*tmpibuf == NULL)
173                 *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
174         
175         tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
176         BLI_strncpy(tile->idname, ima->id.name, sizeof(tile->idname));
177         tile->x = x_tile;
178         tile->y = y_tile;
179
180         allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
181         allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
182         tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
183
184         BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
185
186         tile->gen_type = ima->gen_type;
187         tile->source = ima->source;
188         tile->use_float = use_float;
189
190         undo_copy_tile(tile, *tmpibuf, ibuf, 0);
191         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, allocsize);
192
193         BLI_addtail(lb, tile);
194         
195         return tile->rect.pt;
196 }
197
198 void image_undo_restore(bContext *C, ListBase *lb)
199 {
200         Main *bmain = CTX_data_main(C);
201         Image *ima = NULL;
202         ImBuf *ibuf, *tmpibuf;
203         UndoImageTile *tile;
204
205         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
206                                  IB_rectfloat | IB_rect);
207
208         for (tile = lb->first; tile; tile = tile->next) {
209                 short use_float;
210
211                 /* find image based on name, pointer becomes invalid with global undo */
212                 if (ima && strcmp(tile->idname, ima->id.name) == 0) {
213                         /* ima is valid */
214                 }
215                 else {
216                         ima = BLI_findstring(&bmain->image, tile->idname, offsetof(ID, name));
217                 }
218
219                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
220
221                 if (ima && ibuf && strcmp(tile->ibufname, ibuf->name) != 0) {
222                         /* current ImBuf filename was changed, probably current frame
223                          * was changed when paiting on image sequence, rather than storing
224                          * full image user (which isn't so obvious, btw) try to find ImBuf with
225                          * matched file name in list of already loaded images */
226
227                         BKE_image_release_ibuf(ima, ibuf, NULL);
228
229                         ibuf = BLI_findstring(&ima->ibufs, tile->ibufname, offsetof(ImBuf, name));
230                 }
231
232                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
233                         BKE_image_release_ibuf(ima, ibuf, NULL);
234                         continue;
235                 }
236
237                 if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
238                         BKE_image_release_ibuf(ima, ibuf, NULL);
239                         continue;
240                 }
241
242                 use_float = ibuf->rect_float ? 1 : 0;
243
244                 if (use_float != tile->use_float) {
245                         BKE_image_release_ibuf(ima, ibuf, NULL);
246                         continue;
247                 }
248
249                 undo_copy_tile(tile, tmpibuf, ibuf, 1);
250
251                 GPU_free_image(ima); /* force OpenGL reload */
252                 if (ibuf->rect_float)
253                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
254                 if (ibuf->mipmap[0])
255                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
256                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
257
258                 BKE_image_release_ibuf(ima, ibuf, NULL);
259         }
260
261         IMB_freeImBuf(tmpibuf);
262 }
263
264 void image_undo_free(ListBase *lb)
265 {
266         UndoImageTile *tile;
267
268         for (tile = lb->first; tile; tile = tile->next)
269                 MEM_freeN(tile->rect.pt);
270 }
271
272 /* Imagepaint Partial Redraw & Dirty Region */
273
274 void imapaint_clear_partial_redraw(void)
275 {
276         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
277 }
278
279 void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h)
280 {
281         ImBuf *tmpibuf = NULL;
282         int srcx = 0, srcy = 0, origx;
283
284         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
285
286         if (w == 0 || h == 0)
287                 return;
288         
289         if (!imapaintpartial.enabled) {
290                 imapaintpartial.x1 = x;
291                 imapaintpartial.y1 = y;
292                 imapaintpartial.x2 = x + w;
293                 imapaintpartial.y2 = y + h;
294                 imapaintpartial.enabled = 1;
295         }
296         else {
297                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
298                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
299                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
300                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
301         }
302
303         w = ((x + w - 1) >> IMAPAINT_TILE_BITS);
304         h = ((y + h - 1) >> IMAPAINT_TILE_BITS);
305         origx = (x >> IMAPAINT_TILE_BITS);
306         y = (y >> IMAPAINT_TILE_BITS);
307         
308         for (; y <= h; y++)
309                 for (x = origx; x <= w; x++)
310                         image_undo_push_tile(ima, ibuf, &tmpibuf, x, y);
311
312         ibuf->userflags |= IB_BITMAPDIRTY;
313         
314         if (tmpibuf)
315                 IMB_freeImBuf(tmpibuf);
316 }
317
318 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
319 {
320         if (imapaintpartial.x1 != imapaintpartial.x2 &&
321             imapaintpartial.y1 != imapaintpartial.y2)
322         {
323                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
324                                                           imapaintpartial.x2, imapaintpartial.y2);
325         }
326         
327         if (ibuf->mipmap[0])
328                 ibuf->userflags |= IB_MIPMAP_INVALID;
329
330         /* todo: should set_tpage create ->rect? */
331         if (texpaint || (sima && sima->lock)) {
332                 int w = imapaintpartial.x2 - imapaintpartial.x1;
333                 int h = imapaintpartial.y2 - imapaintpartial.y1;
334                 /* Testing with partial update in uv editor too */
335                 GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); //!texpaint);
336         }
337 }
338
339 /************************ image paint poll ************************/
340
341 static Brush *image_paint_brush(bContext *C)
342 {
343         Scene *scene = CTX_data_scene(C);
344         ToolSettings *settings = scene->toolsettings;
345
346         return paint_brush(&settings->imapaint.paint);
347 }
348
349 static int image_paint_poll(bContext *C)
350 {
351         Object *obact = CTX_data_active_object(C);
352
353         if (!image_paint_brush(C))
354                 return 0;
355
356         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
357                 return 1;
358         }
359         else {
360                 SpaceImage *sima = CTX_wm_space_image(C);
361
362                 if (sima) {
363                         ARegion *ar = CTX_wm_region(C);
364
365                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
366                                 return 1;
367                         }
368                 }
369         }
370
371         return 0;
372 }
373
374 static int image_paint_2d_clone_poll(bContext *C)
375 {
376         Brush *brush = image_paint_brush(C);
377
378         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
379                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
380                         if (brush->clone.image)
381                                 return 1;
382         
383         return 0;
384 }
385
386 /************************ paint operator ************************/
387 typedef enum TexPaintMode {
388         PAINT_MODE_2D,
389         PAINT_MODE_3D_PROJECT
390 } TexPaintMode;
391
392 typedef struct PaintOperation {
393         TexPaintMode mode;
394
395         void *custom_paint;
396
397         int prevmouse[2];
398         double starttime;
399
400         ViewContext vc;
401         wmTimer *timer;
402 } PaintOperation;
403
404 void paint_brush_init_tex(Brush *brush)
405 {
406         /* init mtex nodes */
407         if (brush) {
408                 MTex *mtex = &brush->mtex;
409                 if (mtex->tex && mtex->tex->nodetree)
410                         ntreeTexBeginExecTree(mtex->tex->nodetree, 1);  /* has internal flag to detect it only does it once */
411         }
412 }
413
414 void paint_brush_exit_tex(Brush *brush)
415 {
416         if (brush) {
417                 MTex *mtex = &brush->mtex;
418                 if (mtex->tex && mtex->tex->nodetree)
419                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata, 1);
420         }
421 }
422
423
424 static void paint_redraw(const bContext *C, PaintOperation *pop, int final)
425 {
426         if (pop->mode == PAINT_MODE_2D) {
427                 paint_2d_redraw(C, pop->custom_paint, final);
428         }
429         else {
430                 if (final) {
431                         /* compositor listener deals with updating */
432                         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, NULL);
433                 }
434                 else {
435                         ED_region_tag_redraw(CTX_wm_region(C));
436                 }
437         }
438 }
439
440 static PaintOperation * texture_paint_init(bContext *C, wmOperator *op, const wmEvent *event)
441 {
442         Scene *scene = CTX_data_scene(C);
443         ToolSettings *settings = scene->toolsettings;
444         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
445         int mode = RNA_enum_get(op->ptr, "mode");
446         view3d_set_viewcontext(C, &pop->vc);
447
448         /* TODO Should avoid putting this here. Instead, last position should be requested
449          * from stroke system. */
450         pop->prevmouse[0] = event->mval[0];
451         pop->prevmouse[1] = event->mval[1];
452
453
454         /* initialize from context */
455         if (CTX_wm_region_view3d(C)) {
456                 pop->mode = PAINT_MODE_3D_PROJECT;
457                 pop->custom_paint = paint_proj_new_stroke(C, OBACT, pop->prevmouse, mode);
458         }
459         else {
460                 pop->mode = PAINT_MODE_2D;
461                 pop->custom_paint = paint_2d_new_stroke(C, op);
462         }
463
464         if (!pop->custom_paint) {
465                 MEM_freeN(pop);
466                 return NULL;
467         }
468
469         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
470         undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
471                               image_undo_restore, image_undo_free);
472
473         {
474                 UnifiedPaintSettings *ups = &settings->unified_paint_settings;
475                 ups->draw_pressure = true;
476         }
477
478         return pop;
479 }
480
481 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
482 {
483         PaintOperation *pop = paint_stroke_mode_data(stroke);
484         Scene *scene = CTX_data_scene(C);
485         Brush *brush = paint_brush(&scene->toolsettings->imapaint.paint);
486
487         /* initial brush values. Maybe it should be considered moving these to stroke system */
488         float startsize = BKE_brush_size_get(scene, brush);
489         float startalpha = BKE_brush_alpha_get(scene, brush);
490
491         float mousef[2];
492         float pressure;
493         int mouse[2], redraw, eraser;
494
495         RNA_float_get_array(itemptr, "mouse", mousef);
496         mouse[0] = (int)(mousef[0]);
497         mouse[1] = (int)(mousef[1]);
498         pressure = RNA_float_get(itemptr, "pressure");
499         eraser = RNA_boolean_get(itemptr, "pen_flip");
500
501         if (BKE_brush_use_alpha_pressure(scene, brush))
502                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure));
503         if (BKE_brush_use_size_pressure(scene, brush))
504                 BKE_brush_size_set(scene, brush, max_ff(1.0f, startsize * pressure));
505
506         if (pop->mode == PAINT_MODE_3D_PROJECT) {
507                 redraw = paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse);
508         }
509         else {
510                 redraw = paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser);
511         }
512
513         pop->prevmouse[0] = mouse[0];
514         pop->prevmouse[1] = mouse[1];
515
516         /* restore brush values */
517         BKE_brush_alpha_set(scene, brush, startalpha);
518         BKE_brush_size_set(scene, brush, startsize);
519
520
521         if (redraw)
522                 paint_redraw(C, pop, 0);
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 *settings = scene->toolsettings;
530         PaintOperation *pop = paint_stroke_mode_data(stroke);
531
532         paint_redraw(C, pop, 1);
533
534         if (pop->timer)
535                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), pop->timer);
536
537         settings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
538
539         if (pop->mode == PAINT_MODE_3D_PROJECT) {
540                 paint_proj_stroke_done(pop->custom_paint);
541         }
542         else {
543                 paint_2d_stroke_done(pop->custom_paint);
544         }
545
546         undo_paint_push_end(UNDO_PAINT_IMAGE);
547
548         /* duplicate warning, see texpaint_init
549         if (pop->s.warnmultifile)
550                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
551         if (pop->s.warnpackedfile)
552                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
553         */
554         MEM_freeN(pop);
555
556         {
557                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
558                 ups->draw_pressure = false;
559         }
560 }
561
562 static int paint_stroke_test_start(bContext *UNUSED(C), wmOperator *UNUSED(op), const float UNUSED(mouse[2]))
563 {
564         return true;
565 }
566
567
568 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
569 {
570         PaintOperation *pop;
571         struct PaintStroke *stroke;
572         int retval;
573
574         if (!(pop = texture_paint_init(C, op, event))) {
575                 return OPERATOR_CANCELLED;
576         }
577
578         stroke = op->customdata = paint_stroke_new(C, NULL, paint_stroke_test_start,
579                                           paint_stroke_update_step,
580                                           paint_stroke_done, event->type);
581         paint_stroke_set_mode_data(stroke, pop);
582         /* add modal handler */
583         WM_event_add_modal_handler(C, op);
584
585         retval = op->type->modal(C, op, event);
586         OPERATOR_RETVAL_CHECK(retval);
587         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
588
589         return OPERATOR_RUNNING_MODAL;
590 }
591
592
593 void PAINT_OT_image_paint(wmOperatorType *ot)
594 {
595         static EnumPropertyItem stroke_mode_items[] = {
596                 {BRUSH_STROKE_NORMAL, "NORMAL", 0, "Normal", "Apply brush normally"},
597                 {BRUSH_STROKE_INVERT, "INVERT", 0, "Invert", "Invert action of brush for duration of stroke"},
598                 {0}
599         };
600
601         /* identifiers */
602         ot->name = "Image Paint";
603         ot->idname = "PAINT_OT_image_paint";
604         ot->description = "Paint a stroke into the image";
605
606         /* api callbacks */
607         ot->invoke = paint_invoke;
608         ot->modal = paint_stroke_modal;
609         /* ot->exec = paint_exec; <-- needs stroke property */
610         ot->poll = image_paint_poll;
611         ot->cancel = paint_stroke_cancel;
612
613         /* flags */
614         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
615
616         RNA_def_enum(ot->srna, "mode", stroke_mode_items, BRUSH_STROKE_NORMAL,
617                      "Paint Stroke Mode",
618                      "Action taken when a paint stroke is made");
619
620         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
621 }
622
623
624 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
625 {
626         RegionView3D *rv3d = CTX_wm_region_view3d(C);
627
628         if (!rv3d) {
629                 SpaceImage *sima = CTX_wm_space_image(C);
630                 ARegion *ar = CTX_wm_region(C);
631
632                 if (sima->mode == SI_MODE_PAINT) {
633                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
634
635                         return 1;
636                 }
637         }
638
639         *zoomx = *zoomy = 1;
640
641         return 0;
642 }
643
644 /************************ cursor drawing *******************************/
645
646 void brush_drawcursor_texpaint_uvsculpt(bContext *C, int x, int y, void *UNUSED(customdata))
647 {
648 #define PX_SIZE_FADE_MAX 12.0f
649 #define PX_SIZE_FADE_MIN 4.0f
650
651         Scene *scene = CTX_data_scene(C);
652         //Brush *brush = image_paint_brush(C);
653         Paint *paint = paint_get_active_from_context(C);
654         Brush *brush = paint_brush(paint);
655
656         if (paint && brush && paint->flags & PAINT_SHOW_BRUSH) {
657                 float zoomx, zoomy;
658                 const float size = (float)BKE_brush_size_get(scene, brush);
659                 short use_zoom;
660                 float pixel_size;
661                 float alpha = 0.5f;
662
663                 use_zoom = get_imapaint_zoom(C, &zoomx, &zoomy);
664
665                 if (use_zoom) {
666                         pixel_size = size * max_ff(zoomx, zoomy);
667                 }
668                 else {
669                         pixel_size = size;
670                 }
671
672                 /* fade out the brush (cheap trick to work around brush interfering with sampling [#])*/
673                 if (pixel_size < PX_SIZE_FADE_MIN) {
674                         return;
675                 }
676                 else if (pixel_size < PX_SIZE_FADE_MAX) {
677                         alpha *= (pixel_size - PX_SIZE_FADE_MIN) / (PX_SIZE_FADE_MAX - PX_SIZE_FADE_MIN);
678                 }
679
680                 glPushMatrix();
681
682                 glTranslatef((float)x, (float)y, 0.0f);
683
684                 /* No need to scale for uv sculpting, on the contrary it might be useful to keep un-scaled */
685                 if (use_zoom)
686                         glScalef(zoomx, zoomy, 1.0f);
687
688                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], alpha);
689                 glEnable(GL_LINE_SMOOTH);
690                 glEnable(GL_BLEND);
691                 {
692                         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
693                         /* hrmf, duplicate paint_draw_cursor logic here */
694                         if (ups->draw_pressure && BKE_brush_use_size_pressure(scene, brush)) {
695                                 /* inner at full alpha */
696                                 glutil_draw_lined_arc(0, (float)(M_PI * 2.0), size * ups->pressure_value, 40);
697                                 /* outer at half alpha */
698                                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], alpha * 0.5f);
699                         }
700                 }
701                 glutil_draw_lined_arc(0, (float)(M_PI * 2.0), size, 40);
702                 glDisable(GL_BLEND);
703                 glDisable(GL_LINE_SMOOTH);
704
705                 glPopMatrix();
706         }
707 #undef PX_SIZE_FADE_MAX
708 #undef PX_SIZE_FADE_MIN
709 }
710
711 static void toggle_paint_cursor(bContext *C, int enable)
712 {
713         wmWindowManager *wm = CTX_wm_manager(C);
714         Scene *scene = CTX_data_scene(C);
715         ToolSettings *settings = scene->toolsettings;
716
717         if (settings->imapaint.paintcursor && !enable) {
718                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
719                 settings->imapaint.paintcursor = NULL;
720         }
721         else if (enable)
722                 settings->imapaint.paintcursor =
723                         WM_paint_cursor_activate(wm, image_paint_poll, brush_drawcursor_texpaint_uvsculpt, NULL);
724 }
725
726 /* enable the paint cursor if it isn't already.
727  *
728  * purpose is to make sure the paint cursor is shown if paint
729  * mode is enabled in the image editor. the paint poll will
730  * ensure that the cursor is hidden when not in paint mode */
731 void ED_space_image_paint_update(wmWindowManager *wm, ToolSettings *settings)
732 {
733         wmWindow *win;
734         ScrArea *sa;
735         ImagePaintSettings *imapaint = &settings->imapaint;
736         int enabled = FALSE;
737
738         for (win = wm->windows.first; win; win = win->next)
739                 for (sa = win->screen->areabase.first; sa; sa = sa->next)
740                         if (sa->spacetype == SPACE_IMAGE)
741                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
742                                         enabled = TRUE;
743
744         if (enabled) {
745                 BKE_paint_init(&imapaint->paint, PAINT_CURSOR_TEXTURE_PAINT);
746
747                 if (!imapaint->paintcursor) {
748                         imapaint->paintcursor =
749                                 WM_paint_cursor_activate(wm, image_paint_poll,
750                                                          brush_drawcursor_texpaint_uvsculpt, NULL);
751                 }
752         }
753 }
754
755 /************************ grab clone operator ************************/
756
757 typedef struct GrabClone {
758         float startoffset[2];
759         int startx, starty;
760 } GrabClone;
761
762 static void grab_clone_apply(bContext *C, wmOperator *op)
763 {
764         Brush *brush = image_paint_brush(C);
765         float delta[2];
766
767         RNA_float_get_array(op->ptr, "delta", delta);
768         add_v2_v2(brush->clone.offset, delta);
769         ED_region_tag_redraw(CTX_wm_region(C));
770 }
771
772 static int grab_clone_exec(bContext *C, wmOperator *op)
773 {
774         grab_clone_apply(C, op);
775
776         return OPERATOR_FINISHED;
777 }
778
779 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
780 {
781         Brush *brush = image_paint_brush(C);
782         GrabClone *cmv;
783
784         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
785         copy_v2_v2(cmv->startoffset, brush->clone.offset);
786         cmv->startx = event->x;
787         cmv->starty = event->y;
788         op->customdata = cmv;
789
790         WM_event_add_modal_handler(C, op);
791
792         return OPERATOR_RUNNING_MODAL;
793 }
794
795 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
796 {
797         Brush *brush = image_paint_brush(C);
798         ARegion *ar = CTX_wm_region(C);
799         GrabClone *cmv = op->customdata;
800         float startfx, startfy, fx, fy, delta[2];
801         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
802
803         switch (event->type) {
804                 case LEFTMOUSE:
805                 case MIDDLEMOUSE:
806                 case RIGHTMOUSE: // XXX hardcoded
807                         MEM_freeN(op->customdata);
808                         return OPERATOR_FINISHED;
809                 case MOUSEMOVE:
810                         /* mouse moved, so move the clone image */
811                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
812                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
813
814                         delta[0] = fx - startfx;
815                         delta[1] = fy - startfy;
816                         RNA_float_set_array(op->ptr, "delta", delta);
817
818                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
819
820                         grab_clone_apply(C, op);
821                         break;
822         }
823
824         return OPERATOR_RUNNING_MODAL;
825 }
826
827 static int grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
828 {
829         MEM_freeN(op->customdata);
830         return OPERATOR_CANCELLED;
831 }
832
833 void PAINT_OT_grab_clone(wmOperatorType *ot)
834 {
835         /* identifiers */
836         ot->name = "Grab Clone";
837         ot->idname = "PAINT_OT_grab_clone";
838         ot->description = "Move the clone source image";
839         
840         /* api callbacks */
841         ot->exec = grab_clone_exec;
842         ot->invoke = grab_clone_invoke;
843         ot->modal = grab_clone_modal;
844         ot->cancel = grab_clone_cancel;
845         ot->poll = image_paint_2d_clone_poll;
846
847         /* flags */
848         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
849
850         /* properties */
851         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);
852 }
853
854 /******************** sample color operator ********************/
855
856 static int sample_color_exec(bContext *C, wmOperator *op)
857 {
858         Brush *brush = image_paint_brush(C);
859         ARegion *ar = CTX_wm_region(C);
860         int location[2];
861
862         RNA_int_get_array(op->ptr, "location", location);
863         paint_sample_color(C, ar, location[0], location[1]);
864
865         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
866         
867         return OPERATOR_FINISHED;
868 }
869
870 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
871 {
872         RNA_int_set_array(op->ptr, "location", event->mval);
873         sample_color_exec(C, op);
874
875         WM_event_add_modal_handler(C, op);
876
877         return OPERATOR_RUNNING_MODAL;
878 }
879
880 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
881 {
882         switch (event->type) {
883                 case LEFTMOUSE:
884                 case RIGHTMOUSE: // XXX hardcoded
885                         return OPERATOR_FINISHED;
886                 case MOUSEMOVE:
887                         RNA_int_set_array(op->ptr, "location", event->mval);
888                         sample_color_exec(C, op);
889                         break;
890         }
891
892         return OPERATOR_RUNNING_MODAL;
893 }
894
895 /* same as image_paint_poll but fail when face mask mode is enabled */
896 static int image_paint_sample_color_poll(bContext *C)
897 {
898         if (image_paint_poll(C)) {
899                 if (CTX_wm_view3d(C)) {
900                         Object *obact = CTX_data_active_object(C);
901                         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) {
902                                 Mesh *me = BKE_mesh_from_object(obact);
903                                 if (me) {
904                                         return !(me->editflag & ME_EDIT_PAINT_FACE_SEL);
905                                 }
906                         }
907                 }
908
909                 return 1;
910         }
911
912         return 0;
913 }
914
915 void PAINT_OT_sample_color(wmOperatorType *ot)
916 {
917         /* identifiers */
918         ot->name = "Sample Color";
919         ot->idname = "PAINT_OT_sample_color";
920         ot->description = "Use the mouse to sample a color in the image";
921         
922         /* api callbacks */
923         ot->exec = sample_color_exec;
924         ot->invoke = sample_color_invoke;
925         ot->modal = sample_color_modal;
926         ot->poll = image_paint_sample_color_poll;
927
928         /* flags */
929         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
930
931         /* properties */
932         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "Cursor location in region coordinates", 0, 16384);
933 }
934
935 /******************** texture paint toggle operator ********************/
936
937 static int texture_paint_toggle_poll(bContext *C)
938 {
939         if (CTX_data_edit_object(C))
940                 return 0;
941         if (CTX_data_active_object(C) == NULL)
942                 return 0;
943
944         return 1;
945 }
946
947 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
948 {
949         Scene *scene = CTX_data_scene(C);
950         Object *ob = CTX_data_active_object(C);
951         Mesh *me = NULL;
952         
953         if (ob == NULL)
954                 return OPERATOR_CANCELLED;
955         
956         if (BKE_object_obdata_is_libdata(ob)) {
957                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
958                 return OPERATOR_CANCELLED;
959         }
960
961         me = BKE_mesh_from_object(ob);
962
963         if (!(ob->mode & OB_MODE_TEXTURE_PAINT) && !me) {
964                 BKE_report(op->reports, RPT_ERROR, "Can only enter texture paint mode for mesh objects");
965                 return OPERATOR_CANCELLED;
966         }
967
968         if (ob->mode & OB_MODE_TEXTURE_PAINT) {
969                 ob->mode &= ~OB_MODE_TEXTURE_PAINT;
970
971                 if (U.glreslimit != 0)
972                         GPU_free_images();
973                 GPU_paint_set_mipmap(1);
974
975                 toggle_paint_cursor(C, 0);
976         }
977         else {
978                 ob->mode |= OB_MODE_TEXTURE_PAINT;
979
980                 if (me->mtface == NULL)
981                         me->mtface = CustomData_add_layer(&me->fdata, CD_MTFACE, CD_DEFAULT,
982                                                           NULL, me->totface);
983
984                 BKE_paint_init(&scene->toolsettings->imapaint.paint, PAINT_CURSOR_TEXTURE_PAINT);
985
986                 if (U.glreslimit != 0)
987                         GPU_free_images();
988                 GPU_paint_set_mipmap(0);
989
990                 toggle_paint_cursor(C, 1);
991         }
992
993         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
994         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
995
996         return OPERATOR_FINISHED;
997 }
998
999 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1000 {
1001         /* identifiers */
1002         ot->name = "Texture Paint Toggle";
1003         ot->idname = "PAINT_OT_texture_paint_toggle";
1004         ot->description = "Toggle texture paint mode in 3D view";
1005         
1006         /* api callbacks */
1007         ot->exec = texture_paint_toggle_exec;
1008         ot->poll = texture_paint_toggle_poll;
1009
1010         /* flags */
1011         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1012 }
1013
1014 static int texture_paint_poll(bContext *C)
1015 {
1016         if (texture_paint_toggle_poll(C))
1017                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1018                         return 1;
1019         
1020         return 0;
1021 }
1022
1023 int image_texture_paint_poll(bContext *C)
1024 {
1025         return (texture_paint_poll(C) || image_paint_poll(C));
1026 }
1027
1028 int facemask_paint_poll(bContext *C)
1029 {
1030         return paint_facesel_test(CTX_data_active_object(C));
1031 }
1032
1033 int vert_paint_poll(bContext *C)
1034 {
1035         return paint_vertsel_test(CTX_data_active_object(C));
1036 }
1037
1038 int mask_paint_poll(bContext *C)
1039 {
1040         return paint_facesel_test(CTX_data_active_object(C)) || paint_vertsel_test(CTX_data_active_object(C));
1041 }
1042