Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / paint.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  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/paint.c
29  *  \ingroup bke
30  */
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_object_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_brush_types.h"
43 #include "DNA_space_types.h"
44
45 #include "BLI_bitmap.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_math_vector.h"
48 #include "BLI_listbase.h"
49
50 #include "BKE_brush.h"
51 #include "BKE_colortools.h"
52 #include "BKE_deform.h"
53 #include "BKE_main.h"
54 #include "BKE_context.h"
55 #include "BKE_crazyspace.h"
56 #include "BKE_global.h"
57 #include "BKE_image.h"
58 #include "BKE_key.h"
59 #include "BKE_library.h"
60 #include "BKE_mesh.h"
61 #include "BKE_modifier.h"
62 #include "BKE_object.h"
63 #include "BKE_paint.h"
64 #include "BKE_pbvh.h"
65 #include "BKE_subsurf.h"
66
67 #include "DEG_depsgraph.h"
68
69 #include "bmesh.h"
70
71 const char PAINT_CURSOR_SCULPT[3] = {255, 100, 100};
72 const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255};
73 const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255};
74 const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255};
75
76 static eOverlayControlFlags overlay_flags = 0;
77
78 void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Tex *tex)
79 {
80         /* TODO/OBMODE (we should combine all) */
81         Paint *p = BKE_paint_get_active(scene, view_layer, G.main->eval_ctx->object_mode);
82         Brush *br = p->brush;
83
84         if (!br)
85                 return;
86
87         if (br->mtex.tex == tex)
88                 overlay_flags |= PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY;
89         if (br->mask_mtex.tex == tex)
90                 overlay_flags |= PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY;
91 }
92
93 void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve)
94 {
95         /* TODO/OBMODE (we should combine all) */
96         Paint *p = BKE_paint_get_active(scene, view_layer, G.main->eval_ctx->object_mode);
97         Brush *br = p->brush;
98
99         if (br && br->curve == curve)
100                 overlay_flags |= PAINT_INVALID_OVERLAY_CURVE;
101 }
102
103 void BKE_paint_invalidate_overlay_all(void)
104 {
105         overlay_flags |= (PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY |
106                           PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY |
107                           PAINT_INVALID_OVERLAY_CURVE);
108 }
109
110 eOverlayControlFlags BKE_paint_get_overlay_flags(void)
111 {
112         return overlay_flags;
113 }
114
115 void BKE_paint_set_overlay_override(eOverlayFlags flags)
116 {
117         if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) {
118                 if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE)
119                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR;
120                 if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE)
121                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY;
122                 if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE)
123                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY;
124         }
125         else {
126                 overlay_flags &= ~(PAINT_OVERRIDE_MASK);
127         }
128 }
129
130 void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag)
131 {
132         overlay_flags &= ~(flag);
133 }
134
135 Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode)
136 {
137         if (sce) {
138                 ToolSettings *ts = sce->toolsettings;
139
140                 switch (mode) {
141                         case ePaintSculpt:
142                                 return &ts->sculpt->paint;
143                         case ePaintVertex:
144                                 return &ts->vpaint->paint;
145                         case ePaintWeight:
146                                 return &ts->wpaint->paint;
147                         case ePaintTexture2D:
148                         case ePaintTextureProjective:
149                                 return &ts->imapaint.paint;
150                         case ePaintSculptUV:
151                                 return &ts->uvsculpt->paint;
152                         case ePaintInvalid:
153                                 return NULL;
154                         default:
155                                 return &ts->imapaint.paint;
156                 }
157         }
158
159         return NULL;
160 }
161
162 Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer, const short object_mode)
163 {
164         if (sce && view_layer) {
165                 ToolSettings *ts = sce->toolsettings;
166                 
167                 if (view_layer->basact && view_layer->basact->object) {
168                         switch (object_mode) {
169                                 case OB_MODE_SCULPT:
170                                         return &ts->sculpt->paint;
171                                 case OB_MODE_VERTEX_PAINT:
172                                         return &ts->vpaint->paint;
173                                 case OB_MODE_WEIGHT_PAINT:
174                                         return &ts->wpaint->paint;
175                                 case OB_MODE_TEXTURE_PAINT:
176                                         return &ts->imapaint.paint;
177                                 case OB_MODE_EDIT:
178                                         if (ts->use_uv_sculpt)
179                                                 return &ts->uvsculpt->paint;
180                                         return &ts->imapaint.paint;
181                         }
182                 }
183
184                 /* default to image paint */
185                 return &ts->imapaint.paint;
186         }
187
188         return NULL;
189 }
190
191 Paint *BKE_paint_get_active_from_context(const bContext *C)
192 {
193         Scene *sce = CTX_data_scene(C);
194         ViewLayer *view_layer = CTX_data_view_layer(C);
195         SpaceImage *sima;
196
197         if (sce && view_layer) {
198                 EvaluationContext eval_ctx;
199                 CTX_data_eval_ctx(C, &eval_ctx);
200
201                 ToolSettings *ts = sce->toolsettings;
202                 Object *obact = NULL;
203
204                 if (view_layer->basact && view_layer->basact->object)
205                         obact = view_layer->basact->object;
206
207                 if ((sima = CTX_wm_space_image(C)) != NULL) {
208                         if (obact && eval_ctx.object_mode == OB_MODE_EDIT) {
209                                 if (sima->mode == SI_MODE_PAINT)
210                                         return &ts->imapaint.paint;
211                                 else if (ts->use_uv_sculpt)
212                                         return &ts->uvsculpt->paint;
213                         }
214                         else {
215                                 return &ts->imapaint.paint;
216                         }
217                 }
218                 else if (obact) {
219                         switch (eval_ctx.object_mode) {
220                                 case OB_MODE_SCULPT:
221                                         return &ts->sculpt->paint;
222                                 case OB_MODE_VERTEX_PAINT:
223                                         return &ts->vpaint->paint;
224                                 case OB_MODE_WEIGHT_PAINT:
225                                         return &ts->wpaint->paint;
226                                 case OB_MODE_TEXTURE_PAINT:
227                                         return &ts->imapaint.paint;
228                                 case OB_MODE_EDIT:
229                                         if (ts->use_uv_sculpt)
230                                                 return &ts->uvsculpt->paint;
231                                         return &ts->imapaint.paint;
232                                 default:
233                                         return &ts->imapaint.paint;
234                         }
235                 }
236                 else {
237                         /* default to image paint */
238                         return &ts->imapaint.paint;
239                 }
240         }
241
242         return NULL;
243 }
244
245 ePaintMode BKE_paintmode_get_active_from_context(const bContext *C)
246 {
247         Scene *sce = CTX_data_scene(C);
248         ViewLayer *view_layer = CTX_data_view_layer(C);
249         SpaceImage *sima;
250
251         if (sce && view_layer) {
252                 EvaluationContext eval_ctx;
253                 CTX_data_eval_ctx(C, &eval_ctx);
254
255                 ToolSettings *ts = sce->toolsettings;
256                 Object *obact = NULL;
257
258                 if (view_layer->basact && view_layer->basact->object)
259                         obact = view_layer->basact->object;
260
261                 if ((sima = CTX_wm_space_image(C)) != NULL) {
262                         if (obact && eval_ctx.object_mode == OB_MODE_EDIT) {
263                                 if (sima->mode == SI_MODE_PAINT)
264                                         return ePaintTexture2D;
265                                 else if (ts->use_uv_sculpt)
266                                         return ePaintSculptUV;
267                         }
268                         else {
269                                 return ePaintTexture2D;
270                         }
271                 }
272                 else if (obact) {
273                         switch (eval_ctx.object_mode) {
274                                 case OB_MODE_SCULPT:
275                                         return ePaintSculpt;
276                                 case OB_MODE_VERTEX_PAINT:
277                                         return ePaintVertex;
278                                 case OB_MODE_WEIGHT_PAINT:
279                                         return ePaintWeight;
280                                 case OB_MODE_TEXTURE_PAINT:
281                                         return ePaintTextureProjective;
282                                 case OB_MODE_EDIT:
283                                         if (ts->use_uv_sculpt)
284                                                 return ePaintSculptUV;
285                                         return ePaintTexture2D;
286                                 default:
287                                         return ePaintTexture2D;
288                         }
289                 }
290                 else {
291                         /* default to image paint */
292                         return ePaintTexture2D;
293                 }
294         }
295
296         return ePaintInvalid;
297 }
298
299 Brush *BKE_paint_brush(Paint *p)
300 {
301         return p ? p->brush : NULL;
302 }
303
304 void BKE_paint_brush_set(Paint *p, Brush *br)
305 {
306         if (p) {
307                 id_us_min((ID *)p->brush);
308                 id_us_plus((ID *)br);
309                 p->brush = br;
310         }
311 }
312
313 /** Free (or release) any data used by this paint curve (does not free the pcurve itself). */
314 void BKE_paint_curve_free(PaintCurve *pc)
315 {
316         MEM_SAFE_FREE(pc->points);
317         pc->tot_points = 0;
318 }
319
320 PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name)
321 {
322         PaintCurve *pc;
323
324         pc = BKE_libblock_alloc(bmain, ID_PC, name, 0);
325
326         return pc;
327 }
328
329 /**
330  * Only copy internal data of PaintCurve ID from source to already allocated/initialized destination.
331  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
332  *
333  * WARNING! This function will not handle ID user count!
334  *
335  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
336  */
337 void BKE_paint_curve_copy_data(Main *UNUSED(bmain), PaintCurve *pc_dst, const PaintCurve *pc_src, const int UNUSED(flag))
338 {
339         if (pc_src->tot_points != 0) {
340                 pc_dst->points = MEM_dupallocN(pc_src->points);
341         }
342 }
343
344 PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc)
345 {
346         PaintCurve *pc_copy;
347         BKE_id_copy_ex(bmain, &pc->id, (ID **)&pc_copy, 0, false);
348         return pc_copy;
349 }
350
351 void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local)
352 {
353         BKE_id_make_local_generic(bmain, &pc->id, true, lib_local);
354 }
355
356 Palette *BKE_paint_palette(Paint *p)
357 {
358         return p ? p->palette : NULL;
359 }
360
361 void BKE_paint_palette_set(Paint *p, Palette *palette)
362 {
363         if (p) {
364                 id_us_min((ID *)p->palette);
365                 id_us_plus((ID *)palette);
366                 p->palette = palette;
367         }
368 }
369
370 void BKE_paint_curve_set(Brush *br, PaintCurve *pc)
371 {
372         if (br) {
373                 id_us_min((ID *)br->paint_curve);
374                 id_us_plus((ID *)pc);
375                 br->paint_curve = pc;
376         }
377 }
378
379 void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_index)
380 {
381         pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0;
382 }
383
384 /* remove colour from palette. Must be certain color is inside the palette! */
385 void BKE_palette_color_remove(Palette *palette, PaletteColor *color)
386 {
387         if (BLI_listbase_count_ex(&palette->colors, palette->active_color) == palette->active_color) {
388                 palette->active_color--;
389         }
390
391         BLI_remlink(&palette->colors, color);
392
393         if (palette->active_color < 0 && !BLI_listbase_is_empty(&palette->colors)) {
394                 palette->active_color = 0;
395         }
396
397         MEM_freeN(color);
398 }
399
400 void BKE_palette_clear(Palette *palette)
401 {
402         BLI_freelistN(&palette->colors);
403         palette->active_color = 0;
404 }
405
406 Palette *BKE_palette_add(Main *bmain, const char *name)
407 {
408         Palette *palette;
409
410         palette = BKE_libblock_alloc(bmain, ID_PAL, name, 0);
411
412         /* enable fake user by default */
413         id_fake_user_set(&palette->id);
414
415         return palette;
416 }
417
418 /**
419  * Only copy internal data of Palette ID from source to already allocated/initialized destination.
420  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
421  *
422  * WARNING! This function will not handle ID user count!
423  *
424  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
425  */
426 void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag))
427 {
428         BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
429 }
430
431 Palette *BKE_palette_copy(Main *bmain, const Palette *palette)
432 {
433         Palette *palette_copy;
434         BKE_id_copy_ex(bmain, &palette->id, (ID **)&palette_copy, 0, false);
435         return palette_copy;
436 }
437
438 void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local)
439 {
440         BKE_id_make_local_generic(bmain, &palette->id, true, lib_local);
441 }
442
443 /** Free (or release) any data used by this palette (does not free the palette itself). */
444 void BKE_palette_free(Palette *palette)
445 {
446         BLI_freelistN(&palette->colors);
447 }
448
449 PaletteColor *BKE_palette_color_add(Palette *palette)
450 {
451         PaletteColor *color = MEM_callocN(sizeof(*color), "Pallete Color");
452         BLI_addtail(&palette->colors, color);
453         return color;
454 }
455
456
457 bool BKE_palette_is_empty(const struct Palette *palette)
458 {
459         return BLI_listbase_is_empty(&palette->colors);
460 }
461
462
463 /* are we in vertex paint or weight pain face select mode? */
464 bool BKE_paint_select_face_test(const EvaluationContext *eval_ctx, Object *ob)
465 {
466         return ( (ob != NULL) &&
467                  (ob->type == OB_MESH) &&
468                  (ob->data != NULL) &&
469                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) &&
470                  (eval_ctx->object_mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))
471                  );
472 }
473
474 /* are we in weight paint vertex select mode? */
475 bool BKE_paint_select_vert_test(const EvaluationContext *eval_ctx, Object *ob)
476 {
477         return ( (ob != NULL) &&
478                  (ob->type == OB_MESH) &&
479                  (ob->data != NULL) &&
480                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
481                  (eval_ctx->object_mode & OB_MODE_WEIGHT_PAINT || eval_ctx->object_mode & OB_MODE_VERTEX_PAINT)
482                  );
483 }
484
485 /**
486  * used to check if selection is possible
487  * (when we don't care if its face or vert)
488  */
489 bool BKE_paint_select_elem_test(const EvaluationContext *eval_ctx, Object *ob)
490 {
491         return (BKE_paint_select_vert_test(eval_ctx, ob) ||
492                 BKE_paint_select_face_test(eval_ctx, ob));
493 }
494
495 void BKE_paint_cavity_curve_preset(Paint *p, int preset)
496 {
497         CurveMap *cm = NULL;
498
499         if (!p->cavity_curve)
500                 p->cavity_curve = curvemapping_add(1, 0, 0, 1, 1);
501
502         cm = p->cavity_curve->cm;
503         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
504
505         p->cavity_curve->preset = preset;
506         curvemap_reset(cm, &p->cavity_curve->clipr, p->cavity_curve->preset, CURVEMAP_SLOPE_POSITIVE);
507         curvemapping_changed(p->cavity_curve, false);
508 }
509
510 short BKE_paint_object_mode_from_paint_mode(ePaintMode mode)
511 {
512         switch (mode) {
513                 case ePaintSculpt:
514                         return OB_MODE_SCULPT;
515                 case ePaintVertex:
516                         return OB_MODE_VERTEX_PAINT;
517                 case ePaintWeight:
518                         return OB_MODE_WEIGHT_PAINT;
519                 case ePaintTextureProjective:
520                         return OB_MODE_TEXTURE_PAINT;
521                 case ePaintTexture2D:
522                         return OB_MODE_TEXTURE_PAINT;
523                 case ePaintSculptUV:
524                         return OB_MODE_EDIT;
525                 case ePaintInvalid:
526                 default:
527                         return 0;
528         }
529 }
530
531 void BKE_paint_init(Scene *sce, ePaintMode mode, const char col[3])
532 {
533         UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
534         Brush *brush;
535         Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode);
536
537         /* If there's no brush, create one */
538         brush = BKE_paint_brush(paint);
539         if (brush == NULL) {
540                 short ob_mode = BKE_paint_object_mode_from_paint_mode(mode);
541                 brush = BKE_brush_first_search(G.main, ob_mode);
542
543                 if (!brush) {
544                         brush = BKE_brush_add(G.main, "Brush", ob_mode);
545                         id_us_min(&brush->id);  /* fake user only */
546                 }
547                 BKE_paint_brush_set(paint, brush);
548         }
549
550         memcpy(paint->paint_cursor_col, col, 3);
551         paint->paint_cursor_col[3] = 128;
552         ups->last_stroke_valid = false;
553         zero_v3(ups->average_stroke_accum);
554         ups->average_stroke_counter = 0;
555         if (!paint->cavity_curve)
556                 BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE);
557 }
558
559 void BKE_paint_free(Paint *paint)
560 {
561         curvemapping_free(paint->cavity_curve);
562 }
563
564 /* called when copying scene settings, so even if 'src' and 'tar' are the same
565  * still do a id_us_plus(), rather then if we were copying between 2 existing
566  * scenes where a matching value should decrease the existing user count as
567  * with paint_brush_set() */
568 void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
569 {
570         tar->brush = src->brush;
571         tar->cavity_curve = curvemapping_copy(src->cavity_curve);
572
573         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
574                 id_us_plus((ID *)tar->brush);
575                 id_us_plus((ID *)tar->palette);
576         }
577 }
578
579 void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
580 {
581         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
582         if (ups->last_stroke_valid && ups->average_stroke_counter > 0) {
583                 float fac = 1.0f / ups->average_stroke_counter;
584                 mul_v3_v3fl(stroke, ups->average_stroke_accum, fac);
585         }
586         else {
587                 copy_v3_v3(stroke, ob->obmat[3]);
588         }
589 }
590
591 /* returns non-zero if any of the face's vertices
592  * are hidden, zero otherwise */
593 bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop)
594 {
595         return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) ||
596                 (mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) ||
597                 (mvert[mloop[lt->tri[2]].v].flag & ME_HIDE));
598 }
599
600 /* returns non-zero if any of the corners of the grid
601  * face whose inner corner is at (x, y) are hidden,
602  * zero otherwise */
603 bool paint_is_grid_face_hidden(const unsigned int *grid_hidden,
604                               int gridsize, int x, int y)
605 {
606         /* skip face if any of its corners are hidden */
607         return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) ||
608                 BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) ||
609                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) ||
610                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x));
611 }
612
613 /* Return true if all vertices in the face are visible, false otherwise */
614 bool paint_is_bmesh_face_hidden(BMFace *f)
615 {
616         BMLoop *l_iter;
617         BMLoop *l_first;
618
619         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
620         do {
621                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) {
622                         return true;
623                 }
624         } while ((l_iter = l_iter->next) != l_first);
625
626         return false;
627 }
628
629 float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level,
630                             unsigned x, unsigned y)
631 {
632         int factor = BKE_ccg_factor(level, gpm->level);
633         int gridsize = BKE_ccg_gridsize(gpm->level);
634         
635         return gpm->data[(y * factor) * gridsize + (x * factor)];
636 }
637
638 /* threshold to move before updating the brush rotation */
639 #define RAKE_THRESHHOLD 20
640
641 void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation)
642 {
643         if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
644                 ups->brush_rotation = rotation;
645         else
646                 ups->brush_rotation = 0.0f;
647
648         if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
649                 ups->brush_rotation_sec = rotation;
650         else
651                 ups->brush_rotation_sec = 0.0f;
652 }
653
654 bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2])
655 {
656         bool ok = false;
657         if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
658                 const float r = RAKE_THRESHHOLD;
659                 float rotation;
660
661                 float dpos[2];
662                 sub_v2_v2v2(dpos, ups->last_rake, mouse_pos);
663
664                 if (len_squared_v2(dpos) >= r * r) {
665                         rotation = atan2f(dpos[0], dpos[1]);
666
667                         copy_v2_v2(ups->last_rake, mouse_pos);
668
669                         ups->last_rake_angle = rotation;
670
671                         paint_update_brush_rake_rotation(ups, brush, rotation);
672                         ok = true;
673                 }
674                 /* make sure we reset here to the last rotation to avoid accumulating
675                  * values in case a random rotation is also added */
676                 else {
677                         paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
678                         ok = false;
679                 }
680         }
681         else {
682                 ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
683                 ok = true;
684         }
685         return ok;
686 }
687
688 void BKE_sculptsession_free_deformMats(SculptSession *ss)
689 {
690         MEM_SAFE_FREE(ss->orig_cos);
691         MEM_SAFE_FREE(ss->deform_cos);
692         MEM_SAFE_FREE(ss->deform_imats);
693 }
694
695 void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
696 {
697         struct SculptVertexPaintGeomMap *gmap = NULL;
698         if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
699                 gmap = &ss->mode.vpaint.gmap;
700
701                 MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
702         }
703         else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
704                 gmap = &ss->mode.wpaint.gmap;
705
706                 MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
707                 if (ss->mode.wpaint.dvert_prev) {
708                         BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
709                         MEM_freeN(ss->mode.wpaint.dvert_prev);
710                         ss->mode.wpaint.dvert_prev = NULL;
711                 }
712         }
713         else {
714                 return;
715         }
716         MEM_SAFE_FREE(gmap->vert_to_loop);
717         MEM_SAFE_FREE(gmap->vert_map_mem);
718         MEM_SAFE_FREE(gmap->vert_to_poly);
719         MEM_SAFE_FREE(gmap->poly_map_mem);
720 }
721
722 /* Write out the sculpt dynamic-topology BMesh to the Mesh */
723 static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
724 {
725         SculptSession *ss = ob->sculpt;
726
727         if (ss->bm) {
728                 if (ob->data) {
729                         BMIter iter;
730                         BMFace *efa;
731                         BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
732                                 BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading);
733                         }
734                         if (reorder)
735                                 BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
736                         BM_mesh_bm_to_me(ss->bm, ob->data, (&(struct BMeshToMeshParams){0}));
737                 }
738         }
739 }
740
741 void BKE_sculptsession_bm_to_me(Object *ob, bool reorder)
742 {
743         if (ob && ob->sculpt) {
744                 sculptsession_bm_to_me_update_data_only(ob, reorder);
745
746                 /* ensure the objects DerivedMesh mesh doesn't hold onto arrays now realloc'd in the mesh [#34473] */
747                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
748         }
749 }
750
751 void BKE_sculptsession_bm_to_me_for_render(Object *object)
752 {
753         if (object && object->sculpt) {
754                 if (object->sculpt->bm) {
755                         /* Ensure no points to old arrays are stored in DM
756                          *
757                          * Apparently, we could not use DEG_id_tag_update
758                          * here because this will lead to the while object
759                          * surface to disappear, so we'll release DM in place.
760                          */
761                         BKE_object_free_derived_caches(object);
762
763                         if (object->sculpt->pbvh) {
764                                 BKE_pbvh_free(object->sculpt->pbvh);
765                                 object->sculpt->pbvh = NULL;
766                         }
767
768                         sculptsession_bm_to_me_update_data_only(object, false);
769
770                         /* In contrast with sculptsession_bm_to_me no need in
771                          * DAG tag update here - derived mesh was freed and
772                          * old pointers are nowhere stored.
773                          */
774                 }
775         }
776 }
777
778 void BKE_sculptsession_free(Object *ob)
779 {
780         if (ob && ob->sculpt) {
781                 SculptSession *ss = ob->sculpt;
782                 DerivedMesh *dm = ob->derivedFinal;
783
784                 if (ss->bm) {
785                         BKE_sculptsession_bm_to_me(ob, true);
786                         BM_mesh_free(ss->bm);
787                 }
788
789                 if (ss->pbvh)
790                         BKE_pbvh_free(ss->pbvh);
791                 if (ss->bm_log)
792                         BM_log_free(ss->bm_log);
793
794                 if (dm && dm->getPBVH)
795                         dm->getPBVH(NULL, dm);  /* signal to clear */
796
797                 if (ss->texcache)
798                         MEM_freeN(ss->texcache);
799
800                 if (ss->tex_pool)
801                         BKE_image_pool_free(ss->tex_pool);
802
803                 if (ss->layer_co)
804                         MEM_freeN(ss->layer_co);
805
806                 if (ss->orig_cos)
807                         MEM_freeN(ss->orig_cos);
808                 if (ss->deform_cos)
809                         MEM_freeN(ss->deform_cos);
810                 if (ss->deform_imats)
811                         MEM_freeN(ss->deform_imats);
812
813                 BKE_sculptsession_free_vwpaint_data(ob->sculpt);
814
815                 MEM_freeN(ss);
816
817                 ob->sculpt = NULL;
818         }
819 }
820
821 /* Sculpt mode handles multires differently from regular meshes, but only if
822  * it's the last modifier on the stack and it is not on the first level */
823 MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob)
824 {
825         Mesh *me = (Mesh *)ob->data;
826         ModifierData *md;
827         VirtualModifierData virtualModifierData;
828
829         if (ob->sculpt && ob->sculpt->bm) {
830                 /* can't combine multires and dynamic topology */
831                 return NULL;
832         }
833
834         if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
835                 /* multires can't work without displacement layer */
836                 return NULL;
837         }
838
839         for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) {
840                 if (md->type == eModifierType_Multires) {
841                         MultiresModifierData *mmd = (MultiresModifierData *)md;
842
843                         if (!modifier_isEnabled(scene, md, eModifierMode_Realtime))
844                                 continue;
845
846                         if (mmd->sculptlvl > 0) return mmd;
847                         else return NULL;
848                 }
849         }
850
851         return NULL;
852 }
853
854
855 /* Checks if there are any supported deformation modifiers active */
856 static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob)
857 {
858         ModifierData *md;
859         Mesh *me = (Mesh *)ob->data;
860         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
861         VirtualModifierData virtualModifierData;
862
863         if (mmd || ob->sculpt->bm)
864                 return false;
865
866         /* non-locked shape keys could be handled in the same way as deformed mesh */
867         if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr)
868                 return true;
869
870         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
871
872         /* exception for shape keys because we can edit those */
873         for (; md; md = md->next) {
874                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
875                 if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) continue;
876                 if (ELEM(md->type, eModifierType_ShapeKey, eModifierType_Multires)) continue;
877
878                 if (mti->type == eModifierTypeType_OnlyDeform) return true;
879                 else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) return true;
880         }
881
882         return false;
883 }
884
885 /**
886  * \param need_mask So the DerivedMesh thats returned has mask data
887  */
888 void BKE_sculpt_update_mesh_elements(
889         const EvaluationContext *eval_ctx, Scene *scene, Sculpt *sd, Object *ob,
890         bool need_pmap, bool need_mask)
891 {
892         DerivedMesh *dm;
893         SculptSession *ss = ob->sculpt;
894         Mesh *me = ob->data;
895         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
896
897         ss->modifiers_active = sculpt_modifiers_active(scene, sd, ob);
898         ss->show_diffuse_color = (sd->flags & SCULPT_SHOW_DIFFUSE) != 0;
899         ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
900
901         ss->building_vp_handle = false;
902
903         if (need_mask) {
904                 if (mmd == NULL) {
905                         if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
906                                 BKE_sculpt_mask_layers_ensure(ob, NULL);
907                         }
908                 }
909                 else {
910                         if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
911 #if 1
912                                 BKE_sculpt_mask_layers_ensure(ob, mmd);
913 #else                           /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
914                                 if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) {
915                                         /* remake the derived mesh */
916                                         ob->recalc |= OB_RECALC_DATA;
917                                         BKE_object_handle_update(scene, ob);
918                                 }
919 #endif
920                         }
921                 }
922         }
923
924         /* tessfaces aren't used and will become invalid */
925         BKE_mesh_tessface_clear(me);
926
927         ss->kb = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL;
928
929         dm = mesh_get_derived_final(eval_ctx, scene, ob, CD_MASK_BAREMESH);
930
931         /* VWPaint require mesh info for loop lookup, so require sculpt mode here */
932         if (mmd && eval_ctx->object_mode & OB_MODE_SCULPT) {
933                 ss->multires = mmd;
934                 ss->totvert = dm->getNumVerts(dm);
935                 ss->totpoly = dm->getNumPolys(dm);
936                 ss->mvert = NULL;
937                 ss->mpoly = NULL;
938                 ss->mloop = NULL;
939         }
940         else {
941                 ss->totvert = me->totvert;
942                 ss->totpoly = me->totpoly;
943                 ss->mvert = me->mvert;
944                 ss->mpoly = me->mpoly;
945                 ss->mloop = me->mloop;
946                 ss->multires = NULL;
947                 ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
948         }
949
950         ss->pbvh = dm->getPBVH(ob, dm);
951         ss->pmap = (need_pmap && dm->getPolyMap) ? dm->getPolyMap(ob, dm) : NULL;
952
953         pbvh_show_diffuse_color_set(ss->pbvh, ss->show_diffuse_color);
954         pbvh_show_mask_set(ss->pbvh, ss->show_mask);
955
956         if (ss->modifiers_active) {
957                 if (!ss->orig_cos) {
958                         int a;
959
960                         BKE_sculptsession_free_deformMats(ss);
961
962                         ss->orig_cos = (ss->kb) ? BKE_keyblock_convert_to_vertcos(ob, ss->kb) : BKE_mesh_vertexCos_get(me, NULL);
963
964                         BKE_crazyspace_build_sculpt(eval_ctx, scene, ob, &ss->deform_imats, &ss->deform_cos);
965                         BKE_pbvh_apply_vertCos(ss->pbvh, ss->deform_cos);
966
967                         for (a = 0; a < me->totvert; ++a) {
968                                 invert_m3(ss->deform_imats[a]);
969                         }
970                 }
971         }
972         else {
973                 BKE_sculptsession_free_deformMats(ss);
974         }
975
976         if (ss->kb != NULL && ss->deform_cos == NULL) {
977                 ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
978         }
979
980         /* if pbvh is deformed, key block is already applied to it */
981         if (ss->kb) {
982                 bool pbvh_deformd = BKE_pbvh_isDeformed(ss->pbvh);
983                 if (!pbvh_deformd || ss->deform_cos == NULL) {
984                         float (*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
985
986                         if (vertCos) {
987                                 if (!pbvh_deformd) {
988                                         /* apply shape keys coordinates to PBVH */
989                                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
990                                 }
991                                 if (ss->deform_cos == NULL) {
992                                         ss->deform_cos = vertCos;
993                                 }
994                                 if (vertCos != ss->deform_cos) {
995                                         MEM_freeN(vertCos);
996                                 }
997                         }
998                 }
999         }
1000
1001         /* 2.8x - avoid full mesh update! */
1002         BKE_mesh_batch_cache_dirty(me, BKE_MESH_BATCH_DIRTY_SCULPT_COORDS);
1003 }
1004
1005 int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
1006 {
1007         const float *paint_mask;
1008         Mesh *me = ob->data;
1009         int ret = 0;
1010
1011         paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
1012
1013         /* if multires is active, create a grid paint mask layer if there
1014          * isn't one already */
1015         if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
1016                 GridPaintMask *gmask;
1017                 int level = max_ii(1, mmd->sculptlvl);
1018                 int gridsize = BKE_ccg_gridsize(level);
1019                 int gridarea = gridsize * gridsize;
1020                 int i, j;
1021
1022                 gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK,
1023                                              CD_CALLOC, NULL, me->totloop);
1024
1025                 for (i = 0; i < me->totloop; i++) {
1026                         GridPaintMask *gpm = &gmask[i];
1027
1028                         gpm->level = level;
1029                         gpm->data = MEM_callocN(sizeof(float) * gridarea,
1030                                                 "GridPaintMask.data");
1031                 }
1032
1033                 /* if vertices already have mask, copy into multires data */
1034                 if (paint_mask) {
1035                         for (i = 0; i < me->totpoly; i++) {
1036                                 const MPoly *p = &me->mpoly[i];
1037                                 float avg = 0;
1038
1039                                 /* mask center */
1040                                 for (j = 0; j < p->totloop; j++) {
1041                                         const MLoop *l = &me->mloop[p->loopstart + j];
1042                                         avg += paint_mask[l->v];
1043                                 }
1044                                 avg /= (float)p->totloop;
1045
1046                                 /* fill in multires mask corner */
1047                                 for (j = 0; j < p->totloop; j++) {
1048                                         GridPaintMask *gpm = &gmask[p->loopstart + j];
1049                                         const MLoop *l = &me->mloop[p->loopstart + j];
1050                                         const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j);
1051                                         const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j);
1052
1053                                         gpm->data[0] = avg;
1054                                         gpm->data[1] = (paint_mask[l->v] +
1055                                                         paint_mask[next->v]) * 0.5f;
1056                                         gpm->data[2] = (paint_mask[l->v] +
1057                                                         paint_mask[prev->v]) * 0.5f;
1058                                         gpm->data[3] = paint_mask[l->v];
1059                                 }
1060                         }
1061                 }
1062
1063                 ret |= SCULPT_MASK_LAYER_CALC_LOOP;
1064         }
1065
1066         /* create vertex paint mask layer if there isn't one already */
1067         if (!paint_mask) {
1068                 CustomData_add_layer(&me->vdata, CD_PAINT_MASK,
1069                                      CD_CALLOC, NULL, me->totvert);
1070                 ret |= SCULPT_MASK_LAYER_CALC_VERT;
1071         }
1072
1073         return ret;
1074 }
1075
1076 void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
1077 {
1078         Sculpt *sd = scene->toolsettings->sculpt;
1079         if (sd == NULL) {
1080                 sd = scene->toolsettings->sculpt = MEM_callocN(sizeof(Sculpt), __func__);
1081
1082                 /* Turn on X plane mirror symmetry by default */
1083                 sd->paint.symmetry_flags |= PAINT_SYMM_X;
1084                 sd->paint.flags |= PAINT_SHOW_BRUSH;
1085
1086                 /* Make sure at least dyntopo subdivision is enabled */
1087                 sd->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
1088         }
1089
1090         if (!sd->detail_size) {
1091                 sd->detail_size = 12;
1092         }
1093         if (!sd->detail_percent) {
1094                 sd->detail_percent = 25;
1095         }
1096         if (sd->constant_detail == 0.0f) {
1097                 sd->constant_detail = 3.0f;
1098         }
1099
1100         /* Set sane default tiling offsets */
1101         if (!sd->paint.tile_offset[0]) {
1102                 sd->paint.tile_offset[0] = 1.0f;
1103         }
1104         if (!sd->paint.tile_offset[1]) {
1105                 sd->paint.tile_offset[1] = 1.0f;
1106         }
1107         if (!sd->paint.tile_offset[2]) {
1108                 sd->paint.tile_offset[2] = 1.0f;
1109         }
1110 }