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