Cleanup: Math lib naming (use v3 suffix)
[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(void *userdata, void *UNUSED(userdata_chunck), const int j, const int thread_id)
155 {
156         LoadTexData *data = userdata;
157         Brush *br = data->br;
158         ViewContext *vc = data->vc;
159
160         MTex *mtex = data->mtex;
161         GLubyte *buffer = data->buffer;
162         const bool col = data->col;
163
164         struct ImagePool *pool = data->pool;
165         const int size = data->size;
166         const float rotation = data->rotation;
167         const float radius = data->radius;
168
169         bool convert_to_linear = false;
170         struct ColorSpace *colorspace = NULL;
171
172         if (mtex->tex && mtex->tex->type == TEX_IMAGE && mtex->tex->ima) {
173                 ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(mtex->tex->ima, &mtex->tex->iuser, pool);
174                 /* For consistency, sampling always returns color in linear space */
175                 if (tex_ibuf && tex_ibuf->rect_float == NULL) {
176                         convert_to_linear = true;
177                         colorspace = tex_ibuf->rect_colorspace;
178                 }
179                 BKE_image_pool_release_ibuf(mtex->tex->ima, tex_ibuf, pool);
180         }
181
182         for (int i = 0; i < size; i++) {
183                 // largely duplicated from tex_strength
184
185                 int index = j * size + i;
186
187                 float x = (float)i / size;
188                 float y = (float)j / size;
189                 float len;
190
191                 if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
192                         x *= vc->ar->winx / radius;
193                         y *= vc->ar->winy / radius;
194                 }
195                 else {
196                         x = (x - 0.5f) * 2.0f;
197                         y = (y - 0.5f) * 2.0f;
198                 }
199
200                 len = sqrtf(x * x + y * y);
201
202                 if (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL) || len <= 1.0f) {
203                         /* it is probably worth optimizing for those cases where the texture is not rotated by skipping the calls to
204                          * atan2, sqrtf, sin, and cos. */
205                         if (mtex->tex && (rotation > 0.001f || rotation < -0.001f)) {
206                                 const float angle = atan2f(y, x) + rotation;
207
208                                 x = len * cosf(angle);
209                                 y = len * sinf(angle);
210                         }
211
212                         if (col) {
213                                 float rgba[4];
214
215                                 paint_get_tex_pixel_col(mtex, x, y, rgba, pool, thread_id, convert_to_linear, colorspace);
216
217                                 buffer[index * 4]     = rgba[0] * 255;
218                                 buffer[index * 4 + 1] = rgba[1] * 255;
219                                 buffer[index * 4 + 2] = rgba[2] * 255;
220                                 buffer[index * 4 + 3] = rgba[3] * 255;
221                         }
222                         else {
223                                 float avg = paint_get_tex_pixel(mtex, x, y, pool, thread_id);
224
225                                 avg += br->texture_sample_bias;
226
227                                 /* clamp to avoid precision overflow */
228                                 CLAMP(avg, 0.0f, 1.0f);
229                                 buffer[index] = 255 - (GLubyte)(255 * avg);
230                         }
231                 }
232                 else {
233                         if (col) {
234                                 buffer[index * 4]     = 0;
235                                 buffer[index * 4 + 1] = 0;
236                                 buffer[index * 4 + 2] = 0;
237                                 buffer[index * 4 + 3] = 0;
238                         }
239                         else {
240                                 buffer[index] = 0;
241                         }
242                 }
243         }
244 }
245
246 static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool primary)
247 {
248         bool init;
249         TexSnapshot *target;
250
251         MTex *mtex = (primary) ? &br->mtex : &br->mask_mtex;
252         OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
253         GLubyte *buffer = NULL;
254
255         int size;
256         bool refresh;
257         OverlayControlFlags invalid = (primary) ? (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
258                                                   (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY);
259
260         target = (primary) ? &primary_snap : &secondary_snap;
261
262         refresh = 
263             !target->overlay_texture ||
264             (invalid != 0) ||
265             !same_tex_snap(target, mtex, vc, col, zoom);
266
267         init = (target->overlay_texture != 0);
268
269         if (refresh) {
270                 struct ImagePool *pool = NULL;
271                 /* stencil is rotated later */
272                 const float rotation = (mtex->brush_map_mode != MTEX_MAP_MODE_STENCIL) ? -mtex->rot : 0.0f;
273                 const float radius = BKE_brush_size_get(vc->scene, br) * zoom;
274
275                 make_tex_snap(target, vc, zoom);
276
277                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
278                         int s = BKE_brush_size_get(vc->scene, br);
279                         int r = 1;
280
281                         for (s >>= 1; s > 0; s >>= 1)
282                                 r++;
283
284                         size = (1 << r);
285
286                         if (size < 256)
287                                 size = 256;
288
289                         if (size < target->old_size)
290                                 size = target->old_size;
291                 }
292                 else {
293                         size = 512;
294                 }
295
296                 if (target->old_size != size) {
297                         if (target->overlay_texture) {
298                                 glDeleteTextures(1, &target->overlay_texture);
299                                 target->overlay_texture = 0;
300                         }
301
302                         init = false;
303
304                         target->old_size = size;
305                 }
306                 if (col)
307                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size * 4, "load_tex");
308                 else
309                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
310
311                 pool = BKE_image_pool_new();
312
313                 if (mtex->tex && mtex->tex->nodetree)
314                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
315
316                 LoadTexData data = {
317                     .br = br, .vc = vc, .mtex = mtex, .buffer = buffer, .col = col,
318                     .pool = pool, .size = size, .rotation = rotation, .radius = radius,
319                 };
320
321                 BLI_task_parallel_range_ex(0, size, &data, NULL, 0, load_tex_task_cb_ex, true, false);
322
323                 if (mtex->tex && mtex->tex->nodetree)
324                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
325
326                 if (pool)
327                         BKE_image_pool_free(pool);
328
329                 if (!target->overlay_texture)
330                         glGenTextures(1, &target->overlay_texture);
331         }
332         else {
333                 size = target->old_size;
334         }
335
336         glBindTexture(GL_TEXTURE_2D, target->overlay_texture);
337
338         if (refresh) {
339                 GLenum format = col ? GL_RGBA : GL_ALPHA;
340                 GLenum internalformat = col ? GL_RGBA8 : GL_ALPHA8;
341
342                 if (!init || (target->old_col != col)) {
343                         glTexImage2D(GL_TEXTURE_2D, 0, internalformat, size, size, 0, format, GL_UNSIGNED_BYTE, buffer);
344                 }
345                 else {
346                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, format, GL_UNSIGNED_BYTE, buffer);
347                 }
348
349                 if (buffer)
350                         MEM_freeN(buffer);
351
352                 target->old_col = col;
353         }
354
355         GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
356
357         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
358         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
359
360         if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
361                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
362                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
363         }
364
365         BKE_paint_reset_overlay_invalid(invalid);
366
367         return 1;
368 }
369
370 static void load_tex_cursor_task_cb(void *userdata, const int j)
371 {
372         LoadTexData *data = userdata;
373         Brush *br = data->br;
374
375         GLubyte *buffer = data->buffer;
376
377         const int size = data->size;
378
379         for (int i = 0; i < size; i++) {
380                 // largely duplicated from tex_strength
381
382                 const int index = j * size + i;
383                 const float x = (((float)i / size) - 0.5f) * 2.0f;
384                 const float y = (((float)j / size) - 0.5f) * 2.0f;
385                 const float len = sqrtf(x * x + y * y);
386
387                 if (len <= 1.0f) {
388                         float avg = BKE_brush_curve_strength_clamped(br, len, 1.0f);  /* Falloff curve */
389
390                         buffer[index] = 255 - (GLubyte)(255 * avg);
391                 }
392                 else {
393                         buffer[index] = 0;
394                 }
395         }
396 }
397
398 static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
399 {
400         bool init;
401
402         OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
403         GLubyte *buffer = NULL;
404
405         int size;
406         const bool refresh =
407             !cursor_snap.overlay_texture ||
408             (overlay_flags & PAINT_INVALID_OVERLAY_CURVE) ||
409             cursor_snap.zoom != zoom;
410
411         init = (cursor_snap.overlay_texture != 0);
412
413         if (refresh) {
414                 int s, r;
415
416                 cursor_snap.zoom = zoom;
417
418                 s = BKE_brush_size_get(vc->scene, br);
419                 r = 1;
420
421                 for (s >>= 1; s > 0; s >>= 1)
422                         r++;
423
424                 size = (1 << r);
425
426                 if (size < 256)
427                         size = 256;
428
429                 if (size < cursor_snap.size)
430                         size = cursor_snap.size;
431
432                 if (cursor_snap.size != size) {
433                         if (cursor_snap.overlay_texture) {
434                                 glDeleteTextures(1, &cursor_snap.overlay_texture);
435                                 cursor_snap.overlay_texture = 0;
436                         }
437
438                         init = false;
439
440                         cursor_snap.size = size;
441                 }
442                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
443
444                 curvemapping_initialize(br->curve);
445
446                 LoadTexData data = {
447                     .br = br, .buffer = buffer, .size = size,
448                 };
449
450                 BLI_task_parallel_range(0, size, &data, load_tex_cursor_task_cb, true);
451
452                 if (!cursor_snap.overlay_texture)
453                         glGenTextures(1, &cursor_snap.overlay_texture);
454         }
455         else {
456                 size = cursor_snap.size;
457         }
458
459         glBindTexture(GL_TEXTURE_2D, cursor_snap.overlay_texture);
460
461         if (refresh) {
462                 if (!init) {
463                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
464                 }
465                 else {
466                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
467                 }
468
469                 if (buffer)
470                         MEM_freeN(buffer);
471         }
472
473         GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
474
475         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
476         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
477
478         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
479         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
480
481         BKE_paint_reset_overlay_invalid(PAINT_INVALID_OVERLAY_CURVE);
482
483         return 1;
484 }
485
486
487
488 static int project_brush_radius(ViewContext *vc,
489                                 float radius,
490                                 const float location[3])
491 {
492         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
493
494         ED_view3d_global_to_vector(vc->rv3d, location, view);
495
496         /* create a vector that is not orthogonal to view */
497
498         if (fabsf(view[0]) < 0.1f) {
499                 nonortho[0] = view[0] + 1.0f;
500                 nonortho[1] = view[1];
501                 nonortho[2] = view[2];
502         }
503         else if (fabsf(view[1]) < 0.1f) {
504                 nonortho[0] = view[0];
505                 nonortho[1] = view[1] + 1.0f;
506                 nonortho[2] = view[2];
507         }
508         else {
509                 nonortho[0] = view[0];
510                 nonortho[1] = view[1];
511                 nonortho[2] = view[2] + 1.0f;
512         }
513
514         /* get a vector in the plane of the view */
515         cross_v3_v3v3(ortho, nonortho, view);
516         normalize_v3(ortho);
517
518         /* make a point on the surface of the brush tagent to the view */
519         mul_v3_fl(ortho, radius);
520         add_v3_v3v3(offset, location, ortho);
521
522         /* project the center of the brush, and the tangent point to the view onto the screen */
523         if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
524             (ED_view3d_project_float_global(vc->ar, offset,   p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
525         {
526                 /* the distance between these points is the size of the projected brush in pixels */
527                 return len_v2v2(p1, p2);
528         }
529         else {
530                 BLI_assert(0);  /* assert because the code that sets up the vectors should disallow this */
531                 return 0;
532         }
533 }
534
535 static bool sculpt_get_brush_geometry(
536         bContext *C, ViewContext *vc,
537         int x, int y, int *pixel_radius,
538         float location[3], UnifiedPaintSettings *ups)
539 {
540         Scene *scene = CTX_data_scene(C);
541         Paint *paint = BKE_paint_get_active_from_context(C);
542         float mouse[2];
543         bool hit = false;
544
545         mouse[0] = x;
546         mouse[1] = y;
547
548         if (vc->obact->sculpt && vc->obact->sculpt->pbvh) {
549                 if (!ups->stroke_active) {
550                         hit = sculpt_stroke_get_location(C, location, mouse);
551                 }
552                 else {
553                         hit = ups->last_hit;
554                         copy_v3_v3(location, ups->last_location);
555                 }
556         }
557
558         if (hit) {
559                 Brush *brush = BKE_paint_brush(paint);
560
561                 *pixel_radius =
562                         project_brush_radius(vc,
563                                              BKE_brush_unprojected_radius_get(scene, brush),
564                                              location);
565
566                 if (*pixel_radius == 0)
567                         *pixel_radius = BKE_brush_size_get(scene, brush);
568
569                 mul_m4_v3(vc->obact->obmat, location);
570         }
571         else {
572                 Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;
573                 Brush *brush = BKE_paint_brush(&sd->paint);
574
575                 *pixel_radius = BKE_brush_size_get(scene, brush);
576         }
577
578         return hit;
579 }
580
581 /* Draw an overlay that shows what effect the brush's texture will
582  * have on brush strength */
583 static void paint_draw_tex_overlay(UnifiedPaintSettings *ups, Brush *brush,
584                                      ViewContext *vc, int x, int y, float zoom, bool col, bool primary)
585 {
586         rctf quad;
587         /* check for overlay mode */
588
589         MTex *mtex = (primary) ? &brush->mtex : &brush->mask_mtex;
590         bool valid = (primary) ? (brush->overlay_flags & BRUSH_OVERLAY_PRIMARY) != 0 :
591                                  (brush->overlay_flags & BRUSH_OVERLAY_SECONDARY) != 0;
592         int overlay_alpha = (primary) ? brush->texture_overlay_alpha : brush->mask_overlay_alpha;
593
594         if (!(mtex->tex) || !((mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) ||
595             (valid &&
596             ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_TILED))))
597         {
598                 return;
599         }
600
601         if (load_tex(brush, vc, zoom, col, primary)) {
602                 glEnable(GL_BLEND);
603
604                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
605                 glDepthMask(GL_FALSE);
606                 glDepthFunc(GL_ALWAYS);
607
608                 glMatrixMode(GL_TEXTURE);
609                 glPushMatrix();
610                 glLoadIdentity();
611
612                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
613                         /* brush rotation */
614                         glTranslatef(0.5, 0.5, 0);
615                         glRotatef((double)RAD2DEGF((primary) ? ups->brush_rotation : ups->brush_rotation_sec),
616                                   0.0, 0.0, 1.0);
617                         glTranslatef(-0.5f, -0.5f, 0);
618
619                         /* scale based on tablet pressure */
620                         if (primary && ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
621                                 glTranslatef(0.5f, 0.5f, 0);
622                                 glScalef(1.0f / ups->size_pressure_value, 1.0f / ups->size_pressure_value, 1);
623                                 glTranslatef(-0.5f, -0.5f, 0);
624                         }
625
626                         if (ups->draw_anchored) {
627                                 const float *aim = ups->anchored_initial_mouse;
628                                 quad.xmin = aim[0] - ups->anchored_size;
629                                 quad.ymin = aim[1] - ups->anchored_size;
630                                 quad.xmax = aim[0] + ups->anchored_size;
631                                 quad.ymax = aim[1] + ups->anchored_size;
632                         }
633                         else {
634                                 const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
635                                 quad.xmin = x - radius;
636                                 quad.ymin = y - radius;
637                                 quad.xmax = x + radius;
638                                 quad.ymax = y + radius;
639                         }
640                 }
641                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
642                         quad.xmin = 0;
643                         quad.ymin = 0;
644                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
645                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
646                 }
647                 /* Stencil code goes here */
648                 else {
649                         if (primary) {
650                                 quad.xmin = -brush->stencil_dimension[0];
651                                 quad.ymin = -brush->stencil_dimension[1];
652                                 quad.xmax = brush->stencil_dimension[0];
653                                 quad.ymax = brush->stencil_dimension[1];
654                         }
655                         else {
656                                 quad.xmin = -brush->mask_stencil_dimension[0];
657                                 quad.ymin = -brush->mask_stencil_dimension[1];
658                                 quad.xmax = brush->mask_stencil_dimension[0];
659                                 quad.ymax = brush->mask_stencil_dimension[1];
660                         }
661                         glMatrixMode(GL_MODELVIEW);
662                         glPushMatrix();
663                         if (primary)
664                                 glTranslate2fv(brush->stencil_pos);
665                         else
666                                 glTranslate2fv(brush->mask_stencil_pos);
667                         glRotatef(RAD2DEGF(mtex->rot), 0, 0, 1);
668                         glMatrixMode(GL_TEXTURE);
669                 }
670
671                 /* set quad color. Colored overlay does not get blending */
672                 if (col) {
673                         glColor4f(1.0, 1.0, 1.0, overlay_alpha / 100.0f);
674                 }
675                 else {
676                         glColor4f(UNPACK3(U.sculpt_paint_overlay_col), overlay_alpha / 100.0f);
677                 }
678
679                 /* draw textured quad */
680                 glBegin(GL_QUADS);
681                 glTexCoord2f(0, 0);
682                 glVertex2f(quad.xmin, quad.ymin);
683                 glTexCoord2f(1, 0);
684                 glVertex2f(quad.xmax, quad.ymin);
685                 glTexCoord2f(1, 1);
686                 glVertex2f(quad.xmax, quad.ymax);
687                 glTexCoord2f(0, 1);
688                 glVertex2f(quad.xmin, quad.ymax);
689                 glEnd();
690
691                 glPopMatrix();
692
693                 if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
694                         glMatrixMode(GL_MODELVIEW);
695                         glPopMatrix();
696                 }
697         }
698 }
699
700 /* Draw an overlay that shows what effect the brush's texture will
701  * have on brush strength */
702 static void paint_draw_cursor_overlay(UnifiedPaintSettings *ups, Brush *brush,
703                                       ViewContext *vc, int x, int y, float zoom)
704 {
705         rctf quad;
706         /* check for overlay mode */
707
708         if (!(brush->overlay_flags & BRUSH_OVERLAY_CURSOR)) {
709                 return;
710         }
711
712         if (load_tex_cursor(brush, vc, zoom)) {
713                 bool do_pop = false;
714                 float center[2];
715                 glEnable(GL_BLEND);
716
717                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
718                 glDepthMask(GL_FALSE);
719                 glDepthFunc(GL_ALWAYS);
720
721                 if (ups->draw_anchored) {
722                         const float *aim = ups->anchored_initial_mouse;
723                         copy_v2_v2(center, aim);
724                         quad.xmin = aim[0] - ups->anchored_size;
725                         quad.ymin = aim[1] - ups->anchored_size;
726                         quad.xmax = aim[0] + ups->anchored_size;
727                         quad.ymax = aim[1] + ups->anchored_size;
728                 }
729                 else {
730                         const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
731                         center[0] = x;
732                         center[1] = y;
733
734                         quad.xmin = x - radius;
735                         quad.ymin = y - radius;
736                         quad.xmax = x + radius;
737                         quad.ymax = y + radius;
738                 }
739
740                 /* scale based on tablet pressure */
741                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
742                         do_pop = true;
743                         glPushMatrix();
744                         glLoadIdentity();
745                         glTranslate2fv(center);
746                         glScalef(ups->size_pressure_value, ups->size_pressure_value, 1);
747                         glTranslatef(-center[0], -center[1], 0);
748                 }
749
750                 glColor4f(U.sculpt_paint_overlay_col[0],
751                         U.sculpt_paint_overlay_col[1],
752                         U.sculpt_paint_overlay_col[2],
753                         brush->cursor_overlay_alpha / 100.0f);
754
755                 /* draw textured quad */
756                 glBegin(GL_QUADS);
757                 glTexCoord2f(0, 0);
758                 glVertex2f(quad.xmin, quad.ymin);
759                 glTexCoord2f(1, 0);
760                 glVertex2f(quad.xmax, quad.ymin);
761                 glTexCoord2f(1, 1);
762                 glVertex2f(quad.xmax, quad.ymax);
763                 glTexCoord2f(0, 1);
764                 glVertex2f(quad.xmin, quad.ymax);
765                 glEnd();
766
767                 if (do_pop)
768                         glPopMatrix();
769         }
770 }
771
772 static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush,
773                                      ViewContext *vc, int x, int y, float zoom, PaintMode mode)
774 {
775         /* color means that primary brush texture is colured and secondary is used for alpha/mask control */
776         bool col = ELEM(mode, ePaintTextureProjective, ePaintTexture2D, ePaintVertex) ? true : false;
777         OverlayControlFlags flags = BKE_paint_get_overlay_flags();
778         /* save lots of GL state
779          * TODO: check on whether all of these are needed? */
780         glPushAttrib(GL_COLOR_BUFFER_BIT |
781                      GL_CURRENT_BIT |
782                      GL_DEPTH_BUFFER_BIT |
783                      GL_ENABLE_BIT |
784                      GL_LINE_BIT |
785                      GL_POLYGON_BIT |
786                      GL_STENCIL_BUFFER_BIT |
787                      GL_TRANSFORM_BIT |
788                      GL_VIEWPORT_BIT |
789                      GL_TEXTURE_BIT);
790
791
792         /* coloured overlay should be drawn separately */
793         if (col) {
794                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY))
795                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, true, true);
796                 if (!(flags & PAINT_OVERLAY_OVERRIDE_SECONDARY))
797                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, false);
798                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
799                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
800         }
801         else {
802                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY) && (mode != ePaintWeight))
803                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, true);
804                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
805                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
806         }
807
808         glPopAttrib();
809         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
810 }
811
812
813 BLI_INLINE void draw_tri_point(float *co, float width, bool selected)
814 {
815         float w = width / 2.0f;
816         if (selected)
817                 UI_ThemeColor4(TH_VERTEX_SELECT);
818         else
819                 UI_ThemeColor4(TH_PAINT_CURVE_PIVOT);
820
821         glLineWidth(3.0);
822
823         glBegin(GL_LINE_LOOP);
824         glVertex2f(co[0], co[1] + w);
825         glVertex2f(co[0] - w, co[1] - w);
826         glVertex2f(co[0] + w, co[1] - w);
827         glEnd();
828
829         glColor4f(1.0, 1.0, 1.0, 0.5);
830         glLineWidth(1.0);
831
832         glBegin(GL_LINE_LOOP);
833         glVertex2f(co[0], co[1] + w);
834         glVertex2f(co[0] - w, co[1] - w);
835         glVertex2f(co[0] + w, co[1] - w);
836         glEnd();
837 }
838
839 BLI_INLINE void draw_rect_point(float *co, float width, bool selected)
840 {
841         float w = width / 2.0f;
842         if (selected)
843                 UI_ThemeColor4(TH_VERTEX_SELECT);
844         else
845                 UI_ThemeColor4(TH_PAINT_CURVE_HANDLE);
846         glLineWidth(3.0);
847
848         glBegin(GL_LINE_LOOP);
849         glVertex2f(co[0] + w, co[1] + w);
850         glVertex2f(co[0] - w, co[1] + w);
851         glVertex2f(co[0] - w, co[1] - w);
852         glVertex2f(co[0] + w, co[1] - w);
853         glEnd();
854
855         glColor4f(1.0, 1.0, 1.0, 0.5);
856         glLineWidth(1.0);
857
858         glBegin(GL_LINE_LOOP);
859         glVertex2f(co[0] + w, co[1] + w);
860         glVertex2f(co[0] - w, co[1] + w);
861         glVertex2f(co[0] - w, co[1] - w);
862         glVertex2f(co[0] + w, co[1] - w);
863         glEnd();
864 }
865
866
867 BLI_INLINE void draw_bezier_handle_lines(BezTriple *bez)
868 {
869         short line1[] = {0, 1};
870         short line2[] = {1, 2};
871
872         glVertexPointer(2, GL_FLOAT, 3 * sizeof(float), bez->vec);
873         glColor4f(0.0, 0.0, 0.0, 0.5);
874         glLineWidth(3.0);
875         glDrawArrays(GL_LINE_STRIP, 0, 3);
876
877         glLineWidth(1.0);
878         if (bez->f1 || bez->f2)
879                 UI_ThemeColor4(TH_VERTEX_SELECT);
880         else
881                 glColor4f(1.0, 1.0, 1.0, 0.5);
882         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line1);
883         if (bez->f3 || bez->f2)
884                 UI_ThemeColor4(TH_VERTEX_SELECT);
885         else
886                 glColor4f(1.0, 1.0, 1.0, 0.5);
887         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line2);
888 }
889
890 static void paint_draw_curve_cursor(Brush *brush)
891 {
892         if (brush->paint_curve && brush->paint_curve->points) {
893                 int i;
894                 PaintCurve *pc = brush->paint_curve;
895                 PaintCurvePoint *cp = pc->points;
896
897                 glEnable(GL_LINE_SMOOTH);
898                 glEnable(GL_BLEND);
899                 glEnableClientState(GL_VERTEX_ARRAY);
900
901                 /* draw the bezier handles and the curve segment between the current and next point */
902                 for (i = 0; i < pc->tot_points - 1; i++, cp++) {
903                         int j;
904                         PaintCurvePoint *cp_next = cp + 1;
905                         float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
906                         /* use color coding to distinguish handles vs curve segments  */
907                         draw_bezier_handle_lines(&cp->bez);
908                         draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
909                         draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
910                         draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
911
912                         for (j = 0; j < 2; j++)
913                                 BKE_curve_forward_diff_bezier(
914                                         cp->bez.vec[1][j],
915                                         cp->bez.vec[2][j],
916                                         cp_next->bez.vec[0][j],
917                                         cp_next->bez.vec[1][j],
918                                         data + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
919
920                         glVertexPointer(2, GL_FLOAT, 0, data);
921                         glLineWidth(3.0);
922                         glColor4f(0.0, 0.0, 0.0, 0.5);
923                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
924
925                         glLineWidth(1.0);
926                         glColor4f(0.9, 0.9, 1.0, 0.5);
927                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
928                 }
929
930                 /* draw last line segment */
931                 draw_bezier_handle_lines(&cp->bez);
932                 draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
933                 draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
934                 draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
935
936                 glDisable(GL_BLEND);
937                 glDisable(GL_LINE_SMOOTH);
938                 glDisableClientState(GL_VERTEX_ARRAY);
939         }
940 }
941
942 /* Special actions taken when paint cursor goes over mesh */
943 /* TODO: sculpt only for now */
944 static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
945                                 const float location[3])
946 {
947         float unprojected_radius, projected_radius;
948
949         /* update the brush's cached 3D radius */
950         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
951                 /* get 2D brush radius */
952                 if (ups->draw_anchored)
953                         projected_radius = ups->anchored_size;
954                 else {
955                         if (brush->flag & BRUSH_ANCHORED)
956                                 projected_radius = 8;
957                         else
958                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
959                 }
960         
961                 /* convert brush radius from 2D to 3D */
962                 unprojected_radius = paint_calc_object_space_radius(vc, location,
963                                                                     projected_radius);
964
965                 /* scale 3D brush radius by pressure */
966                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush))
967                         unprojected_radius *= ups->size_pressure_value;
968
969                 /* set cached value in either Brush or UnifiedPaintSettings */
970                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
971         }
972 }
973
974 static bool ommit_cursor_drawing(Paint *paint, PaintMode mode, Brush *brush)
975 {
976         if (paint->flags & PAINT_SHOW_BRUSH) {
977                 if (ELEM(mode, ePaintTexture2D, ePaintTextureProjective) && brush->imagepaint_tool == PAINT_TOOL_FILL) {
978                         return true;
979                 }
980                 return false;
981         }
982         return true;
983 }
984
985 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
986 {
987         Scene *scene = CTX_data_scene(C);
988         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
989         Paint *paint = BKE_paint_get_active_from_context(C);
990         Brush *brush = BKE_paint_brush(paint);
991         PaintMode mode = BKE_paintmode_get_active_from_context(C);
992         ViewContext vc;
993         float final_radius;
994         float translation[2];
995         float outline_alpha, *outline_col;
996         float zoomx, zoomy;
997
998         /* check that brush drawing is enabled */
999         if (ommit_cursor_drawing(paint, mode, brush))
1000                 return;
1001
1002         /* can't use stroke vc here because this will be called during
1003          * mouse over too, not just during a stroke */
1004         view3d_set_viewcontext(C, &vc);
1005
1006         if (vc.rv3d->rflag & RV3D_NAVIGATING) {
1007                 return;
1008         }
1009
1010         /* skip everything and draw brush here */
1011         if (brush->flag & BRUSH_CURVE) {
1012                 paint_draw_curve_cursor(brush);
1013                 return;
1014         }
1015
1016         get_imapaint_zoom(C, &zoomx, &zoomy);
1017         zoomx = max_ff(zoomx, zoomy);
1018
1019         /* set various defaults */
1020         translation[0] = x;
1021         translation[1] = y;
1022         outline_alpha = 0.5;
1023         outline_col = brush->add_col;
1024         final_radius = (BKE_brush_size_get(scene, brush) * zoomx);
1025
1026         /* don't calculate rake angles while a stroke is active because the rake variables are global and
1027          * we may get interference with the stroke itself. For line strokes, such interference is visible */
1028         if (!ups->stroke_active) {
1029                 paint_calculate_rake_rotation(ups, brush, translation);
1030         }
1031
1032         /* draw overlay */
1033         paint_draw_alpha_overlay(ups, brush, &vc, x, y, zoomx, mode);
1034
1035         /* TODO: as sculpt and other paint modes are unified, this
1036          * special mode of drawing will go away */
1037         if ((mode == ePaintSculpt) && vc.obact->sculpt) {
1038                 float location[3];
1039                 int pixel_radius;
1040                 bool hit;
1041
1042                 /* test if brush is over the mesh */
1043                 hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location, ups);
1044
1045                 if (BKE_brush_use_locked_size(scene, brush))
1046                         BKE_brush_size_set(scene, brush, pixel_radius);
1047
1048                 /* check if brush is subtracting, use different color then */
1049                 /* TODO: no way currently to know state of pen flip or
1050                  * invert key modifier without starting a stroke */
1051                 if (((ups->draw_inverted == 0) ^ ((brush->flag & BRUSH_DIR_IN) == 0)) &&
1052                     BKE_brush_sculpt_has_secondary_color(brush))
1053                 {
1054                         outline_col = brush->sub_col;
1055                 }
1056
1057                 /* only do if brush is over the mesh */
1058                 if (hit)
1059                         paint_cursor_on_hit(ups, brush, &vc, location);
1060         }
1061
1062         if (ups->draw_anchored) {
1063                 final_radius = ups->anchored_size;
1064                 translation[0] = ups->anchored_initial_mouse[0];
1065                 translation[1] = ups->anchored_initial_mouse[1];
1066         }
1067
1068         /* make lines pretty */
1069         glLineWidth(1.0f);
1070         glEnable(GL_BLEND);
1071         glEnable(GL_LINE_SMOOTH);
1072
1073         /* set brush color */
1074         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
1075
1076         /* draw brush outline */
1077         glTranslate2fv(translation);
1078
1079         /* draw an inner brush */
1080         if (ups->stroke_active && BKE_brush_use_size_pressure(scene, brush)) {
1081                 /* inner at full alpha */
1082                 glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius * ups->size_pressure_value, 40);
1083                 /* outer at half alpha */
1084                 glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha * 0.5f);
1085         }
1086         glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius, 40);
1087         glTranslatef(-translation[0], -translation[1], 0);
1088
1089         /* restore GL state */
1090         glDisable(GL_BLEND);
1091         glDisable(GL_LINE_SMOOTH);
1092 }
1093
1094 /* Public API */
1095
1096 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
1097 {
1098         Paint *p = BKE_paint_get_active_from_context(C);
1099
1100         if (p && !p->paint_cursor)
1101                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
1102
1103         /* invalidate the paint cursors */
1104         BKE_paint_invalidate_overlay_all();
1105 }
1106
1107 void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, int (*poll)(bContext *C))
1108 {
1109         if (p && !p->paint_cursor)
1110                 p->paint_cursor = WM_paint_cursor_activate(wm, poll, paint_draw_cursor, NULL);
1111 }