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