Merge remote-tracking branch 'origin/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                 p->palette = palette;
342                 id_us_plus((ID *)p->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                 br->paint_curve = pc;
351                 id_us_plus((ID *)br->paint_curve);
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 = BKE_id_new(bmain, ID_PAL, name);
385
386         /* enable fake user by default */
387         id_fake_user_set(&palette->id);
388
389         return palette;
390 }
391
392 /**
393  * Only copy internal data of Palette ID from source to already allocated/initialized destination.
394  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
395  *
396  * WARNING! This function will not handle ID user count!
397  *
398  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
399  */
400 void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag))
401 {
402         BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
403 }
404
405 Palette *BKE_palette_copy(Main *bmain, const Palette *palette)
406 {
407         Palette *palette_copy;
408         BKE_id_copy_ex(bmain, &palette->id, (ID **)&palette_copy, 0, false);
409         return palette_copy;
410 }
411
412 void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local)
413 {
414         BKE_id_make_local_generic(bmain, &palette->id, true, lib_local);
415 }
416
417 /** Free (or release) any data used by this palette (does not free the palette itself). */
418 void BKE_palette_free(Palette *palette)
419 {
420         BLI_freelistN(&palette->colors);
421 }
422
423 PaletteColor *BKE_palette_color_add(Palette *palette)
424 {
425         PaletteColor *color = MEM_callocN(sizeof(*color), "Palette Color");
426         BLI_addtail(&palette->colors, color);
427         return color;
428 }
429
430
431 bool BKE_palette_is_empty(const struct Palette *palette)
432 {
433         return BLI_listbase_is_empty(&palette->colors);
434 }
435
436
437 /* are we in vertex paint or weight pain face select mode? */
438 bool BKE_paint_select_face_test(Object *ob)
439 {
440         return ( (ob != NULL) &&
441                  (ob->type == OB_MESH) &&
442                  (ob->data != NULL) &&
443                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) &&
444                  (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))
445                  );
446 }
447
448 /* are we in weight paint vertex select mode? */
449 bool BKE_paint_select_vert_test(Object *ob)
450 {
451         return ( (ob != NULL) &&
452                  (ob->type == OB_MESH) &&
453                  (ob->data != NULL) &&
454                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
455                  (ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT)
456                  );
457 }
458
459 /**
460  * used to check if selection is possible
461  * (when we don't care if its face or vert)
462  */
463 bool BKE_paint_select_elem_test(Object *ob)
464 {
465         return (BKE_paint_select_vert_test(ob) ||
466                 BKE_paint_select_face_test(ob));
467 }
468
469 void BKE_paint_cavity_curve_preset(Paint *p, int preset)
470 {
471         CurveMap *cm = NULL;
472
473         if (!p->cavity_curve)
474                 p->cavity_curve = curvemapping_add(1, 0, 0, 1, 1);
475
476         cm = p->cavity_curve->cm;
477         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
478
479         p->cavity_curve->preset = preset;
480         curvemap_reset(cm, &p->cavity_curve->clipr, p->cavity_curve->preset, CURVEMAP_SLOPE_POSITIVE);
481         curvemapping_changed(p->cavity_curve, false);
482 }
483
484 eObjectMode BKE_paint_object_mode_from_paint_mode(ePaintMode mode)
485 {
486         switch (mode) {
487                 case ePaintSculpt:
488                         return OB_MODE_SCULPT;
489                 case ePaintVertex:
490                         return OB_MODE_VERTEX_PAINT;
491                 case ePaintWeight:
492                         return OB_MODE_WEIGHT_PAINT;
493                 case ePaintTextureProjective:
494                         return OB_MODE_TEXTURE_PAINT;
495                 case ePaintTexture2D:
496                         return OB_MODE_TEXTURE_PAINT;
497                 case ePaintSculptUV:
498                         return OB_MODE_EDIT;
499                 case ePaintInvalid:
500                 default:
501                         return 0;
502         }
503 }
504
505 void BKE_paint_init(Scene *sce, ePaintMode mode, const char col[3])
506 {
507         UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
508         Brush *brush;
509         Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode);
510
511         /* If there's no brush, create one */
512         brush = BKE_paint_brush(paint);
513         if (brush == NULL) {
514                 eObjectMode ob_mode = BKE_paint_object_mode_from_paint_mode(mode);
515                 brush = BKE_brush_first_search(G.main, ob_mode);
516
517                 if (!brush) {
518                         brush = BKE_brush_add(G.main, "Brush", ob_mode);
519                         id_us_min(&brush->id);  /* fake user only */
520                 }
521                 BKE_paint_brush_set(paint, brush);
522         }
523
524         memcpy(paint->paint_cursor_col, col, 3);
525         paint->paint_cursor_col[3] = 128;
526         ups->last_stroke_valid = false;
527         zero_v3(ups->average_stroke_accum);
528         ups->average_stroke_counter = 0;
529         if (!paint->cavity_curve)
530                 BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE);
531 }
532
533 void BKE_paint_free(Paint *paint)
534 {
535         curvemapping_free(paint->cavity_curve);
536 }
537
538 /* called when copying scene settings, so even if 'src' and 'tar' are the same
539  * still do a id_us_plus(), rather then if we were copying between 2 existing
540  * scenes where a matching value should decrease the existing user count as
541  * with paint_brush_set() */
542 void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
543 {
544         tar->brush = src->brush;
545         tar->cavity_curve = curvemapping_copy(src->cavity_curve);
546
547         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
548                 id_us_plus((ID *)tar->brush);
549                 id_us_plus((ID *)tar->palette);
550         }
551 }
552
553 void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
554 {
555         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
556         if (ups->last_stroke_valid && ups->average_stroke_counter > 0) {
557                 float fac = 1.0f / ups->average_stroke_counter;
558                 mul_v3_v3fl(stroke, ups->average_stroke_accum, fac);
559         }
560         else {
561                 copy_v3_v3(stroke, ob->obmat[3]);
562         }
563 }
564
565 /* returns non-zero if any of the face's vertices
566  * are hidden, zero otherwise */
567 bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop)
568 {
569         return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) ||
570                 (mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) ||
571                 (mvert[mloop[lt->tri[2]].v].flag & ME_HIDE));
572 }
573
574 /* returns non-zero if any of the corners of the grid
575  * face whose inner corner is at (x, y) are hidden,
576  * zero otherwise */
577 bool paint_is_grid_face_hidden(const unsigned int *grid_hidden,
578                               int gridsize, int x, int y)
579 {
580         /* skip face if any of its corners are hidden */
581         return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) ||
582                 BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) ||
583                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) ||
584                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x));
585 }
586
587 /* Return true if all vertices in the face are visible, false otherwise */
588 bool paint_is_bmesh_face_hidden(BMFace *f)
589 {
590         BMLoop *l_iter;
591         BMLoop *l_first;
592
593         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
594         do {
595                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) {
596                         return true;
597                 }
598         } while ((l_iter = l_iter->next) != l_first);
599
600         return false;
601 }
602
603 float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level,
604                             unsigned x, unsigned y)
605 {
606         int factor = BKE_ccg_factor(level, gpm->level);
607         int gridsize = BKE_ccg_gridsize(gpm->level);
608         
609         return gpm->data[(y * factor) * gridsize + (x * factor)];
610 }
611
612 /* threshold to move before updating the brush rotation */
613 #define RAKE_THRESHHOLD 20
614
615 void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation)
616 {
617         if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
618                 ups->brush_rotation = rotation;
619         else
620                 ups->brush_rotation = 0.0f;
621
622         if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
623                 ups->brush_rotation_sec = rotation;
624         else
625                 ups->brush_rotation_sec = 0.0f;
626 }
627
628 bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2])
629 {
630         bool ok = false;
631         if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
632                 const float r = RAKE_THRESHHOLD;
633                 float rotation;
634
635                 float dpos[2];
636                 sub_v2_v2v2(dpos, ups->last_rake, mouse_pos);
637
638                 if (len_squared_v2(dpos) >= r * r) {
639                         rotation = atan2f(dpos[0], dpos[1]);
640
641                         copy_v2_v2(ups->last_rake, mouse_pos);
642
643                         ups->last_rake_angle = rotation;
644
645                         paint_update_brush_rake_rotation(ups, brush, rotation);
646                         ok = true;
647                 }
648                 /* make sure we reset here to the last rotation to avoid accumulating
649                  * values in case a random rotation is also added */
650                 else {
651                         paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
652                         ok = false;
653                 }
654         }
655         else {
656                 ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
657                 ok = true;
658         }
659         return ok;
660 }
661
662 void BKE_sculptsession_free_deformMats(SculptSession *ss)
663 {
664         MEM_SAFE_FREE(ss->orig_cos);
665         MEM_SAFE_FREE(ss->deform_cos);
666         MEM_SAFE_FREE(ss->deform_imats);
667 }
668
669 void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
670 {
671         struct SculptVertexPaintGeomMap *gmap = NULL;
672         if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
673                 gmap = &ss->mode.vpaint.gmap;
674
675                 MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
676         }
677         else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
678                 gmap = &ss->mode.wpaint.gmap;
679
680                 MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
681                 if (ss->mode.wpaint.dvert_prev) {
682                         BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
683                         MEM_freeN(ss->mode.wpaint.dvert_prev);
684                         ss->mode.wpaint.dvert_prev = NULL;
685                 }
686         }
687         else {
688                 return;
689         }
690         MEM_SAFE_FREE(gmap->vert_to_loop);
691         MEM_SAFE_FREE(gmap->vert_map_mem);
692         MEM_SAFE_FREE(gmap->vert_to_poly);
693         MEM_SAFE_FREE(gmap->poly_map_mem);
694 }
695
696 /* Write out the sculpt dynamic-topology BMesh to the Mesh */
697 static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
698 {
699         SculptSession *ss = ob->sculpt;
700
701         if (ss->bm) {
702                 if (ob->data) {
703                         BMIter iter;
704                         BMFace *efa;
705                         BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
706                                 BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading);
707                         }
708                         if (reorder)
709                                 BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
710                         BM_mesh_bm_to_me(ss->bm, ob->data, (&(struct BMeshToMeshParams){0}));
711                 }
712         }
713 }
714
715 void BKE_sculptsession_bm_to_me(Object *ob, bool reorder)
716 {
717         if (ob && ob->sculpt) {
718                 sculptsession_bm_to_me_update_data_only(ob, reorder);
719
720                 /* ensure the objects DerivedMesh mesh doesn't hold onto arrays now realloc'd in the mesh [#34473] */
721                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
722         }
723 }
724
725 void BKE_sculptsession_bm_to_me_for_render(Object *object)
726 {
727         if (object && object->sculpt) {
728                 if (object->sculpt->bm) {
729                         /* Ensure no points to old arrays are stored in DM
730                          *
731                          * Apparently, we could not use DEG_id_tag_update
732                          * here because this will lead to the while object
733                          * surface to disappear, so we'll release DM in place.
734                          */
735                         BKE_object_free_derived_caches(object);
736
737                         if (object->sculpt->pbvh) {
738                                 BKE_pbvh_free(object->sculpt->pbvh);
739                                 object->sculpt->pbvh = NULL;
740                         }
741
742                         sculptsession_bm_to_me_update_data_only(object, false);
743
744                         /* In contrast with sculptsession_bm_to_me no need in
745                          * DAG tag update here - derived mesh was freed and
746                          * old pointers are nowhere stored.
747                          */
748                 }
749         }
750 }
751
752 void BKE_sculptsession_free(Object *ob)
753 {
754         if (ob && ob->sculpt) {
755                 SculptSession *ss = ob->sculpt;
756                 DerivedMesh *dm = ob->derivedFinal;
757
758                 if (ss->bm) {
759                         BKE_sculptsession_bm_to_me(ob, true);
760                         BM_mesh_free(ss->bm);
761                 }
762
763                 if (ss->pbvh)
764                         BKE_pbvh_free(ss->pbvh);
765                 if (ss->bm_log)
766                         BM_log_free(ss->bm_log);
767
768                 if (dm && dm->getPBVH)
769                         dm->getPBVH(NULL, dm);  /* signal to clear */
770
771                 if (ss->texcache)
772                         MEM_freeN(ss->texcache);
773
774                 if (ss->tex_pool)
775                         BKE_image_pool_free(ss->tex_pool);
776
777                 if (ss->layer_co)
778                         MEM_freeN(ss->layer_co);
779
780                 if (ss->orig_cos)
781                         MEM_freeN(ss->orig_cos);
782                 if (ss->deform_cos)
783                         MEM_freeN(ss->deform_cos);
784                 if (ss->deform_imats)
785                         MEM_freeN(ss->deform_imats);
786
787                 BKE_sculptsession_free_vwpaint_data(ob->sculpt);
788
789                 MEM_freeN(ss);
790
791                 ob->sculpt = NULL;
792         }
793 }
794
795 /* Sculpt mode handles multires differently from regular meshes, but only if
796  * it's the last modifier on the stack and it is not on the first level */
797 MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob)
798 {
799         Mesh *me = (Mesh *)ob->data;
800         ModifierData *md;
801         VirtualModifierData virtualModifierData;
802
803         if (ob->sculpt && ob->sculpt->bm) {
804                 /* can't combine multires and dynamic topology */
805                 return NULL;
806         }
807
808         if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
809                 /* multires can't work without displacement layer */
810                 return NULL;
811         }
812
813         for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) {
814                 if (md->type == eModifierType_Multires) {
815                         MultiresModifierData *mmd = (MultiresModifierData *)md;
816
817                         if (!modifier_isEnabled(scene, md, eModifierMode_Realtime))
818                                 continue;
819
820                         if (mmd->sculptlvl > 0) return mmd;
821                         else return NULL;
822                 }
823         }
824
825         return NULL;
826 }
827
828
829 /* Checks if there are any supported deformation modifiers active */
830 static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob)
831 {
832         ModifierData *md;
833         Mesh *me = (Mesh *)ob->data;
834         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
835         VirtualModifierData virtualModifierData;
836
837         if (mmd || ob->sculpt->bm)
838                 return false;
839
840         /* non-locked shape keys could be handled in the same way as deformed mesh */
841         if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr)
842                 return true;
843
844         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
845
846         /* exception for shape keys because we can edit those */
847         for (; md; md = md->next) {
848                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
849                 if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) continue;
850                 if (ELEM(md->type, eModifierType_ShapeKey, eModifierType_Multires)) continue;
851
852                 if (mti->type == eModifierTypeType_OnlyDeform) return true;
853                 else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) return true;
854         }
855
856         return false;
857 }
858
859 /**
860  * \param need_mask So the DerivedMesh thats returned has mask data
861  */
862 void BKE_sculpt_update_mesh_elements(
863         Depsgraph *depsgraph, Scene *scene, Sculpt *sd, Object *ob,
864         bool need_pmap, bool need_mask)
865 {
866         if (depsgraph == NULL) {
867                 /* Happens on file load.
868                  *
869                  * We do nothing in this case, it will be taken care about on depsgraph
870                  * evaluation.
871                  */
872                 return;
873         }
874
875         DerivedMesh *dm;
876         SculptSession *ss = ob->sculpt;
877         Mesh *me = ob->data;
878         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
879
880         ss->modifiers_active = sculpt_modifiers_active(scene, sd, ob);
881         ss->show_diffuse_color = (sd->flags & SCULPT_SHOW_DIFFUSE) != 0;
882         ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
883
884         ss->building_vp_handle = false;
885
886         if (need_mask) {
887                 if (mmd == NULL) {
888                         if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
889                                 BKE_sculpt_mask_layers_ensure(ob, NULL);
890                         }
891                 }
892                 else {
893                         if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
894 #if 1
895                                 BKE_sculpt_mask_layers_ensure(ob, mmd);
896 #else                   /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
897                                 if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) {
898                                         /* remake the derived mesh */
899                                         ob->recalc |= OB_RECALC_DATA;
900                                         BKE_object_handle_update(scene, ob);
901                                 }
902 #endif
903                         }
904                 }
905         }
906
907         /* tessfaces aren't used and will become invalid */
908         BKE_mesh_tessface_clear(me);
909
910         ss->kb = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL;
911
912         dm = mesh_get_derived_final(depsgraph, scene, ob, CD_MASK_BAREMESH);
913
914         /* VWPaint require mesh info for loop lookup, so require sculpt mode here */
915         if (mmd && ob->mode & OB_MODE_SCULPT) {
916                 ss->multires = mmd;
917                 ss->totvert = dm->getNumVerts(dm);
918                 ss->totpoly = dm->getNumPolys(dm);
919                 ss->mvert = NULL;
920                 ss->mpoly = NULL;
921                 ss->mloop = NULL;
922         }
923         else {
924                 ss->totvert = me->totvert;
925                 ss->totpoly = me->totpoly;
926                 ss->mvert = me->mvert;
927                 ss->mpoly = me->mpoly;
928                 ss->mloop = me->mloop;
929                 ss->multires = NULL;
930                 ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
931         }
932
933         ss->pbvh = dm->getPBVH(ob, dm);
934         ss->pmap = (need_pmap && dm->getPolyMap) ? dm->getPolyMap(ob, dm) : NULL;
935
936         pbvh_show_diffuse_color_set(ss->pbvh, ss->show_diffuse_color);
937         pbvh_show_mask_set(ss->pbvh, ss->show_mask);
938
939         if (ss->modifiers_active) {
940                 if (!ss->orig_cos) {
941                         int a;
942
943                         BKE_sculptsession_free_deformMats(ss);
944
945                         ss->orig_cos = (ss->kb) ? BKE_keyblock_convert_to_vertcos(ob, ss->kb) : BKE_mesh_vertexCos_get(me, NULL);
946
947                         BKE_crazyspace_build_sculpt(depsgraph, scene, ob, &ss->deform_imats, &ss->deform_cos);
948                         BKE_pbvh_apply_vertCos(ss->pbvh, ss->deform_cos);
949
950                         for (a = 0; a < me->totvert; ++a) {
951                                 invert_m3(ss->deform_imats[a]);
952                         }
953                 }
954         }
955         else {
956                 BKE_sculptsession_free_deformMats(ss);
957         }
958
959         if (ss->kb != NULL && ss->deform_cos == NULL) {
960                 ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
961         }
962
963         /* if pbvh is deformed, key block is already applied to it */
964         if (ss->kb) {
965                 bool pbvh_deformd = BKE_pbvh_isDeformed(ss->pbvh);
966                 if (!pbvh_deformd || ss->deform_cos == NULL) {
967                         float (*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
968
969                         if (vertCos) {
970                                 if (!pbvh_deformd) {
971                                         /* apply shape keys coordinates to PBVH */
972                                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
973                                 }
974                                 if (ss->deform_cos == NULL) {
975                                         ss->deform_cos = vertCos;
976                                 }
977                                 if (vertCos != ss->deform_cos) {
978                                         MEM_freeN(vertCos);
979                                 }
980                         }
981                 }
982         }
983
984         /* 2.8x - avoid full mesh update! */
985         BKE_mesh_batch_cache_dirty(me, BKE_MESH_BATCH_DIRTY_SCULPT_COORDS);
986 }
987
988 int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
989 {
990         const float *paint_mask;
991         Mesh *me = ob->data;
992         int ret = 0;
993
994         paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
995
996         /* if multires is active, create a grid paint mask layer if there
997          * isn't one already */
998         if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
999                 GridPaintMask *gmask;
1000                 int level = max_ii(1, mmd->sculptlvl);
1001                 int gridsize = BKE_ccg_gridsize(level);
1002                 int gridarea = gridsize * gridsize;
1003                 int i, j;
1004
1005                 gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK,
1006                                              CD_CALLOC, NULL, me->totloop);
1007
1008                 for (i = 0; i < me->totloop; i++) {
1009                         GridPaintMask *gpm = &gmask[i];
1010
1011                         gpm->level = level;
1012                         gpm->data = MEM_callocN(sizeof(float) * gridarea,
1013                                                 "GridPaintMask.data");
1014                 }
1015
1016                 /* if vertices already have mask, copy into multires data */
1017                 if (paint_mask) {
1018                         for (i = 0; i < me->totpoly; i++) {
1019                                 const MPoly *p = &me->mpoly[i];
1020                                 float avg = 0;
1021
1022                                 /* mask center */
1023                                 for (j = 0; j < p->totloop; j++) {
1024                                         const MLoop *l = &me->mloop[p->loopstart + j];
1025                                         avg += paint_mask[l->v];
1026                                 }
1027                                 avg /= (float)p->totloop;
1028
1029                                 /* fill in multires mask corner */
1030                                 for (j = 0; j < p->totloop; j++) {
1031                                         GridPaintMask *gpm = &gmask[p->loopstart + j];
1032                                         const MLoop *l = &me->mloop[p->loopstart + j];
1033                                         const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j);
1034                                         const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j);
1035
1036                                         gpm->data[0] = avg;
1037                                         gpm->data[1] = (paint_mask[l->v] +
1038                                                         paint_mask[next->v]) * 0.5f;
1039                                         gpm->data[2] = (paint_mask[l->v] +
1040                                                         paint_mask[prev->v]) * 0.5f;
1041                                         gpm->data[3] = paint_mask[l->v];
1042                                 }
1043                         }
1044                 }
1045
1046                 ret |= SCULPT_MASK_LAYER_CALC_LOOP;
1047         }
1048
1049         /* create vertex paint mask layer if there isn't one already */
1050         if (!paint_mask) {
1051                 CustomData_add_layer(&me->vdata, CD_PAINT_MASK,
1052                                      CD_CALLOC, NULL, me->totvert);
1053                 ret |= SCULPT_MASK_LAYER_CALC_VERT;
1054         }
1055
1056         return ret;
1057 }
1058
1059 void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
1060 {
1061         Sculpt *sd = scene->toolsettings->sculpt;
1062         if (sd == NULL) {
1063                 sd = scene->toolsettings->sculpt = MEM_callocN(sizeof(Sculpt), __func__);
1064
1065                 /* Turn on X plane mirror symmetry by default */
1066                 sd->paint.symmetry_flags |= PAINT_SYMM_X;
1067                 sd->paint.flags |= PAINT_SHOW_BRUSH;
1068
1069                 /* Make sure at least dyntopo subdivision is enabled */
1070                 sd->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
1071         }
1072
1073         if (!sd->detail_size) {
1074                 sd->detail_size = 12;
1075         }
1076         if (!sd->detail_percent) {
1077                 sd->detail_percent = 25;
1078         }
1079         if (sd->constant_detail == 0.0f) {
1080                 sd->constant_detail = 3.0f;
1081         }
1082
1083         /* Set sane default tiling offsets */
1084         if (!sd->paint.tile_offset[0]) {
1085                 sd->paint.tile_offset[0] = 1.0f;
1086         }
1087         if (!sd->paint.tile_offset[1]) {
1088                 sd->paint.tile_offset[1] = 1.0f;
1089         }
1090         if (!sd->paint.tile_offset[2]) {
1091                 sd->paint.tile_offset[2] = 1.0f;
1092         }
1093 }