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