WM: space, region type filtering for paint cursor
[blender.git] / source / blender / editors / sculpt_paint / paint_cursor.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  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2009 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * Contributor(s): Jason Wilkins, Tom Musgrove.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_cursor.c
28  *  \ingroup edsculpt
29  */
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_math.h"
34 #include "BLI_rect.h"
35 #include "BLI_task.h"
36 #include "BLI_utildefines.h"
37
38 #include "DNA_brush_types.h"
39 #include "DNA_customdata_types.h"
40 #include "DNA_color_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_space_types.h"
45 #include "DNA_userdef_types.h"
46 #include "DNA_view3d_types.h"
47
48 #include "BKE_brush.h"
49 #include "BKE_context.h"
50 #include "BKE_curve.h"
51 #include "BKE_image.h"
52 #include "BKE_node.h"
53 #include "BKE_paint.h"
54 #include "BKE_colortools.h"
55
56 #include "WM_api.h"
57
58 #include "IMB_imbuf_types.h"
59
60 #include "ED_view3d.h"
61
62 #include "GPU_draw.h"
63 #include "GPU_immediate.h"
64 #include "GPU_immediate_util.h"
65 #include "GPU_matrix.h"
66 #include "GPU_state.h"
67
68 #include "UI_resources.h"
69
70 #include "paint_intern.h"
71 /* still needed for sculpt_stroke_get_location, should be
72  * removed eventually (TODO) */
73 #include "sculpt_intern.h"
74
75 /* TODOs:
76  *
77  * Some of the cursor drawing code is doing non-draw stuff
78  * (e.g. updating the brush rake angle). This should be cleaned up
79  * still.
80  *
81  * There is also some ugliness with sculpt-specific code.
82  */
83
84 typedef struct TexSnapshot {
85         GLuint overlay_texture;
86         int winx;
87         int winy;
88         int old_size;
89         float old_zoom;
90         bool old_col;
91 } TexSnapshot;
92
93 typedef struct CursorSnapshot {
94         GLuint overlay_texture;
95         int size;
96         int zoom;
97 } CursorSnapshot;
98
99 static TexSnapshot primary_snap = {0};
100 static TexSnapshot secondary_snap  = {0};
101 static CursorSnapshot cursor_snap  = {0};
102
103 /* delete overlay cursor textures to preserve memory and invalidate all overlay flags */
104 void paint_cursor_delete_textures(void)
105 {
106         if (primary_snap.overlay_texture)
107                 glDeleteTextures(1, &primary_snap.overlay_texture);
108         if (secondary_snap.overlay_texture)
109                 glDeleteTextures(1, &secondary_snap.overlay_texture);
110         if (cursor_snap.overlay_texture)
111                 glDeleteTextures(1, &cursor_snap.overlay_texture);
112
113         memset(&primary_snap, 0, sizeof(TexSnapshot));
114         memset(&secondary_snap, 0, sizeof(TexSnapshot));
115         memset(&cursor_snap, 0, sizeof(CursorSnapshot));
116
117         BKE_paint_invalidate_overlay_all();
118 }
119
120 static int same_tex_snap(TexSnapshot *snap, MTex *mtex, ViewContext *vc, bool col, float zoom)
121 {
122         return (/* make brush smaller shouldn't cause a resample */
123                 //(mtex->brush_map_mode != MTEX_MAP_MODE_VIEW ||
124                 //(BKE_brush_size_get(vc->scene, brush) <= snap->BKE_brush_size_get)) &&
125
126                 (mtex->brush_map_mode != MTEX_MAP_MODE_TILED ||
127                  (vc->ar->winx == snap->winx &&
128                   vc->ar->winy == snap->winy)) &&
129                 (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL ||
130                 snap->old_zoom == zoom) &&
131                 snap->old_col == col
132                 );
133 }
134
135 static void make_tex_snap(TexSnapshot *snap, ViewContext *vc, float zoom)
136 {
137         snap->old_zoom = zoom;
138         snap->winx = vc->ar->winx;
139         snap->winy = vc->ar->winy;
140 }
141
142 typedef struct LoadTexData {
143         Brush *br;
144         ViewContext *vc;
145
146         MTex *mtex;
147         GLubyte *buffer;
148         bool col;
149
150         struct ImagePool *pool;
151         int size;
152         float rotation;
153         float radius;
154 } LoadTexData;
155
156 static void load_tex_task_cb_ex(
157         void *__restrict userdata,
158         const int j,
159         const ParallelRangeTLS *__restrict tls)
160 {
161         LoadTexData *data = userdata;
162         Brush *br = data->br;
163         ViewContext *vc = data->vc;
164
165         MTex *mtex = data->mtex;
166         GLubyte *buffer = data->buffer;
167         const bool col = data->col;
168
169         struct ImagePool *pool = data->pool;
170         const int size = data->size;
171         const float rotation = data->rotation;
172         const float radius = data->radius;
173
174         bool convert_to_linear = false;
175         struct ColorSpace *colorspace = NULL;
176
177         if (mtex->tex && mtex->tex->type == TEX_IMAGE && mtex->tex->ima) {
178                 ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(mtex->tex->ima, &mtex->tex->iuser, pool);
179                 /* For consistency, sampling always returns color in linear space */
180                 if (tex_ibuf && tex_ibuf->rect_float == NULL) {
181                         convert_to_linear = true;
182                         colorspace = tex_ibuf->rect_colorspace;
183                 }
184                 BKE_image_pool_release_ibuf(mtex->tex->ima, tex_ibuf, pool);
185         }
186
187         for (int i = 0; i < size; i++) {
188                 // largely duplicated from tex_strength
189
190                 int index = j * size + i;
191
192                 float x = (float)i / size;
193                 float y = (float)j / size;
194                 float len;
195
196                 if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
197                         x *= vc->ar->winx / radius;
198                         y *= vc->ar->winy / radius;
199                 }
200                 else {
201                         x = (x - 0.5f) * 2.0f;
202                         y = (y - 0.5f) * 2.0f;
203                 }
204
205                 len = sqrtf(x * x + y * y);
206
207                 if (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL) || len <= 1.0f) {
208                         /* it is probably worth optimizing for those cases where the texture is not rotated by skipping the calls to
209                          * atan2, sqrtf, sin, and cos. */
210                         if (mtex->tex && (rotation > 0.001f || rotation < -0.001f)) {
211                                 const float angle = atan2f(y, x) + rotation;
212
213                                 x = len * cosf(angle);
214                                 y = len * sinf(angle);
215                         }
216
217                         if (col) {
218                                 float rgba[4];
219
220                                 paint_get_tex_pixel_col(mtex, x, y, rgba, pool, tls->thread_id, convert_to_linear, colorspace);
221
222                                 buffer[index * 4]     = rgba[0] * 255;
223                                 buffer[index * 4 + 1] = rgba[1] * 255;
224                                 buffer[index * 4 + 2] = rgba[2] * 255;
225                                 buffer[index * 4 + 3] = rgba[3] * 255;
226                         }
227                         else {
228                                 float avg = paint_get_tex_pixel(mtex, x, y, pool, tls->thread_id);
229
230                                 avg += br->texture_sample_bias;
231
232                                 /* clamp to avoid precision overflow */
233                                 CLAMP(avg, 0.0f, 1.0f);
234                                 buffer[index] = 255 - (GLubyte)(255 * avg);
235                         }
236                 }
237                 else {
238                         if (col) {
239                                 buffer[index * 4]     = 0;
240                                 buffer[index * 4 + 1] = 0;
241                                 buffer[index * 4 + 2] = 0;
242                                 buffer[index * 4 + 3] = 0;
243                         }
244                         else {
245                                 buffer[index] = 0;
246                         }
247                 }
248         }
249 }
250
251 static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool primary)
252 {
253         bool init;
254         TexSnapshot *target;
255
256         MTex *mtex = (primary) ? &br->mtex : &br->mask_mtex;
257         eOverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
258         GLubyte *buffer = NULL;
259
260         int size;
261         bool refresh;
262         eOverlayControlFlags invalid = (
263                 (primary) ?
264                 (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
265                 (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY));
266         target = (primary) ? &primary_snap : &secondary_snap;
267
268         refresh =
269             !target->overlay_texture ||
270             (invalid != 0) ||
271             !same_tex_snap(target, mtex, vc, col, zoom);
272
273         init = (target->overlay_texture != 0);
274
275         if (refresh) {
276                 struct ImagePool *pool = NULL;
277                 /* stencil is rotated later */
278                 const float rotation = (mtex->brush_map_mode != MTEX_MAP_MODE_STENCIL) ? -mtex->rot : 0.0f;
279                 const float radius = BKE_brush_size_get(vc->scene, br) * zoom;
280
281                 make_tex_snap(target, vc, zoom);
282
283                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
284                         int s = BKE_brush_size_get(vc->scene, br);
285                         int r = 1;
286
287                         for (s >>= 1; s > 0; s >>= 1)
288                                 r++;
289
290                         size = (1 << r);
291
292                         if (size < 256)
293                                 size = 256;
294
295                         if (size < target->old_size)
296                                 size = target->old_size;
297                 }
298                 else {
299                         size = 512;
300                 }
301
302                 if (target->old_size != size) {
303                         if (target->overlay_texture) {
304                                 glDeleteTextures(1, &target->overlay_texture);
305                                 target->overlay_texture = 0;
306                         }
307
308                         init = false;
309
310                         target->old_size = size;
311                 }
312                 if (col)
313                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size * 4, "load_tex");
314                 else
315                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
316
317                 pool = BKE_image_pool_new();
318
319                 if (mtex->tex && mtex->tex->nodetree)
320                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
321
322                 LoadTexData data = {
323                     .br = br, .vc = vc, .mtex = mtex, .buffer = buffer, .col = col,
324                     .pool = pool, .size = size, .rotation = rotation, .radius = radius,
325                 };
326
327                 ParallelRangeSettings settings;
328                 BLI_parallel_range_settings_defaults(&settings);
329                 BLI_task_parallel_range(0, size, &data, load_tex_task_cb_ex, &settings);
330
331                 if (mtex->tex && mtex->tex->nodetree)
332                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
333
334                 if (pool)
335                         BKE_image_pool_free(pool);
336
337                 if (!target->overlay_texture)
338                         glGenTextures(1, &target->overlay_texture);
339         }
340         else {
341                 size = target->old_size;
342         }
343
344         glActiveTexture(GL_TEXTURE0);
345         glBindTexture(GL_TEXTURE_2D, target->overlay_texture);
346
347         if (refresh) {
348                 GLenum format = col ? GL_RGBA : GL_RED;
349                 GLenum internalformat = col ? GL_RGBA8 : GL_R8;
350
351                 if (!init || (target->old_col != col)) {
352                         glTexImage2D(GL_TEXTURE_2D, 0, internalformat, size, size, 0, format, GL_UNSIGNED_BYTE, buffer);
353                 }
354                 else {
355                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, format, GL_UNSIGNED_BYTE, buffer);
356                 }
357
358                 if (buffer)
359                         MEM_freeN(buffer);
360
361                 target->old_col = col;
362         }
363
364         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
365         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
366
367         if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
368                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
369                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
370         }
371
372         BKE_paint_reset_overlay_invalid(invalid);
373
374         return 1;
375 }
376
377 static void load_tex_cursor_task_cb(
378         void *__restrict userdata,
379         const int j,
380         const ParallelRangeTLS *__restrict UNUSED(tls))
381 {
382         LoadTexData *data = userdata;
383         Brush *br = data->br;
384
385         GLubyte *buffer = data->buffer;
386
387         const int size = data->size;
388
389         for (int i = 0; i < size; i++) {
390                 // largely duplicated from tex_strength
391
392                 const int index = j * size + i;
393                 const float x = (((float)i / size) - 0.5f) * 2.0f;
394                 const float y = (((float)j / size) - 0.5f) * 2.0f;
395                 const float len = sqrtf(x * x + y * y);
396
397                 if (len <= 1.0f) {
398                         float avg = BKE_brush_curve_strength_clamped(br, len, 1.0f);  /* Falloff curve */
399
400                         buffer[index] = 255 - (GLubyte)(255 * avg);
401                 }
402                 else {
403                         buffer[index] = 0;
404                 }
405         }
406 }
407
408 static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
409 {
410         bool init;
411
412         eOverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
413         GLubyte *buffer = NULL;
414
415         int size;
416         const bool refresh =
417             !cursor_snap.overlay_texture ||
418             (overlay_flags & PAINT_INVALID_OVERLAY_CURVE) ||
419             cursor_snap.zoom != zoom;
420
421         init = (cursor_snap.overlay_texture != 0);
422
423         if (refresh) {
424                 int s, r;
425
426                 cursor_snap.zoom = zoom;
427
428                 s = BKE_brush_size_get(vc->scene, br);
429                 r = 1;
430
431                 for (s >>= 1; s > 0; s >>= 1)
432                         r++;
433
434                 size = (1 << r);
435
436                 if (size < 256)
437                         size = 256;
438
439                 if (size < cursor_snap.size)
440                         size = cursor_snap.size;
441
442                 if (cursor_snap.size != size) {
443                         if (cursor_snap.overlay_texture) {
444                                 glDeleteTextures(1, &cursor_snap.overlay_texture);
445                                 cursor_snap.overlay_texture = 0;
446                         }
447
448                         init = false;
449
450                         cursor_snap.size = size;
451                 }
452                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
453
454                 curvemapping_initialize(br->curve);
455
456                 LoadTexData data = {
457                     .br = br, .buffer = buffer, .size = size,
458                 };
459
460                 ParallelRangeSettings settings;
461                 BLI_parallel_range_settings_defaults(&settings);
462                 BLI_task_parallel_range(0, size, &data, load_tex_cursor_task_cb, &settings);
463
464                 if (!cursor_snap.overlay_texture)
465                         glGenTextures(1, &cursor_snap.overlay_texture);
466         }
467         else {
468                 size = cursor_snap.size;
469         }
470
471         glActiveTexture(GL_TEXTURE0);
472         glBindTexture(GL_TEXTURE_2D, cursor_snap.overlay_texture);
473
474         if (refresh) {
475                 if (!init) {
476                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, size, size, 0, GL_RED, GL_UNSIGNED_BYTE, buffer);
477                 }
478                 else {
479                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_RED, GL_UNSIGNED_BYTE, buffer);
480                 }
481
482                 if (buffer)
483                         MEM_freeN(buffer);
484         }
485
486         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
487         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
488
489         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
490         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
491
492         BKE_paint_reset_overlay_invalid(PAINT_INVALID_OVERLAY_CURVE);
493
494         return 1;
495 }
496
497
498
499 static int project_brush_radius(
500         ViewContext *vc,
501         float radius,
502         const float location[3])
503 {
504         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
505
506         ED_view3d_global_to_vector(vc->rv3d, location, view);
507
508         /* create a vector that is not orthogonal to view */
509
510         if (fabsf(view[0]) < 0.1f) {
511                 nonortho[0] = view[0] + 1.0f;
512                 nonortho[1] = view[1];
513                 nonortho[2] = view[2];
514         }
515         else if (fabsf(view[1]) < 0.1f) {
516                 nonortho[0] = view[0];
517                 nonortho[1] = view[1] + 1.0f;
518                 nonortho[2] = view[2];
519         }
520         else {
521                 nonortho[0] = view[0];
522                 nonortho[1] = view[1];
523                 nonortho[2] = view[2] + 1.0f;
524         }
525
526         /* get a vector in the plane of the view */
527         cross_v3_v3v3(ortho, nonortho, view);
528         normalize_v3(ortho);
529
530         /* make a point on the surface of the brush tagent to the view */
531         mul_v3_fl(ortho, radius);
532         add_v3_v3v3(offset, location, ortho);
533
534         /* project the center of the brush, and the tangent point to the view onto the screen */
535         if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
536             (ED_view3d_project_float_global(vc->ar, offset,   p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
537         {
538                 /* the distance between these points is the size of the projected brush in pixels */
539                 return len_v2v2(p1, p2);
540         }
541         else {
542                 BLI_assert(0);  /* assert because the code that sets up the vectors should disallow this */
543                 return 0;
544         }
545 }
546
547 static bool sculpt_get_brush_geometry(
548         bContext *C, ViewContext *vc,
549         int x, int y, int *pixel_radius,
550         float location[3], UnifiedPaintSettings *ups)
551 {
552         Scene *scene = CTX_data_scene(C);
553         Paint *paint = BKE_paint_get_active_from_context(C);
554         float mouse[2];
555         bool hit = false;
556
557         mouse[0] = x;
558         mouse[1] = y;
559
560         if (vc->obact->sculpt && vc->obact->sculpt->pbvh) {
561                 if (!ups->stroke_active) {
562                         hit = sculpt_stroke_get_location(C, location, mouse);
563                 }
564                 else {
565                         hit = ups->last_hit;
566                         copy_v3_v3(location, ups->last_location);
567                 }
568         }
569
570         if (hit) {
571                 Brush *brush = BKE_paint_brush(paint);
572
573                 *pixel_radius = project_brush_radius(
574                         vc, BKE_brush_unprojected_radius_get(scene, brush), location);
575
576                 if (*pixel_radius == 0)
577                         *pixel_radius = BKE_brush_size_get(scene, brush);
578
579                 mul_m4_v3(vc->obact->obmat, location);
580         }
581         else {
582                 Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;
583                 Brush *brush = BKE_paint_brush(&sd->paint);
584
585                 *pixel_radius = BKE_brush_size_get(scene, brush);
586         }
587
588         return hit;
589 }
590
591 /* Draw an overlay that shows what effect the brush's texture will
592  * have on brush strength */
593 static void paint_draw_tex_overlay(
594         UnifiedPaintSettings *ups, Brush *brush,
595         ViewContext *vc, int x, int y, float zoom, bool col, bool primary)
596 {
597         rctf quad;
598         /* check for overlay mode */
599
600         MTex *mtex = (primary) ? &brush->mtex : &brush->mask_mtex;
601         bool valid = (
602                 (primary) ?
603                 (brush->overlay_flags & BRUSH_OVERLAY_PRIMARY) != 0 :
604                 (brush->overlay_flags & BRUSH_OVERLAY_SECONDARY) != 0);
605         int overlay_alpha = (primary) ? brush->texture_overlay_alpha : brush->mask_overlay_alpha;
606
607         if (!(mtex->tex) || !((mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) ||
608             (valid &&
609             ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_TILED))))
610         {
611                 return;
612         }
613
614         if (load_tex(brush, vc, zoom, col, primary)) {
615                 GPU_blend(true);
616
617                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
618                 glDepthMask(GL_FALSE);
619                 glDepthFunc(GL_ALWAYS);
620
621                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
622                         GPU_matrix_push();
623
624                         /* brush rotation */
625                         GPU_matrix_translate_2f(x, y);
626                         GPU_matrix_rotate_2d(-RAD2DEGF(primary ? ups->brush_rotation : ups->brush_rotation_sec));
627                         GPU_matrix_translate_2f(-x, -y);
628
629                         /* scale based on tablet pressure */
630                         if (primary && ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
631                                 const float scale = ups->size_pressure_value;
632                                 GPU_matrix_translate_2f(x, y);
633                                 GPU_matrix_scale_2f(scale, scale);
634                                 GPU_matrix_translate_2f(-x, -y);
635                         }
636
637                         if (ups->draw_anchored) {
638                                 quad.xmin = ups->anchored_initial_mouse[0] - ups->anchored_size;
639                                 quad.ymin = ups->anchored_initial_mouse[1] - ups->anchored_size;
640                                 quad.xmax = ups->anchored_initial_mouse[0] + ups->anchored_size;
641                                 quad.ymax = ups->anchored_initial_mouse[1] + ups->anchored_size;
642                         }
643                         else {
644                                 const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
645                                 quad.xmin = x - radius;
646                                 quad.ymin = y - radius;
647                                 quad.xmax = x + radius;
648                                 quad.ymax = y + radius;
649                         }
650                 }
651                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
652                         quad.xmin = 0;
653                         quad.ymin = 0;
654                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
655                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
656                 }
657                 /* Stencil code goes here */
658                 else {
659                         if (primary) {
660                                 quad.xmin = -brush->stencil_dimension[0];
661                                 quad.ymin = -brush->stencil_dimension[1];
662                                 quad.xmax = brush->stencil_dimension[0];
663                                 quad.ymax = brush->stencil_dimension[1];
664                         }
665                         else {
666                                 quad.xmin = -brush->mask_stencil_dimension[0];
667                                 quad.ymin = -brush->mask_stencil_dimension[1];
668                                 quad.xmax = brush->mask_stencil_dimension[0];
669                                 quad.ymax = brush->mask_stencil_dimension[1];
670                         }
671                         GPU_matrix_push();
672                         if (primary)
673                                 GPU_matrix_translate_2fv(brush->stencil_pos);
674                         else
675                                 GPU_matrix_translate_2fv(brush->mask_stencil_pos);
676                         GPU_matrix_rotate_2d(RAD2DEGF(mtex->rot));
677                 }
678
679                 /* set quad color. Colored overlay does not get blending */
680                 GPUVertFormat *format = immVertexFormat();
681                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
682                 uint texCoord = GPU_vertformat_attr_add(format, "texCoord", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
683
684                 if (col) {
685                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_COLOR);
686                         immUniformColor4f(1.0f, 1.0f, 1.0f, overlay_alpha * 0.01f);
687                 }
688                 else {
689                         GPU_blend_set_func(GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
690                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_ALPHA_COLOR);
691                         immUniformColor3fvAlpha(U.sculpt_paint_overlay_col, overlay_alpha * 0.01f);
692                 }
693
694                 /* draw textured quad */
695                 immUniform1i("image", GL_TEXTURE0);
696
697                 immBegin(GPU_PRIM_TRI_FAN, 4);
698                 immAttr2f(texCoord, 0.0f, 0.0f);
699                 immVertex2f(pos, quad.xmin, quad.ymin);
700                 immAttr2f(texCoord, 1.0f, 0.0f);
701                 immVertex2f(pos, quad.xmax, quad.ymin);
702                 immAttr2f(texCoord, 1.0f, 1.0f);
703                 immVertex2f(pos, quad.xmax, quad.ymax);
704                 immAttr2f(texCoord, 0.0f, 1.0f);
705                 immVertex2f(pos, quad.xmin, quad.ymax);
706                 immEnd();
707
708                 immUnbindProgram();
709                 GPU_blend_set_func(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA);
710
711                 if (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_VIEW)) {
712                         GPU_matrix_pop();
713                 }
714         }
715 }
716
717 /* Draw an overlay that shows what effect the brush's texture will
718  * have on brush strength */
719 static void paint_draw_cursor_overlay(
720         UnifiedPaintSettings *ups, Brush *brush,
721         ViewContext *vc, int x, int y, float zoom)
722 {
723         rctf quad;
724         /* check for overlay mode */
725
726         if (!(brush->overlay_flags & BRUSH_OVERLAY_CURSOR)) {
727                 return;
728         }
729
730         if (load_tex_cursor(brush, vc, zoom)) {
731                 bool do_pop = false;
732                 float center[2];
733                 GPU_blend(true);
734
735                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
736                 glDepthMask(GL_FALSE);
737                 glDepthFunc(GL_ALWAYS);
738
739                 if (ups->draw_anchored) {
740                         copy_v2_v2(center, ups->anchored_initial_mouse);
741                         quad.xmin = ups->anchored_initial_mouse[0] - ups->anchored_size;
742                         quad.ymin = ups->anchored_initial_mouse[1] - ups->anchored_size;
743                         quad.xmax = ups->anchored_initial_mouse[0] + ups->anchored_size;
744                         quad.ymax = ups->anchored_initial_mouse[1] + ups->anchored_size;
745                 }
746                 else {
747                         const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
748                         center[0] = x;
749                         center[1] = y;
750
751                         quad.xmin = x - radius;
752                         quad.ymin = y - radius;
753                         quad.xmax = x + radius;
754                         quad.ymax = y + radius;
755                 }
756
757                 /* scale based on tablet pressure */
758                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
759                         do_pop = true;
760                         GPU_matrix_push();
761                         GPU_matrix_translate_2fv(center);
762                         GPU_matrix_scale_1f(ups->size_pressure_value);
763                         GPU_matrix_translate_2f(-center[0], -center[1]);
764                 }
765
766                 GPUVertFormat *format = immVertexFormat();
767                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
768                 uint texCoord = GPU_vertformat_attr_add(format, "texCoord", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
769
770                 GPU_blend_set_func(GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
771                 immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_ALPHA_COLOR);
772
773                 immUniformColor3fvAlpha(U.sculpt_paint_overlay_col, brush->cursor_overlay_alpha * 0.01f);
774
775                 /* draw textured quad */
776
777                 /* draw textured quad */
778                 immUniform1i("image", 0);
779
780                 immBegin(GPU_PRIM_TRI_FAN, 4);
781                 immAttr2f(texCoord, 0.0f, 0.0f);
782                 immVertex2f(pos, quad.xmin, quad.ymin);
783                 immAttr2f(texCoord, 1.0f, 0.0f);
784                 immVertex2f(pos, quad.xmax, quad.ymin);
785                 immAttr2f(texCoord, 1.0f, 1.0f);
786                 immVertex2f(pos, quad.xmax, quad.ymax);
787                 immAttr2f(texCoord, 0.0f, 1.0f);
788                 immVertex2f(pos, quad.xmin, quad.ymax);
789                 immEnd();
790
791                 immUnbindProgram();
792
793                 GPU_blend_set_func(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA);
794
795                 if (do_pop)
796                         GPU_matrix_pop();
797         }
798 }
799
800 static void paint_draw_alpha_overlay(
801         UnifiedPaintSettings *ups, Brush *brush,
802         ViewContext *vc, int x, int y, float zoom, ePaintMode mode)
803 {
804         /* color means that primary brush texture is colured and secondary is used for alpha/mask control */
805         bool col = ELEM(mode, ePaintTextureProjective, ePaintTexture2D, ePaintVertex) ? true : false;
806         eOverlayControlFlags flags = BKE_paint_get_overlay_flags();
807         gpuPushAttrib(GPU_DEPTH_BUFFER_BIT | GPU_BLEND_BIT);
808
809         /* Translate to region. */
810         GPU_matrix_push();
811         GPU_matrix_translate_2f(vc->ar->winrct.xmin, vc->ar->winrct.ymin);
812         x -= vc->ar->winrct.xmin;
813         y -= vc->ar->winrct.ymin;
814
815         /* coloured overlay should be drawn separately */
816         if (col) {
817                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY))
818                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, true, true);
819                 if (!(flags & PAINT_OVERLAY_OVERRIDE_SECONDARY))
820                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, false);
821                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
822                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
823         }
824         else {
825                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY) && (mode != ePaintWeight))
826                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, true);
827                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
828                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
829         }
830
831         GPU_matrix_pop();
832         gpuPopAttrib();
833 }
834
835
836 BLI_INLINE void draw_tri_point(
837         unsigned int pos, float sel_col[4], float pivot_col[4],
838         float *co, float width, bool selected)
839 {
840         immUniformColor4fv(selected ? sel_col : pivot_col);
841
842         GPU_line_width(3.0f);
843
844         float w = width / 2.0f;
845         float tri[3][2] = {
846                 {co[0], co[1] + w},
847                 {co[0] - w, co[1] - w},
848                 {co[0] + w, co[1] - w},
849         };
850
851         immBegin(GPU_PRIM_LINE_LOOP, 3);
852         immVertex2fv(pos, tri[0]);
853         immVertex2fv(pos, tri[1]);
854         immVertex2fv(pos, tri[2]);
855         immEnd();
856
857         immUniformColor4f(1.0f, 1.0f, 1.0f, 0.5f);
858         GPU_line_width(1.0f);
859
860         immBegin(GPU_PRIM_LINE_LOOP, 3);
861         immVertex2fv(pos, tri[0]);
862         immVertex2fv(pos, tri[1]);
863         immVertex2fv(pos, tri[2]);
864         immEnd();
865 }
866
867 BLI_INLINE void draw_rect_point(
868         unsigned int pos, float sel_col[4], float handle_col[4],
869         float *co, float width, bool selected)
870 {
871         immUniformColor4fv(selected ? sel_col : handle_col);
872
873         GPU_line_width(3.0f);
874
875         float w = width / 2.0f;
876         float minx = co[0] - w;
877         float miny = co[1] - w;
878         float maxx = co[0] + w;
879         float maxy = co[1] + w;
880
881         imm_draw_box_wire_2d(pos, minx, miny, maxx, maxy);
882
883         immUniformColor4f(1.0f, 1.0f, 1.0f, 0.5f);
884         GPU_line_width(1.0f);
885
886         imm_draw_box_wire_2d(pos, minx, miny, maxx, maxy);
887 }
888
889
890 BLI_INLINE void draw_bezier_handle_lines(unsigned int pos, float sel_col[4], BezTriple *bez)
891 {
892         immUniformColor4f(0.0f, 0.0f, 0.0f, 0.5f);
893         GPU_line_width(3.0f);
894
895         immBegin(GPU_PRIM_LINE_STRIP, 3);
896         immVertex2fv(pos, bez->vec[0]);
897         immVertex2fv(pos, bez->vec[1]);
898         immVertex2fv(pos, bez->vec[2]);
899         immEnd();
900
901         GPU_line_width(1.0f);
902
903         if (bez->f1 || bez->f2) {
904                 immUniformColor4fv(sel_col);
905         }
906         else {
907                 immUniformColor4f(1.0f, 1.0f, 1.0f, 0.5f);
908         }
909         immBegin(GPU_PRIM_LINES, 2);
910         immVertex2fv(pos, bez->vec[0]);
911         immVertex2fv(pos, bez->vec[1]);
912         immEnd();
913
914         if (bez->f3 || bez->f2) {
915                 immUniformColor4fv(sel_col);
916         }
917         else {
918                 immUniformColor4f(1.0f, 1.0f, 1.0f, 0.5f);
919         }
920         immBegin(GPU_PRIM_LINES, 2);
921         immVertex2fv(pos, bez->vec[1]);
922         immVertex2fv(pos, bez->vec[2]);
923         immEnd();
924 }
925
926 static void paint_draw_curve_cursor(Brush *brush, ViewContext *vc)
927 {
928         GPU_matrix_push();
929         GPU_matrix_translate_2f(vc->ar->winrct.xmin, vc->ar->winrct.ymin);
930
931         if (brush->paint_curve && brush->paint_curve->points) {
932                 int i;
933                 PaintCurve *pc = brush->paint_curve;
934                 PaintCurvePoint *cp = pc->points;
935
936                 GPU_line_smooth(true);
937                 GPU_blend(true);
938
939                 /* draw the bezier handles and the curve segment between the current and next point */
940                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
941
942                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
943
944                 float selec_col[4], handle_col[4], pivot_col[4];
945                 UI_GetThemeColor4fv(TH_VERTEX_SELECT, selec_col);
946                 UI_GetThemeColor4fv(TH_PAINT_CURVE_HANDLE, handle_col);
947                 UI_GetThemeColor4fv(TH_PAINT_CURVE_PIVOT, pivot_col);
948
949                 for (i = 0; i < pc->tot_points - 1; i++, cp++) {
950                         int j;
951                         PaintCurvePoint *cp_next = cp + 1;
952                         float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
953                         /* use color coding to distinguish handles vs curve segments  */
954                         draw_bezier_handle_lines(pos, selec_col, &cp->bez);
955                         draw_tri_point(pos, selec_col, pivot_col, &cp->bez.vec[1][0], 10.0f, cp->bez.f2);
956                         draw_rect_point(pos, selec_col, handle_col, &cp->bez.vec[0][0], 8.0f, cp->bez.f1 || cp->bez.f2);
957                         draw_rect_point(pos, selec_col, handle_col, &cp->bez.vec[2][0], 8.0f, cp->bez.f3 || cp->bez.f2);
958
959                         for (j = 0; j < 2; j++)
960                                 BKE_curve_forward_diff_bezier(
961                                         cp->bez.vec[1][j],
962                                         cp->bez.vec[2][j],
963                                         cp_next->bez.vec[0][j],
964                                         cp_next->bez.vec[1][j],
965                                         data + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
966
967                         float (*v)[2] = (float(*)[2])data;
968
969                         immUniformColor4f(0.0f, 0.0f, 0.0f, 0.5f);
970                         GPU_line_width(3.0f);
971                         immBegin(GPU_PRIM_LINE_STRIP, PAINT_CURVE_NUM_SEGMENTS + 1);
972                         for (j = 0; j <= PAINT_CURVE_NUM_SEGMENTS; j++) {
973                                 immVertex2fv(pos, v[j]);
974                         }
975                         immEnd();
976
977                         immUniformColor4f(0.9f, 0.9f, 1.0f, 0.5f);
978                         GPU_line_width(1.0f);
979                         immBegin(GPU_PRIM_LINE_STRIP, PAINT_CURVE_NUM_SEGMENTS + 1);
980                         for (j = 0; j <= PAINT_CURVE_NUM_SEGMENTS; j++) {
981                                 immVertex2fv(pos, v[j]);
982                         }
983                         immEnd();
984                 }
985
986                 /* draw last line segment */
987                 draw_bezier_handle_lines(pos, selec_col, &cp->bez);
988                 draw_tri_point(pos, selec_col, pivot_col, &cp->bez.vec[1][0], 10.0f, cp->bez.f2);
989                 draw_rect_point(pos, selec_col, handle_col, &cp->bez.vec[0][0], 8.0f, cp->bez.f1 || cp->bez.f2);
990                 draw_rect_point(pos, selec_col, handle_col, &cp->bez.vec[2][0], 8.0f, cp->bez.f3 || cp->bez.f2);
991
992                 GPU_blend(false);
993                 GPU_line_smooth(false);
994
995                 immUnbindProgram();
996         }
997         GPU_matrix_pop();
998 }
999
1000 /* Special actions taken when paint cursor goes over mesh */
1001 /* TODO: sculpt only for now */
1002 static void paint_cursor_on_hit(
1003         UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
1004         const float location[3])
1005 {
1006         float unprojected_radius, projected_radius;
1007
1008         /* update the brush's cached 3D radius */
1009         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
1010                 /* get 2D brush radius */
1011                 if (ups->draw_anchored)
1012                         projected_radius = ups->anchored_size;
1013                 else {
1014                         if (brush->flag & BRUSH_ANCHORED)
1015                                 projected_radius = 8;
1016                         else
1017                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
1018                 }
1019
1020                 /* convert brush radius from 2D to 3D */
1021                 unprojected_radius = paint_calc_object_space_radius(
1022                         vc, location, projected_radius);
1023
1024                 /* scale 3D brush radius by pressure */
1025                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush))
1026                         unprojected_radius *= ups->size_pressure_value;
1027
1028                 /* set cached value in either Brush or UnifiedPaintSettings */
1029                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
1030         }
1031 }
1032
1033 static bool ommit_cursor_drawing(Paint *paint, ePaintMode mode, Brush *brush)
1034 {
1035         if (paint->flags & PAINT_SHOW_BRUSH) {
1036                 if (ELEM(mode, ePaintTexture2D, ePaintTextureProjective) && brush->imagepaint_tool == PAINT_TOOL_FILL) {
1037                         return true;
1038                 }
1039                 return false;
1040         }
1041         return true;
1042 }
1043
1044 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
1045 {
1046         Scene *scene = CTX_data_scene(C);
1047         ARegion *ar = CTX_wm_region(C);
1048         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1049         Paint *paint = BKE_paint_get_active_from_context(C);
1050         Brush *brush = BKE_paint_brush(paint);
1051         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
1052
1053         /* check that brush drawing is enabled */
1054         if (ommit_cursor_drawing(paint, mode, brush))
1055                 return;
1056
1057         /* can't use stroke vc here because this will be called during
1058          * mouse over too, not just during a stroke */
1059         ViewContext vc;
1060         ED_view3d_viewcontext_init(C, &vc);
1061
1062         if (vc.rv3d && (vc.rv3d->rflag & RV3D_NAVIGATING)) {
1063                 return;
1064         }
1065
1066         /* skip everything and draw brush here */
1067         if (brush->flag & BRUSH_CURVE) {
1068                 paint_draw_curve_cursor(brush, &vc);
1069                 return;
1070         }
1071
1072         float zoomx, zoomy;
1073         get_imapaint_zoom(C, &zoomx, &zoomy);
1074         zoomx = max_ff(zoomx, zoomy);
1075
1076         /* set various defaults */
1077         const float *outline_col = brush->add_col;
1078         const float outline_alpha = 0.5f;
1079         float translation[2] = { x, y };
1080         float final_radius = (BKE_brush_size_get(scene, brush) * zoomx);
1081
1082         /* don't calculate rake angles while a stroke is active because the rake variables are global and
1083          * we may get interference with the stroke itself. For line strokes, such interference is visible */
1084         if (!ups->stroke_active) {
1085                 paint_calculate_rake_rotation(ups, brush, translation);
1086         }
1087
1088         /* draw overlay */
1089         paint_draw_alpha_overlay(ups, brush, &vc, x, y, zoomx, mode);
1090
1091         /* TODO: as sculpt and other paint modes are unified, this
1092          * special mode of drawing will go away */
1093         if ((mode == ePaintSculpt) && vc.obact->sculpt) {
1094                 float location[3];
1095                 int pixel_radius;
1096
1097                 /* test if brush is over the mesh */
1098                 bool hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location, ups);
1099
1100                 if (BKE_brush_use_locked_size(scene, brush))
1101                         BKE_brush_size_set(scene, brush, pixel_radius);
1102
1103                 /* check if brush is subtracting, use different color then */
1104                 /* TODO: no way currently to know state of pen flip or
1105                  * invert key modifier without starting a stroke */
1106                 if (((ups->draw_inverted == 0) ^ ((brush->flag & BRUSH_DIR_IN) == 0)) &&
1107                     BKE_brush_sculpt_has_secondary_color(brush))
1108                 {
1109                         outline_col = brush->sub_col;
1110                 }
1111
1112                 /* only do if brush is over the mesh */
1113                 if (hit)
1114                         paint_cursor_on_hit(ups, brush, &vc, location);
1115         }
1116
1117         if (ups->draw_anchored) {
1118                 final_radius = ups->anchored_size;
1119                 copy_v2_fl2(translation,
1120                             ups->anchored_initial_mouse[0] + ar->winrct.xmin,
1121                             ups->anchored_initial_mouse[1] + ar->winrct.ymin);
1122         }
1123
1124         /* make lines pretty */
1125         GPU_line_width(1.0f);
1126         GPU_blend(true); /* TODO: also set blend mode? */
1127         GPU_line_smooth(true);
1128
1129         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
1130         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1131
1132         /* set brush color */
1133         immUniformColor3fvAlpha(outline_col, outline_alpha);
1134
1135         /* draw brush outline */
1136         if (ups->stroke_active && BKE_brush_use_size_pressure(scene, brush)) {
1137                 /* inner at full alpha */
1138                 imm_draw_circle_wire_2d(pos, translation[0], translation[1], final_radius * ups->size_pressure_value, 40);
1139                 /* outer at half alpha */
1140                 immUniformColor3fvAlpha(outline_col, outline_alpha * 0.5f);
1141         }
1142         imm_draw_circle_wire_2d(pos, translation[0], translation[1], final_radius, 40);
1143
1144         immUnbindProgram();
1145
1146         /* restore GL state */
1147         GPU_blend(false);
1148         GPU_line_smooth(false);
1149 }
1150
1151 /* Public API */
1152
1153 void paint_cursor_start(bContext *C, bool (*poll)(bContext *C))
1154 {
1155         Paint *p = BKE_paint_get_active_from_context(C);
1156
1157         if (p && !p->paint_cursor) {
1158                 p->paint_cursor = WM_paint_cursor_activate(
1159                         CTX_wm_manager(C),
1160                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
1161                         poll,
1162                         paint_draw_cursor,
1163                         NULL);
1164         }
1165
1166         /* invalidate the paint cursors */
1167         BKE_paint_invalidate_overlay_all();
1168 }
1169
1170 void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, bool (*poll)(bContext *C))
1171 {
1172         if (p && !p->paint_cursor) {
1173                 p->paint_cursor = WM_paint_cursor_activate(
1174                         wm,
1175                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
1176                         poll,
1177                         paint_draw_cursor,
1178                         NULL);
1179         }
1180 }