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