fb938ed60c98fdc57e2eeba8e2adcc27984ac7fc
[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 "BIF_gl.h"
58 #include "BIF_glutil.h"
59
60 #include "IMB_imbuf_types.h"
61
62 #include "ED_view3d.h"
63
64 #include "GPU_basic_shader.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 = (
261                 (primary) ?
262                 (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
263                 (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY));
264         target = (primary) ? &primary_snap : &secondary_snap;
265
266         refresh =
267             !target->overlay_texture ||
268             (invalid != 0) ||
269             !same_tex_snap(target, mtex, vc, col, zoom);
270
271         init = (target->overlay_texture != 0);
272
273         if (refresh) {
274                 struct ImagePool *pool = NULL;
275                 /* stencil is rotated later */
276                 const float rotation = (mtex->brush_map_mode != MTEX_MAP_MODE_STENCIL) ? -mtex->rot : 0.0f;
277                 const float radius = BKE_brush_size_get(vc->scene, br) * zoom;
278
279                 make_tex_snap(target, vc, zoom);
280
281                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
282                         int s = BKE_brush_size_get(vc->scene, br);
283                         int r = 1;
284
285                         for (s >>= 1; s > 0; s >>= 1)
286                                 r++;
287
288                         size = (1 << r);
289
290                         if (size < 256)
291                                 size = 256;
292
293                         if (size < target->old_size)
294                                 size = target->old_size;
295                 }
296                 else {
297                         size = 512;
298                 }
299
300                 if (target->old_size != size) {
301                         if (target->overlay_texture) {
302                                 glDeleteTextures(1, &target->overlay_texture);
303                                 target->overlay_texture = 0;
304                         }
305
306                         init = false;
307
308                         target->old_size = size;
309                 }
310                 if (col)
311                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size * 4, "load_tex");
312                 else
313                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
314
315                 pool = BKE_image_pool_new();
316
317                 if (mtex->tex && mtex->tex->nodetree)
318                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
319
320                 LoadTexData data = {
321                     .br = br, .vc = vc, .mtex = mtex, .buffer = buffer, .col = col,
322                     .pool = pool, .size = size, .rotation = rotation, .radius = radius,
323                 };
324
325                 ParallelRangeSettings settings;
326                 BLI_parallel_range_settings_defaults(&settings);
327                 BLI_task_parallel_range(0, size, &data, load_tex_task_cb_ex, &settings);
328
329                 if (mtex->tex && mtex->tex->nodetree)
330                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
331
332                 if (pool)
333                         BKE_image_pool_free(pool);
334
335                 if (!target->overlay_texture)
336                         glGenTextures(1, &target->overlay_texture);
337         }
338         else {
339                 size = target->old_size;
340         }
341
342         glBindTexture(GL_TEXTURE_2D, target->overlay_texture);
343
344         if (refresh) {
345                 GLenum format = col ? GL_RGBA : GL_ALPHA;
346                 GLenum internalformat = col ? GL_RGBA8 : GL_ALPHA8;
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         GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
362
363         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
364         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
365
366         if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
367                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
368                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
369         }
370
371         BKE_paint_reset_overlay_invalid(invalid);
372
373         return 1;
374 }
375
376 static void load_tex_cursor_task_cb(
377         void *__restrict userdata,
378         const int j,
379         const ParallelRangeTLS *__restrict UNUSED(tls))
380 {
381         LoadTexData *data = userdata;
382         Brush *br = data->br;
383
384         GLubyte *buffer = data->buffer;
385
386         const int size = data->size;
387
388         for (int i = 0; i < size; i++) {
389                 // largely duplicated from tex_strength
390
391                 const int index = j * size + i;
392                 const float x = (((float)i / size) - 0.5f) * 2.0f;
393                 const float y = (((float)j / size) - 0.5f) * 2.0f;
394                 const float len = sqrtf(x * x + y * y);
395
396                 if (len <= 1.0f) {
397                         float avg = BKE_brush_curve_strength_clamped(br, len, 1.0f);  /* Falloff curve */
398
399                         buffer[index] = 255 - (GLubyte)(255 * avg);
400                 }
401                 else {
402                         buffer[index] = 0;
403                 }
404         }
405 }
406
407 static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
408 {
409         bool init;
410
411         eOverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
412         GLubyte *buffer = NULL;
413
414         int size;
415         const bool refresh =
416             !cursor_snap.overlay_texture ||
417             (overlay_flags & PAINT_INVALID_OVERLAY_CURVE) ||
418             cursor_snap.zoom != zoom;
419
420         init = (cursor_snap.overlay_texture != 0);
421
422         if (refresh) {
423                 int s, r;
424
425                 cursor_snap.zoom = zoom;
426
427                 s = BKE_brush_size_get(vc->scene, br);
428                 r = 1;
429
430                 for (s >>= 1; s > 0; s >>= 1)
431                         r++;
432
433                 size = (1 << r);
434
435                 if (size < 256)
436                         size = 256;
437
438                 if (size < cursor_snap.size)
439                         size = cursor_snap.size;
440
441                 if (cursor_snap.size != size) {
442                         if (cursor_snap.overlay_texture) {
443                                 glDeleteTextures(1, &cursor_snap.overlay_texture);
444                                 cursor_snap.overlay_texture = 0;
445                         }
446
447                         init = false;
448
449                         cursor_snap.size = size;
450                 }
451                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
452
453                 curvemapping_initialize(br->curve);
454
455                 LoadTexData data = {
456                     .br = br, .buffer = buffer, .size = size,
457                 };
458
459                 ParallelRangeSettings settings;
460                 BLI_parallel_range_settings_defaults(&settings);
461                 BLI_task_parallel_range(0, size, &data, load_tex_cursor_task_cb, &settings);
462
463                 if (!cursor_snap.overlay_texture)
464                         glGenTextures(1, &cursor_snap.overlay_texture);
465         }
466         else {
467                 size = cursor_snap.size;
468         }
469
470         glBindTexture(GL_TEXTURE_2D, cursor_snap.overlay_texture);
471
472         if (refresh) {
473                 if (!init) {
474                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
475                 }
476                 else {
477                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
478                 }
479
480                 if (buffer)
481                         MEM_freeN(buffer);
482         }
483
484         GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
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                 glEnable(GL_BLEND);
616
617                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
618                 glDepthMask(GL_FALSE);
619                 glDepthFunc(GL_ALWAYS);
620
621                 glMatrixMode(GL_TEXTURE);
622                 glPushMatrix();
623                 glLoadIdentity();
624
625                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
626                         /* brush rotation */
627                         glTranslatef(0.5, 0.5, 0);
628                         glRotatef((double)RAD2DEGF((primary) ? ups->brush_rotation : ups->brush_rotation_sec),
629                                   0.0, 0.0, 1.0);
630                         glTranslatef(-0.5f, -0.5f, 0);
631
632                         /* scale based on tablet pressure */
633                         if (primary && ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
634                                 glTranslatef(0.5f, 0.5f, 0);
635                                 glScalef(1.0f / ups->size_pressure_value, 1.0f / ups->size_pressure_value, 1);
636                                 glTranslatef(-0.5f, -0.5f, 0);
637                         }
638
639                         if (ups->draw_anchored) {
640                                 const float *aim = ups->anchored_initial_mouse;
641                                 quad.xmin = aim[0] - ups->anchored_size;
642                                 quad.ymin = aim[1] - ups->anchored_size;
643                                 quad.xmax = aim[0] + ups->anchored_size;
644                                 quad.ymax = aim[1] + ups->anchored_size;
645                         }
646                         else {
647                                 const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
648                                 quad.xmin = x - radius;
649                                 quad.ymin = y - radius;
650                                 quad.xmax = x + radius;
651                                 quad.ymax = y + radius;
652                         }
653                 }
654                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
655                         quad.xmin = 0;
656                         quad.ymin = 0;
657                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
658                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
659                 }
660                 /* Stencil code goes here */
661                 else {
662                         if (primary) {
663                                 quad.xmin = -brush->stencil_dimension[0];
664                                 quad.ymin = -brush->stencil_dimension[1];
665                                 quad.xmax = brush->stencil_dimension[0];
666                                 quad.ymax = brush->stencil_dimension[1];
667                         }
668                         else {
669                                 quad.xmin = -brush->mask_stencil_dimension[0];
670                                 quad.ymin = -brush->mask_stencil_dimension[1];
671                                 quad.xmax = brush->mask_stencil_dimension[0];
672                                 quad.ymax = brush->mask_stencil_dimension[1];
673                         }
674                         glMatrixMode(GL_MODELVIEW);
675                         glPushMatrix();
676                         if (primary)
677                                 glTranslate2fv(brush->stencil_pos);
678                         else
679                                 glTranslate2fv(brush->mask_stencil_pos);
680                         glRotatef(RAD2DEGF(mtex->rot), 0, 0, 1);
681                         glMatrixMode(GL_TEXTURE);
682                 }
683
684                 /* set quad color. Colored overlay does not get blending */
685                 if (col) {
686                         glColor4f(1.0, 1.0, 1.0, overlay_alpha / 100.0f);
687                 }
688                 else {
689                         glColor4f(UNPACK3(U.sculpt_paint_overlay_col), overlay_alpha / 100.0f);
690                 }
691
692                 /* draw textured quad */
693                 glBegin(GL_QUADS);
694                 glTexCoord2f(0, 0);
695                 glVertex2f(quad.xmin, quad.ymin);
696                 glTexCoord2f(1, 0);
697                 glVertex2f(quad.xmax, quad.ymin);
698                 glTexCoord2f(1, 1);
699                 glVertex2f(quad.xmax, quad.ymax);
700                 glTexCoord2f(0, 1);
701                 glVertex2f(quad.xmin, quad.ymax);
702                 glEnd();
703
704                 glPopMatrix();
705
706                 if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
707                         glMatrixMode(GL_MODELVIEW);
708                         glPopMatrix();
709                 }
710         }
711 }
712
713 /* Draw an overlay that shows what effect the brush's texture will
714  * have on brush strength */
715 static void paint_draw_cursor_overlay(
716         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                         const float *aim = ups->anchored_initial_mouse;
737                         copy_v2_v2(center, aim);
738                         quad.xmin = aim[0] - ups->anchored_size;
739                         quad.ymin = aim[1] - ups->anchored_size;
740                         quad.xmax = aim[0] + ups->anchored_size;
741                         quad.ymax = aim[1] + ups->anchored_size;
742                 }
743                 else {
744                         const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
745                         center[0] = x;
746                         center[1] = y;
747
748                         quad.xmin = x - radius;
749                         quad.ymin = y - radius;
750                         quad.xmax = x + radius;
751                         quad.ymax = y + radius;
752                 }
753
754                 /* scale based on tablet pressure */
755                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
756                         do_pop = true;
757                         glPushMatrix();
758                         glLoadIdentity();
759                         glTranslate2fv(center);
760                         glScalef(ups->size_pressure_value, ups->size_pressure_value, 1);
761                         glTranslatef(-center[0], -center[1], 0);
762                 }
763
764                 glColor4f(U.sculpt_paint_overlay_col[0],
765                         U.sculpt_paint_overlay_col[1],
766                         U.sculpt_paint_overlay_col[2],
767                         brush->cursor_overlay_alpha / 100.0f);
768
769                 /* draw textured quad */
770                 glBegin(GL_QUADS);
771                 glTexCoord2f(0, 0);
772                 glVertex2f(quad.xmin, quad.ymin);
773                 glTexCoord2f(1, 0);
774                 glVertex2f(quad.xmax, quad.ymin);
775                 glTexCoord2f(1, 1);
776                 glVertex2f(quad.xmax, quad.ymax);
777                 glTexCoord2f(0, 1);
778                 glVertex2f(quad.xmin, quad.ymax);
779                 glEnd();
780
781                 if (do_pop)
782                         glPopMatrix();
783         }
784 }
785
786 static void paint_draw_alpha_overlay(
787         UnifiedPaintSettings *ups, Brush *brush,
788         ViewContext *vc, int x, int y, float zoom, ePaintMode mode)
789 {
790         /* color means that primary brush texture is colured and secondary is used for alpha/mask control */
791         bool col = ELEM(mode, ePaintTexture3D, ePaintTexture2D, ePaintVertex) ? true : false;
792         eOverlayControlFlags flags = BKE_paint_get_overlay_flags();
793         /* save lots of GL state
794          * TODO: check on whether all of these are needed? */
795         glPushAttrib(GL_COLOR_BUFFER_BIT |
796                      GL_CURRENT_BIT |
797                      GL_DEPTH_BUFFER_BIT |
798                      GL_ENABLE_BIT |
799                      GL_LINE_BIT |
800                      GL_POLYGON_BIT |
801                      GL_STENCIL_BUFFER_BIT |
802                      GL_TRANSFORM_BIT |
803                      GL_VIEWPORT_BIT |
804                      GL_TEXTURE_BIT);
805
806
807         /* coloured overlay should be drawn separately */
808         if (col) {
809                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY))
810                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, true, true);
811                 if (!(flags & PAINT_OVERLAY_OVERRIDE_SECONDARY))
812                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, false);
813                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
814                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
815         }
816         else {
817                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY) && (mode != ePaintWeight))
818                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, true);
819                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
820                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
821         }
822
823         glPopAttrib();
824         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
825 }
826
827
828 BLI_INLINE void draw_tri_point(float *co, float width, bool selected)
829 {
830         float w = width / 2.0f;
831         if (selected)
832                 UI_ThemeColor4(TH_VERTEX_SELECT);
833         else
834                 UI_ThemeColor4(TH_PAINT_CURVE_PIVOT);
835
836         glLineWidth(3.0);
837
838         glBegin(GL_LINE_LOOP);
839         glVertex2f(co[0], co[1] + w);
840         glVertex2f(co[0] - w, co[1] - w);
841         glVertex2f(co[0] + w, co[1] - w);
842         glEnd();
843
844         glColor4f(1.0, 1.0, 1.0, 0.5);
845         glLineWidth(1.0);
846
847         glBegin(GL_LINE_LOOP);
848         glVertex2f(co[0], co[1] + w);
849         glVertex2f(co[0] - w, co[1] - w);
850         glVertex2f(co[0] + w, co[1] - w);
851         glEnd();
852 }
853
854 BLI_INLINE void draw_rect_point(float *co, float width, bool selected)
855 {
856         float w = width / 2.0f;
857         if (selected)
858                 UI_ThemeColor4(TH_VERTEX_SELECT);
859         else
860                 UI_ThemeColor4(TH_PAINT_CURVE_HANDLE);
861         glLineWidth(3.0);
862
863         glBegin(GL_LINE_LOOP);
864         glVertex2f(co[0] + w, co[1] + w);
865         glVertex2f(co[0] - w, co[1] + w);
866         glVertex2f(co[0] - w, co[1] - w);
867         glVertex2f(co[0] + w, co[1] - w);
868         glEnd();
869
870         glColor4f(1.0, 1.0, 1.0, 0.5);
871         glLineWidth(1.0);
872
873         glBegin(GL_LINE_LOOP);
874         glVertex2f(co[0] + w, co[1] + w);
875         glVertex2f(co[0] - w, co[1] + w);
876         glVertex2f(co[0] - w, co[1] - w);
877         glVertex2f(co[0] + w, co[1] - w);
878         glEnd();
879 }
880
881
882 BLI_INLINE void draw_bezier_handle_lines(BezTriple *bez)
883 {
884         short line1[] = {0, 1};
885         short line2[] = {1, 2};
886
887         glVertexPointer(2, GL_FLOAT, 3 * sizeof(float), bez->vec);
888         glColor4f(0.0, 0.0, 0.0, 0.5);
889         glLineWidth(3.0);
890         glDrawArrays(GL_LINE_STRIP, 0, 3);
891
892         glLineWidth(1.0);
893         if (bez->f1 || bez->f2)
894                 UI_ThemeColor4(TH_VERTEX_SELECT);
895         else
896                 glColor4f(1.0, 1.0, 1.0, 0.5);
897         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line1);
898         if (bez->f3 || bez->f2)
899                 UI_ThemeColor4(TH_VERTEX_SELECT);
900         else
901                 glColor4f(1.0, 1.0, 1.0, 0.5);
902         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line2);
903 }
904
905 static void paint_draw_curve_cursor(Brush *brush)
906 {
907         if (brush->paint_curve && brush->paint_curve->points) {
908                 int i;
909                 PaintCurve *pc = brush->paint_curve;
910                 PaintCurvePoint *cp = pc->points;
911
912                 glEnable(GL_LINE_SMOOTH);
913                 glEnable(GL_BLEND);
914                 glEnableClientState(GL_VERTEX_ARRAY);
915
916                 /* draw the bezier handles and the curve segment between the current and next point */
917                 for (i = 0; i < pc->tot_points - 1; i++, cp++) {
918                         int j;
919                         PaintCurvePoint *cp_next = cp + 1;
920                         float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
921                         /* use color coding to distinguish handles vs curve segments  */
922                         draw_bezier_handle_lines(&cp->bez);
923                         draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
924                         draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
925                         draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
926
927                         for (j = 0; j < 2; j++)
928                                 BKE_curve_forward_diff_bezier(
929                                         cp->bez.vec[1][j],
930                                         cp->bez.vec[2][j],
931                                         cp_next->bez.vec[0][j],
932                                         cp_next->bez.vec[1][j],
933                                         data + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
934
935                         glVertexPointer(2, GL_FLOAT, 0, data);
936                         glLineWidth(3.0);
937                         glColor4f(0.0, 0.0, 0.0, 0.5);
938                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
939
940                         glLineWidth(1.0);
941                         glColor4f(0.9, 0.9, 1.0, 0.5);
942                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
943                 }
944
945                 /* draw last line segment */
946                 draw_bezier_handle_lines(&cp->bez);
947                 draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
948                 draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
949                 draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
950
951                 glDisable(GL_BLEND);
952                 glDisable(GL_LINE_SMOOTH);
953                 glDisableClientState(GL_VERTEX_ARRAY);
954         }
955 }
956
957 /* Special actions taken when paint cursor goes over mesh */
958 /* TODO: sculpt only for now */
959 static void paint_cursor_on_hit(
960         UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
961         const float location[3])
962 {
963         float unprojected_radius, projected_radius;
964
965         /* update the brush's cached 3D radius */
966         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
967                 /* get 2D brush radius */
968                 if (ups->draw_anchored)
969                         projected_radius = ups->anchored_size;
970                 else {
971                         if (brush->flag & BRUSH_ANCHORED)
972                                 projected_radius = 8;
973                         else
974                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
975                 }
976
977                 /* convert brush radius from 2D to 3D */
978                 unprojected_radius = paint_calc_object_space_radius(
979                         vc, location, projected_radius);
980
981                 /* scale 3D brush radius by pressure */
982                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush))
983                         unprojected_radius *= ups->size_pressure_value;
984
985                 /* set cached value in either Brush or UnifiedPaintSettings */
986                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
987         }
988 }
989
990 static bool ommit_cursor_drawing(Paint *paint, ePaintMode mode, Brush *brush)
991 {
992         if (paint->flags & PAINT_SHOW_BRUSH) {
993                 if (ELEM(mode, ePaintTexture2D, ePaintTexture3D) && brush->imagepaint_tool == PAINT_TOOL_FILL) {
994                         return true;
995                 }
996                 return false;
997         }
998         return true;
999 }
1000
1001 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
1002 {
1003         Scene *scene = CTX_data_scene(C);
1004         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1005         Paint *paint = BKE_paint_get_active_from_context(C);
1006         Brush *brush = BKE_paint_brush(paint);
1007         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
1008         ViewContext vc;
1009         float final_radius;
1010         float translation[2];
1011         float outline_alpha, *outline_col;
1012         float zoomx, zoomy;
1013
1014         /* check that brush drawing is enabled */
1015         if (ommit_cursor_drawing(paint, mode, brush))
1016                 return;
1017
1018         /* can't use stroke vc here because this will be called during
1019          * mouse over too, not just during a stroke */
1020         ED_view3d_viewcontext_init(C, &vc);
1021
1022         if (vc.rv3d && (vc.rv3d->rflag & RV3D_NAVIGATING)) {
1023                 return;
1024         }
1025
1026         /* skip everything and draw brush here */
1027         if (brush->flag & BRUSH_CURVE) {
1028                 paint_draw_curve_cursor(brush);
1029                 return;
1030         }
1031
1032         get_imapaint_zoom(C, &zoomx, &zoomy);
1033         zoomx = max_ff(zoomx, zoomy);
1034
1035         /* set various defaults */
1036         translation[0] = x;
1037         translation[1] = y;
1038         outline_alpha = 0.5;
1039         outline_col = brush->add_col;
1040         final_radius = (BKE_brush_size_get(scene, brush) * zoomx);
1041
1042         /* don't calculate rake angles while a stroke is active because the rake variables are global and
1043          * we may get interference with the stroke itself. For line strokes, such interference is visible */
1044         if (!ups->stroke_active) {
1045                 paint_calculate_rake_rotation(ups, brush, translation);
1046         }
1047
1048         /* draw overlay */
1049         paint_draw_alpha_overlay(ups, brush, &vc, x, y, zoomx, mode);
1050
1051         /* TODO: as sculpt and other paint modes are unified, this
1052          * special mode of drawing will go away */
1053         if ((mode == ePaintSculpt) && vc.obact->sculpt) {
1054                 float location[3];
1055                 int pixel_radius;
1056                 bool hit;
1057
1058                 /* test if brush is over the mesh */
1059                 hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location, ups);
1060
1061                 if (BKE_brush_use_locked_size(scene, brush))
1062                         BKE_brush_size_set(scene, brush, pixel_radius);
1063
1064                 /* check if brush is subtracting, use different color then */
1065                 /* TODO: no way currently to know state of pen flip or
1066                  * invert key modifier without starting a stroke */
1067                 if (((ups->draw_inverted == 0) ^ ((brush->flag & BRUSH_DIR_IN) == 0)) &&
1068                     BKE_brush_sculpt_has_secondary_color(brush))
1069                 {
1070                         outline_col = brush->sub_col;
1071                 }
1072
1073                 /* only do if brush is over the mesh */
1074                 if (hit)
1075                         paint_cursor_on_hit(ups, brush, &vc, location);
1076         }
1077
1078         if (ups->draw_anchored) {
1079                 final_radius = ups->anchored_size;
1080                 translation[0] = ups->anchored_initial_mouse[0];
1081                 translation[1] = ups->anchored_initial_mouse[1];
1082         }
1083
1084         /* make lines pretty */
1085         glLineWidth(1.0f);
1086         glEnable(GL_BLEND);
1087         glEnable(GL_LINE_SMOOTH);
1088
1089         /* set brush color */
1090         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
1091
1092         /* draw brush outline */
1093         glTranslate2fv(translation);
1094
1095         /* draw an inner brush */
1096         if (ups->stroke_active && BKE_brush_use_size_pressure(scene, brush)) {
1097                 /* inner at full alpha */
1098                 glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius * ups->size_pressure_value, 40);
1099                 /* outer at half alpha */
1100                 glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha * 0.5f);
1101         }
1102         glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius, 40);
1103         glTranslatef(-translation[0], -translation[1], 0);
1104
1105         /* restore GL state */
1106         glDisable(GL_BLEND);
1107         glDisable(GL_LINE_SMOOTH);
1108 }
1109
1110 /* Public API */
1111
1112 void paint_cursor_start(bContext *C, bool (*poll)(bContext *C))
1113 {
1114         Paint *p = BKE_paint_get_active_from_context(C);
1115
1116         if (p && !p->paint_cursor)
1117                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
1118
1119         /* invalidate the paint cursors */
1120         BKE_paint_invalidate_overlay_all();
1121 }
1122
1123 void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, bool (*poll)(bContext *C))
1124 {
1125         if (p && !p->paint_cursor)
1126                 p->paint_cursor = WM_paint_cursor_activate(wm, poll, paint_draw_cursor, NULL);
1127 }