Blender V5.3
sculpt.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2006 by Nicholas Bishop. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
9
10#include <cmath>
11#include <cstdlib>
12#include <cstring>
13
14#include "MEM_guardedalloc.h"
15
16#include "CLG_log.h"
17
18#include "BLI_array_utils.hh"
20#include "BLI_dial_2d.hh"
21#include "BLI_enum_flags.hh"
23#include "BLI_listbase.hh"
25#include "BLI_math_geom_c.hh"
26#include "BLI_math_matrix.hh"
27#include "BLI_math_matrix_c.hh"
30#include "BLI_math_vector.hh"
31#include "BLI_rect.hh"
32#include "BLI_set.hh"
33#include "BLI_span.hh"
34#include "BLI_task.hh"
35#include "BLI_task_c.hh"
36#include "BLI_vector.hh"
37
38#include "DNA_brush_types.h"
40#include "DNA_key_types.h"
41#include "DNA_node_types.h"
42#include "DNA_object_types.h"
43#include "DNA_scene_types.h"
44
45#include "BKE_attribute.hh"
46#include "BKE_brush.hh"
47#include "BKE_bvhutils.hh"
48#include "BKE_ccg.hh"
49#include "BKE_colortools.hh"
50#include "BKE_context.hh"
51#include "BKE_customdata.hh"
52#include "BKE_global.hh"
53#include "BKE_image.hh"
54#include "BKE_key.hh"
55#include "BKE_layer.hh"
56#include "BKE_lib_id.hh"
57#include "BKE_mesh.hh"
58#include "BKE_modifier.hh"
59#include "BKE_multires.hh"
60#include "BKE_node_runtime.hh"
61#include "BKE_object.hh"
62#include "BKE_object_types.hh"
63#include "BKE_paint.hh"
64#include "BKE_paint_bvh.hh"
65#include "BKE_paint_types.hh"
66#include "BKE_report.hh"
67#include "BKE_subdiv_ccg.hh"
68
69#include "BLT_translation.hh"
70
71#include "NOD_texture.h"
72
73#include "PRF_profile.hh"
74
75#include "DEG_depsgraph.hh"
77
78#include "WM_api.hh"
79#include "WM_toolsystem.hh"
80#include "WM_types.hh"
81
82#include "ED_paint.hh"
83#include "ED_screen.hh"
84#include "ED_sculpt.hh"
85#include "ED_view3d.hh"
86
87#include "../paint_intern.hh"
88#include "sculpt_automask.hh"
89#include "sculpt_boundary.hh"
90#include "sculpt_cloth.hh"
91#include "sculpt_color.hh"
92#include "sculpt_dyntopo.hh"
93#include "sculpt_face_set.hh"
94#include "sculpt_filter.hh"
95#include "sculpt_hide.hh"
96#include "sculpt_intern.hh"
97#include "sculpt_islands.hh"
98#include "sculpt_pose.hh"
99#include "sculpt_undo.hh"
100
101#include "RNA_access.hh"
102#include "RNA_define.hh"
103
104#include "bmesh.hh"
105
107#include "mesh_brush_common.hh"
108#include "mesh_paint.hh"
109
110namespace blender {
111
112static CLG_LogRef LOG = {"sculpt"};
113
114namespace ed::sculpt_paint {
115
116/* -------------------------------------------------------------------- */
119
120/* TODO: This should be moved to either BKE_paint.hh or BKE_brush.hh */
122 const Paint &paint,
123 const Brush &brush,
124 const float3 &location,
125 const float scale_factor)
126{
129 vc, location, BKE_brush_radius_get(&paint, &brush) * scale_factor);
130 }
131 return BKE_brush_unprojected_radius_get(&paint, &brush) * scale_factor;
132}
133
134bool shape_key_check(const Object &ob, ReportList *reports)
135{
137
139 if (reports) {
140 BKE_reportf(reports, RPT_ERROR, "The active shape key of %s is locked", ob.id.name + 2);
141 }
142 return false;
143 }
144 if (ss.shapekey_active && (ss.shapekey_active->flag & KEYBLOCK_MUTE) != 0) {
145 if (reports) {
146 BKE_reportf(reports, RPT_ERROR, "The active shape key of %s is muted", ob.id.name + 2);
147 }
148 return false;
149 }
150
151 return true;
152}
153
155{
156 SculptSession &ss = *object.runtime->sculpt_session;
157 if (bke::object::pbvh_get(object)->type() == bke::pbvh::Type::BMesh) {
160 }
161}
162
163int vertex_count_get(const Object &object)
164{
165 const SculptSession &ss = *object.runtime->sculpt_session;
166 switch (bke::object::pbvh_get(object)->type()) {
168 BLI_assert(object.type == OB_MESH);
169 return id_cast<const Mesh *>(object.data)->verts_num;
171 return BM_mesh_elem_count(ss.bm, BM_VERT);
173 return BKE_sculpt_get_grid_num_verts(object);
174 }
175
176 return 0;
177}
178
179Span<float3> vert_positions_for_grab_active_get(const Depsgraph &depsgraph, const Object &object)
180{
181 const SculptSession &ss = *object.runtime->sculpt_session;
183 if (ss.shapekey_active) {
184 /* Always grab active shape key if the sculpt happens on shapekey. */
185 return bke::pbvh::vert_positions_eval(depsgraph, object);
186 }
187 /* Otherwise use the base mesh positions. */
188 const Mesh &mesh = *id_cast<const Mesh *>(object.data);
189 return mesh.vert_positions();
190}
191
193{
194 const Mesh *mesh = id_cast<const Mesh *>(object.data);
195 return ePaintSymmetryFlags(mesh->symmetry & ME_SYMMETRY_XYZ);
196}
197
198/* Sculpt Face Sets and Visibility. */
199
200namespace face_set {
201
202int active_face_set_get(const Object &object)
203{
204 const SculptSession &ss = *object.runtime->sculpt_session;
205 switch (bke::object::pbvh_get(object)->type()) {
207 const Mesh &mesh = *id_cast<const Mesh *>(object.data);
208 const bke::AttributeAccessor attributes = mesh.attributes();
209 const VArray face_sets = *attributes.lookup<int>(".sculpt_face_set", bke::AttrDomain::Face);
210 if (!face_sets || !ss.active_face_index) {
211 return face_set_none_id;
212 }
213 return face_sets[*ss.active_face_index];
214 }
216 const Mesh &mesh = *id_cast<const Mesh *>(object.data);
217 const bke::AttributeAccessor attributes = mesh.attributes();
218 const VArray face_sets = *attributes.lookup<int>(".sculpt_face_set", bke::AttrDomain::Face);
219 if (!face_sets || !ss.active_grid_index) {
220 return face_set_none_id;
221 }
222 const int face_index = BKE_subdiv_ccg_grid_to_face_index(*ss.subdiv_ccg,
224 return face_sets[face_index];
225 }
227 return face_set_none_id;
228 }
229 return face_set_none_id;
230}
231
232int vert_face_set_max_get(const GroupedSpan<int> vert_to_face_map,
233 const Span<int> face_sets,
234 const int vert)
235{
236 int face_set = face_set_none_id;
237 for (const int face : vert_to_face_map[vert]) {
238 face_set = std::max(face_sets[face], face_set);
239 }
240 return face_set;
241}
242
243int vert_face_set_get(const SubdivCCG &subdiv_ccg, const Span<int> face_sets, const int grid)
244{
245 const int face = BKE_subdiv_ccg_grid_to_face_index(subdiv_ccg, grid);
246 return face_sets[face];
247}
248
249int vert_face_set_max_get(const int /*face_set_offset*/, const BMVert & /*vert*/)
250{
251 return face_set_none_id;
252}
253
255 const Span<int> face_sets,
256 const int vert)
257{
259 for (const int face : vert_to_face_map[vert]) {
260 result.add(face_sets[face]);
261 }
262 if (result.is_empty()) {
263 result.add(face_set_none_id);
264 }
265 return result;
266}
267
268bool vert_has_face_set(const GroupedSpan<int> vert_to_face_map,
269 const Span<int> face_sets,
270 const int vert,
271 const int face_set)
272{
273 if (face_sets.is_empty()) {
274 return face_set == face_set_none_id;
275 }
276 const Span<int> faces = vert_to_face_map[vert];
277 return std::any_of(
278 faces.begin(), faces.end(), [&](const int face) { return face_sets[face] == face_set; });
279}
280
281bool vert_has_face_set(const SubdivCCG &subdiv_ccg,
282 const Span<int> face_sets,
283 const int grid,
284 const int face_set)
285{
286 if (face_sets.is_empty()) {
287 return face_set == face_set_none_id;
288 }
289 const int face = BKE_subdiv_ccg_grid_to_face_index(subdiv_ccg, grid);
290 return face_sets[face] == face_set;
291}
292
293bool vert_has_face_set(const int face_set_offset, const BMVert &vert, const int face_set)
294{
295 if (face_set_offset == -1) {
296 return face_set == face_set_none_id;
297 }
298 BMIter iter;
299 BMFace *face;
300 BM_ITER_ELEM (face, &iter, &const_cast<BMVert &>(vert), BM_FACES_OF_VERT) {
301 if (BM_ELEM_CD_GET_INT(face, face_set_offset) == face_set) {
302 return true;
303 }
304 }
305 return false;
306}
307
308bool vert_has_any_face_set(const GroupedSpan<int> vert_to_face_map,
309 const Span<int> face_sets,
310 int vert,
311 const Set<int> &allowed_face_sets)
312{
313 if (face_sets.is_empty()) {
314 return allowed_face_sets.contains(face_set_none_id);
315 }
316 for (const int face : vert_to_face_map[vert]) {
317 if (allowed_face_sets.contains(face_sets[face])) {
318 return true;
319 }
320 }
321 return false;
322}
323
324bool vert_has_unique_face_set(const GroupedSpan<int> vert_to_face_map,
325 const Span<int> face_sets,
326 int vert)
327{
328 /* TODO: Move this check higher out of this function. */
329 if (face_sets.is_empty()) {
330 return true;
331 }
332 int face_set = -1;
333 for (const int face_index : vert_to_face_map[vert]) {
334 if (face_set == -1) {
335 face_set = face_sets[face_index];
336 }
337 else {
338 if (face_sets[face_index] != face_set) {
339 return false;
340 }
341 }
342 }
343 return true;
344}
345
351 const GroupedSpan<int> vert_to_face_map,
352 const Span<int> face_sets,
353 const Span<int> corner_verts,
354 const OffsetIndices<int> faces,
355 int v1,
356 int v2)
357{
358 const Span<int> vert_map = vert_to_face_map[v1];
359 int p1 = -1, p2 = -1;
360 for (int i = 0; i < vert_map.size(); i++) {
361 const int face_i = vert_map[i];
362 for (const int corner : faces[face_i]) {
363 if (corner_verts[corner] == v2) {
364 if (p1 == -1) {
365 p1 = vert_map[i];
366 break;
367 }
368
369 if (p2 == -1) {
370 p2 = vert_map[i];
371 break;
372 }
373 }
374 }
375 }
376
377 if (p1 != -1 && p2 != -1) {
378 return face_sets[p1] == face_sets[p2];
379 }
380 return true;
381}
382
384 const Span<int> corner_verts,
385 const GroupedSpan<int> vert_to_face_map,
386 const Span<int> face_sets,
387 const SubdivCCG &subdiv_ccg,
388 SubdivCCGCoord coord)
389{
390 /* TODO: Move this check higher out of this function. */
391 if (face_sets.is_empty()) {
392 return true;
393 }
394 int v1, v2;
396 subdiv_ccg, coord, corner_verts, faces, v1, v2);
397 switch (adjacency) {
399 return vert_has_unique_face_set(vert_to_face_map, face_sets, v1);
402 vert_to_face_map, face_sets, corner_verts, faces, v1, v2);
404 return true;
405 }
407 return true;
408}
409
411 const Span<int> corner_verts,
412 const GroupedSpan<int> vert_to_face_map,
413 const Span<int> face_sets,
414 const SubdivCCG &subdiv_ccg,
415 const SubdivCCGCoord coord,
416 const int face_set)
417{
418 if (face_sets.is_empty()) {
419 return face_set == face_set_none_id;
420 }
421
422 if (face_set == face_set_none_id) {
423 return false;
424 }
425
426 Set<int> allowed_face_sets;
427 allowed_face_sets.add(face_set);
429 faces, corner_verts, vert_to_face_map, face_sets, subdiv_ccg, coord, allowed_face_sets);
430}
431
433 const Span<int> corner_verts,
434 const GroupedSpan<int> vert_to_face_map,
435 const Span<int> face_sets,
436 const SubdivCCG &subdiv_ccg,
437 const SubdivCCGCoord coord,
438 const Set<int> &allowed_face_sets)
439{
440 if (face_sets.is_empty()) {
441 return allowed_face_sets.contains(face_set_none_id);
442 }
443
444 if (allowed_face_sets.is_empty()) {
445 return false;
446 }
447
448 int v1, v2;
450 subdiv_ccg, coord, corner_verts, faces, v1, v2);
451 switch (adjacency) {
453 for (const int face : vert_to_face_map[v1]) {
454 if (allowed_face_sets.contains(face_sets[face])) {
455 return true;
456 }
457 }
458 return false;
459 }
461 for (const int face : vert_to_face_map[v1]) {
462 const Span<int> face_verts = corner_verts.slice(faces[face]);
463 if (!face_verts.contains(v2)) {
464 continue;
465 }
466 if (allowed_face_sets.contains(face_sets[face])) {
467 return true;
468 }
469 }
470 return false;
472 const int face = BKE_subdiv_ccg_grid_to_face_index(subdiv_ccg, coord.grid_index);
473 return allowed_face_sets.contains(face_sets[face]);
474 }
475 }
476
478 return false;
479}
480
481bool vert_has_unique_face_set(const int /*face_set_offset*/, const BMVert & /*vert*/)
482{
483 /* TODO: Obviously not fully implemented yet. Needs to be implemented for Relax Face Sets brush
484 * to work. */
485 return true;
486}
487
488} // namespace face_set
489
491{
492 r_neighbors.clear();
493 BMIter liter;
494 BMLoop *l;
495 BM_ITER_ELEM (l, &liter, &vert, BM_LOOPS_OF_VERT) {
496 for (BMVert *other_vert : {l->prev->v, l->next->v}) {
497 if (other_vert != &vert) {
498 r_neighbors.append(other_vert);
499 }
500 }
501 }
502 return r_neighbors;
503}
504
506{
507 r_neighbors.clear();
508 BMIter liter;
509 BMLoop *l;
510 BM_ITER_ELEM (l, &liter, &vert, BM_LOOPS_OF_VERT) {
511 for (BMVert *other_vert : {l->prev->v, l->next->v}) {
512 if (other_vert != &vert) {
513 r_neighbors.append(other_vert);
514 }
515 }
516 }
517
518 if (BM_vert_is_boundary(&vert)) {
519 if (r_neighbors.size() == 2) {
520 /* Do not include neighbors of corner vertices. */
521 r_neighbors.clear();
522 }
523 else {
524 /* Only include other boundary vertices as neighbors of boundary vertices. */
525 r_neighbors.remove_if([&](const BMVert *neighbor) {
526 return !BM_edge_is_boundary(BM_edge_exists(&vert, const_cast<BMVert *>(neighbor)));
527 });
528 }
529 }
530
531 return r_neighbors;
532}
533
535 const Span<int> corner_verts,
536 const GroupedSpan<int> vert_to_face,
537 const Span<bool> hide_poly,
538 const int vert,
539 Vector<int> &r_neighbors)
540{
541 r_neighbors.clear();
542
543 for (const int face : vert_to_face[vert]) {
544 if (!hide_poly.is_empty() && hide_poly[face]) {
545 continue;
546 }
547 const int2 verts = bke::mesh::face_find_adjacent_verts(faces[face], corner_verts, vert);
548 r_neighbors.append_non_duplicates(verts[0]);
549 r_neighbors.append_non_duplicates(verts[1]);
550 }
551
552 return r_neighbors.as_span();
553}
554
556 const Span<int> corner_verts,
557 const GroupedSpan<int> vert_to_face,
558 const Span<bool> hide_poly,
559 const int vert,
560 Vector<int> &r_data)
561{
562 const int vert_start = r_data.size();
563 for (const int face : vert_to_face[vert]) {
564 if (!hide_poly.is_empty() && hide_poly[face]) {
565 continue;
566 }
567 /* In order to support non-manifold topology, both neighboring vertices are added for each
568 * face corner. That results in half being duplicates for any "normal" topology. */
569 const int2 neighbors = bke::mesh::face_find_adjacent_verts(faces[face], corner_verts, vert);
570 for (const int neighbor : {neighbors[0], neighbors[1]}) {
571 bool found = false;
572 for (int i = r_data.size() - 1; i >= vert_start; i--) {
573 if (r_data[i] == neighbor) {
574 found = true;
575 break;
576 }
577 }
578 if (found) {
579 continue;
580 }
581 r_data.append(neighbor);
582 }
583 }
584}
585
586namespace boundary {
587
589{
590 SculptSession &ss = *object.runtime->sculpt_session;
591 if (ss.boundary_info_cache) {
592 return;
593 }
594
595 ss.boundary_info_cache = std::make_unique<SculptBoundaryInfoCache>(
597}
598
600{
602 SculptBoundaryInfoCache boundary_info;
603 boundary_info.verts.resize(mesh.verts_num);
604 Array<int> adjacent_faces_edge_count(mesh.edges_num, 0);
605 array_utils::count_indices(mesh.corner_edges(), adjacent_faces_edge_count);
606
607 const Span<int2> edges = mesh.edges();
608 for (const int e : edges.index_range()) {
609 if (adjacent_faces_edge_count[e] < 2) {
610 const int2 &edge = edges[e];
611 boundary_info.edges.add(edge);
612 boundary_info.verts[edge[0]].set();
613 boundary_info.verts[edge[1]].set();
614 }
615 }
616
617 return boundary_info;
618}
619
620bool vert_is_boundary(const GroupedSpan<int> vert_to_face_map,
621 const Span<bool> hide_poly,
622 const BitSpan boundary_verts,
623 const int vert)
624{
625 if (!hide::vert_all_faces_visible_get(hide_poly, vert_to_face_map, vert)) {
626 return true;
627 }
628 return boundary_verts[vert].test();
629}
630
632 const Span<int> corner_verts,
633 const BitSpan boundary_verts,
634 const Set<OrderedEdge> &boundary_edges,
635 const SubdivCCG &subdiv_ccg,
636 const SubdivCCGCoord vert)
637{
638 /* TODO: Unlike the base mesh implementation this method does NOT take into account face
639 * visibility. Either this should be noted as a intentional limitation or fixed. */
641 faces, corner_verts, boundary_verts, boundary_edges, subdiv_ccg, vert);
642}
643
645{
646 /* TODO: Unlike the base mesh implementation this method does NOT take into account face
647 * visibility. Either this should be noted as a intentional limitation or fixed. */
648 return BM_vert_is_boundary(vert);
649}
650
651} // namespace boundary
652
653/* Utilities */
654
656{
657 return cache.mirror_symmetry_pass == 0 && cache.radial_symmetry_pass == 0 &&
658 cache.tile_pass == 0;
659}
660
662{
663 return cache.first_time && cache.mirror_symmetry_pass == 0 && cache.radial_symmetry_pass == 0 &&
664 cache.tile_pass == 0;
665}
666
668{
669 return cache.first_time;
670}
671
672bool check_vertex_pivot_symmetry(const float vco[3], const float pco[3], const char symm)
673{
674 bool is_in_symmetry_area = true;
675 for (int i = 0; i < 3; i++) {
676 char symm_it = 1 << i;
677 if (symm & symm_it) {
678 if (pco[i] == 0.0f) {
679 if (vco[i] > 0.0f) {
680 is_in_symmetry_area = false;
681 }
682 }
683 if (vco[i] * pco[i] < 0.0f) {
684 is_in_symmetry_area = false;
685 }
686 }
687 }
688 return is_in_symmetry_area;
689}
690
697 const float normal_weight,
698 float grab_delta[3])
699{
700 /* Signed to support grabbing in (to make a hole) as well as out. */
701 const float len_signed = dot_v3v3(cache.sculpt_normal_symm, grab_delta);
702
703 /* This scale effectively projects the offset so dragging follows the cursor,
704 * as the normal points towards the view, the scale increases. */
705 float len_view_scale;
706 {
707 float view_aligned_normal[3];
708 project_plane_v3_v3v3(view_aligned_normal, cache.sculpt_normal_symm, cache.view_normal_symm);
709 len_view_scale = fabsf(dot_v3v3(view_aligned_normal, cache.sculpt_normal_symm));
710 len_view_scale = (len_view_scale > FLT_EPSILON) ? 1.0f / len_view_scale : 1.0f;
711 }
712
713 mul_v3_fl(grab_delta, 1.0f - normal_weight);
715 grab_delta, cache.sculpt_normal_symm, (len_signed * normal_weight) * len_view_scale);
716}
717
719{
720 float3 grab_delta = cache.grab_delta_symm;
721
722 const float normal_weight = bke::brush::normal_weight_get(brush, cache.toggle_settings.invert);
723 if (normal_weight > 0.0f) {
724 sculpt_project_v3_normal_align(cache, normal_weight, grab_delta);
725 }
726
727 return grab_delta;
728}
729
731 const Span<float3> vert_positions,
732 const Span<bool> hide_vert,
733 const float3 &location,
734 const float max_distance,
735 const bool use_original)
736{
737 const float max_distance_sq = max_distance * max_distance;
738 IndexMaskMemory memory;
739 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
740 pbvh, memory, [&](const bke::pbvh::Node &node) {
741 return node_in_sphere(node, location, max_distance_sq, use_original);
742 });
743 if (nodes_in_sphere.is_empty()) {
744 return std::nullopt;
745 }
746
747 struct NearestData {
748 int vert = -1;
749 float distance_sq = std::numeric_limits<float>::max();
750 };
751
753 const NearestData nearest = threading::parallel_reduce(
754 nodes_in_sphere.index_range(),
755 1,
756 NearestData(),
757 [&](const IndexRange range, NearestData nearest) {
758 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
759 for (const int vert : nodes[i].verts()) {
760 if (!hide_vert.is_empty() && hide_vert[vert]) {
761 continue;
762 }
763 const float distance_sq = math::distance_squared(vert_positions[vert], location);
764 if (distance_sq < nearest.distance_sq) {
765 nearest = {vert, distance_sq};
766 }
767 }
768 });
769 return nearest;
770 },
771 [](const NearestData a, const NearestData b) {
772 return a.distance_sq < b.distance_sq ? a : b;
773 });
774 return nearest.vert;
775}
776
777std::optional<SubdivCCGCoord> nearest_vert_calc_grids(const bke::pbvh::Tree &pbvh,
778 const SubdivCCG &subdiv_ccg,
779 const float3 &location,
780 const float max_distance,
781 const bool use_original)
782{
783 const float max_distance_sq = max_distance * max_distance;
784 IndexMaskMemory memory;
785 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
786 pbvh, memory, [&](const bke::pbvh::Node &node) {
787 return node_in_sphere(node, location, max_distance_sq, use_original);
788 });
789 if (nodes_in_sphere.is_empty()) {
790 return std::nullopt;
791 }
792
793 struct NearestData {
794 SubdivCCGCoord coord = {};
795 float distance_sq = std::numeric_limits<float>::max();
796 };
797
798 const BitGroupVector<> grid_hidden = subdiv_ccg.grid_hidden;
799 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
800 const Span<float3> positions = subdiv_ccg.positions;
801
803 const NearestData nearest = threading::parallel_reduce(
804 nodes_in_sphere.index_range(),
805 1,
806 NearestData(),
807 [&](const IndexRange range, NearestData nearest) {
808 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
809 for (const int grid : nodes[i].grids()) {
810 const IndexRange grid_range = bke::ccg::grid_range(key, grid);
811 BKE_subdiv_ccg_foreach_visible_grid_vert(key, grid_hidden, grid, [&](const int i) {
812 const float distance_sq = math::distance_squared(positions[grid_range[i]], location);
813 if (distance_sq < nearest.distance_sq) {
814 SubdivCCGCoord coord{};
815 coord.grid_index = grid;
816 coord.x = i % key.grid_size;
817 coord.y = i / key.grid_size;
818 nearest = {coord, distance_sq};
819 }
820 });
821 }
822 });
823 return nearest;
824 },
825 [](const NearestData a, const NearestData b) {
826 return a.distance_sq < b.distance_sq ? a : b;
827 });
828 return nearest.coord;
829}
830
831std::optional<BMVert *> nearest_vert_calc_bmesh(const bke::pbvh::Tree &pbvh,
832 const float3 &location,
833 const float max_distance,
834 const bool use_original)
835{
836 const float max_distance_sq = max_distance * max_distance;
837 IndexMaskMemory memory;
838 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
839 pbvh, memory, [&](const bke::pbvh::Node &node) {
840 return node_in_sphere(node, location, max_distance_sq, use_original);
841 });
842 if (nodes_in_sphere.is_empty()) {
843 return std::nullopt;
844 }
845
846 struct NearestData {
847 BMVert *vert = nullptr;
848 float distance_sq = std::numeric_limits<float>::max();
849 };
850
852 const NearestData nearest = threading::parallel_reduce(
853 nodes_in_sphere.index_range(),
854 1,
855 NearestData(),
856 [&](const IndexRange range, NearestData nearest) {
857 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
858 for (BMVert *vert :
860 {
862 continue;
863 }
864 const float distance_sq = math::distance_squared(float3(vert->co), location);
865 if (distance_sq < nearest.distance_sq) {
866 nearest = {vert, distance_sq};
867 }
868 }
869 });
870 return nearest;
871 },
872 [](const NearestData a, const NearestData b) {
873 return a.distance_sq < b.distance_sq ? a : b;
874 });
875 return nearest.vert;
876}
877
879 const float br_co[3],
880 float radius,
881 char symm)
882{
883 for (char i = 0; i <= symm; ++i) {
884 if (!is_symmetry_iteration_valid(i, symm)) {
885 continue;
886 }
887 float3 location = symmetry_flip(br_co, ePaintSymmetryFlags(i));
888 if (len_squared_v3v3(location, vertex) < radius * radius) {
889 return true;
890 }
891 }
892 return false;
893}
894
910
912
913/* -------------------------------------------------------------------- */
919
933
934static bool brush_uses_topology_rake(const SculptSession &ss, const Brush &brush)
935{
936 return bke::brush::supports_topology_rake(brush) && (brush.topology_rake_factor > 0.0f) &&
937 (ss.bm != nullptr);
938}
939
964
966{
967 return bke::brush::supports_rake_factor(brush) && (brush.rake_factor != 0.0f);
968}
969
971
972static void rake_data_update(SculptRakeData *srd, const float co[3])
973{
974 float rake_dist = len_v3v3(srd->follow_co, co);
975 if (rake_dist > srd->follow_dist) {
976 interp_v3_v3v3(srd->follow_co, srd->follow_co, co, rake_dist - srd->follow_dist);
977 }
978}
979
980/* -------------------------------------------------------------------- */
983
984namespace dyntopo {
985
986bool stroke_is_dyntopo(const Object &object, const Brush &brush)
987{
988 const SculptSession &ss = *object.runtime->sculpt_session;
990 return ((pbvh.type() == bke::pbvh::Type::BMesh) &&
991 (!ss.cache || (!ss.cache->toggle_settings.alt_smooth)) &&
992 /* Requires mesh restore, which doesn't work with
993 * dynamic-topology. */
996}
997
998} // namespace dyntopo
999
1001
1002/* -------------------------------------------------------------------- */
1005
1006namespace undo {
1007
1009{
1010 SculptSession &ss = *object.runtime->sculpt_session;
1012 IndexMaskMemory memory;
1013 const IndexMask node_mask = bke::pbvh::all_leaf_nodes(pbvh, memory);
1014
1015 Array<bool> node_changed(node_mask.min_array_size(), false);
1016
1017 switch (pbvh.type()) {
1018 case bke::pbvh::Type::Mesh: {
1020 Mesh &mesh = *id_cast<Mesh *>(object.data);
1021 bke::MutableAttributeAccessor attributes = mesh.attributes_for_write();
1023 ".sculpt_mask", bke::AttrDomain::Point);
1024 node_mask.foreach_index(
1025 [&](const int i) {
1026 if (const std::optional<Span<float>> orig_data = orig_mask_data_lookup_mesh(object,
1027 nodes[i]))
1028 {
1029 const Span<int> verts = nodes[i].verts();
1030 scatter_data_mesh(*orig_data, verts, mask.span);
1032 node_changed[i] = true;
1033 }
1034 },
1036 mask.finish();
1037 break;
1038 }
1041 const int offset = CustomData_get_offset_named(&ss.bm->vdata, CD_PROP_FLOAT, ".sculpt_mask");
1042 if (offset != -1) {
1043 node_mask.foreach_index(
1044 [&](const int i) {
1045 for (BMVert *vert : BKE_pbvh_bmesh_node_unique_verts(&nodes[i])) {
1046 if (const float *orig_mask = BM_log_find_original_vert_mask(ss.bm_log, vert)) {
1047 BM_ELEM_CD_SET_FLOAT(vert, offset, *orig_mask);
1049 node_changed[i] = true;
1050 }
1051 }
1052 },
1054 }
1055 break;
1056 }
1059 SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
1060 const BitGroupVector<> grid_hidden = subdiv_ccg.grid_hidden;
1061 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
1062 MutableSpan<float> masks = subdiv_ccg.masks;
1063 node_mask.foreach_index(
1064 [&](const int i) {
1065 if (const std::optional<Span<float>> orig_data = orig_mask_data_lookup_grids(object,
1066 nodes[i]))
1067 {
1068 int index = 0;
1069 for (const int grid : nodes[i].grids()) {
1070 const IndexRange grid_range = bke::ccg::grid_range(key, grid);
1071 for (const int i : IndexRange(key.grid_area)) {
1072 if (grid_hidden.is_empty() || !grid_hidden[grid][i]) {
1073 masks[grid_range[i]] = (*orig_data)[index];
1074 }
1075 index++;
1076 }
1077 }
1079 node_changed[i] = true;
1080 }
1081 },
1083 break;
1084 }
1085 }
1086 pbvh.tag_masks_changed(IndexMask::from_bools(node_changed, memory));
1087}
1088
1090{
1093 IndexMaskMemory memory;
1094 const IndexMask node_mask = IndexMask::from_predicate(
1095 nodes.index_range(),
1096 memory,
1097 [&](const int i) { return orig_color_data_lookup_mesh(object, nodes[i]).has_value(); },
1099
1101 Mesh &mesh = *id_cast<Mesh *>(object.data);
1102 const OffsetIndices<int> faces = mesh.faces();
1103 const Span<int> corner_verts = mesh.corner_verts();
1104 const GroupedSpan<int> vert_to_face_map = mesh.vert_to_face_map();
1106 node_mask.foreach_index(
1107 [&](const int i) {
1108 const Span<float4> orig_data = *orig_color_data_lookup_mesh(object, nodes[i]);
1109 const Span<int> verts = nodes[i].verts();
1110 for (const int i : verts.index_range()) {
1112 corner_verts,
1113 vert_to_face_map,
1114 color_attribute.domain,
1115 verts[i],
1116 orig_data[i],
1117 color_attribute.span);
1118 }
1119 },
1121 pbvh.tag_attribute_changed(node_mask, mesh.active_color_attribute);
1122 color_attribute.finish();
1123}
1124
1126{
1127 SculptSession &ss = *object.runtime->sculpt_session;
1129 IndexMaskMemory memory;
1130 const IndexMask node_mask = bke::pbvh::all_leaf_nodes(pbvh, memory);
1131
1132 Array<bool> node_changed(node_mask.min_array_size(), false);
1133
1134 switch (pbvh.type()) {
1135 case bke::pbvh::Type::Mesh: {
1138 *id_cast<Mesh *>(object.data));
1139 node_mask.foreach_index(
1140 [&](const int i) {
1141 if (const std::optional<Span<int>> orig_data = orig_face_set_data_lookup_mesh(
1142 object, nodes[i]))
1143 {
1144 scatter_data_mesh(*orig_data, nodes[i].faces(), attribute.span);
1145 node_changed[i] = true;
1146 }
1147 },
1149 attribute.finish();
1150 break;
1151 }
1153 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
1156 *id_cast<Mesh *>(object.data));
1158 node_mask.foreach_index(
1159 [&](const int i) {
1160 Vector<int> &tls = all_tls.local();
1161 if (const std::optional<Span<int>> orig_data = orig_face_set_data_lookup_grids(
1162 object, nodes[i]))
1163 {
1165 subdiv_ccg, nodes[i], tls);
1166 scatter_data_mesh(*orig_data, faces, attribute.span);
1167 node_changed[i] = true;
1168 }
1169 },
1171 attribute.finish();
1172 break;
1173 }
1175 break;
1176 }
1177
1178 pbvh.tag_face_sets_changed(IndexMask::from_bools(node_changed, memory));
1179}
1180
1181void restore_position_from_undo_step(const Depsgraph &depsgraph, Object &object)
1182{
1183 SculptSession &ss = *object.runtime->sculpt_session;
1185 IndexMaskMemory memory;
1186
1187 switch (pbvh.type()) {
1188 case bke::pbvh::Type::Mesh: {
1190 Mesh &mesh = *id_cast<Mesh *>(object.data);
1191 MutableSpan positions_eval = bke::pbvh::vert_positions_eval_for_write(depsgraph, object);
1192 MutableSpan positions_orig = mesh.vert_positions_for_write();
1193
1194 const IndexMask node_mask = IndexMask::from_predicate(
1195 nodes.index_range(),
1196 memory,
1197 [&](const int i) {
1198 return orig_position_data_lookup_mesh(object, nodes[i]).has_value();
1199 },
1201
1202 struct LocalData {
1203 Vector<float3> translations;
1204 };
1205
1206 std::optional<ShapeKeyData> shape_key_data = ShapeKeyData::from_object(object);
1207 const bool need_translations = !ss.deform_imats.is_empty() || shape_key_data.has_value();
1208
1210 node_mask.foreach_index(
1211 [&](const int i) {
1213 LocalData &tls = all_tls.local();
1214 const OrigPositionData orig_data = *orig_position_data_lookup_mesh(object, nodes[i]);
1215 const Span<int> verts = nodes[i].verts();
1216 const Span<float3> undo_positions = orig_data.positions;
1217 if (need_translations) {
1218 /* Calculate translations from evaluated positions before they are changed. */
1219 tls.translations.resize(verts.size());
1221 undo_positions, verts, positions_eval, tls.translations);
1222 }
1223
1224 scatter_data_mesh(undo_positions, verts, positions_eval);
1225
1226 if (positions_eval.data() == positions_orig.data()) {
1227 return;
1228 }
1229
1230 const MutableSpan<float3> translations = tls.translations;
1231 if (!ss.deform_imats.is_empty()) {
1232 apply_crazyspace_to_translations(ss.deform_imats, verts, translations);
1233 }
1234
1235 if (shape_key_data) {
1236 for (MutableSpan<float3> data : shape_key_data->dependent_keys) {
1237 apply_translations(translations, verts, data);
1238 }
1239
1240 if (shape_key_data->basis_key_active) {
1241 /* The basis key positions and the mesh positions are always kept in sync. */
1242 apply_translations(translations, verts, positions_orig);
1243 }
1244 apply_translations(translations, verts, shape_key_data->active_key_data);
1245 }
1246 else {
1247 apply_translations(translations, verts, positions_orig);
1248 }
1249 });
1250 },
1252 pbvh.tag_positions_changed(node_mask);
1253 break;
1254 }
1258 return;
1259 }
1260 const IndexMask node_mask = bke::pbvh::all_leaf_nodes(pbvh, memory);
1261 node_mask.foreach_index(
1262 [&](const int i) {
1263 for (BMVert *vert : BKE_pbvh_bmesh_node_unique_verts(&nodes[i])) {
1264 if (const float *orig_co = BM_log_find_original_vert_co(ss.bm_log, vert)) {
1265 copy_v3_v3(vert->co, orig_co);
1266 }
1267 }
1268 },
1270 pbvh.tag_positions_changed(node_mask);
1271 break;
1272 }
1275
1276 const IndexMask node_mask = IndexMask::from_predicate(
1277 nodes.index_range(),
1278 memory,
1279 [&](const int i) {
1280 return orig_position_data_lookup_grids(object, nodes[i]).has_value();
1281 },
1283
1284 SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
1285 const BitGroupVector<> grid_hidden = subdiv_ccg.grid_hidden;
1286 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
1287 MutableSpan<float3> positions = subdiv_ccg.positions;
1288 node_mask.foreach_index(
1289 [&](const int i) {
1290 const OrigPositionData orig_data = *orig_position_data_lookup_grids(object, nodes[i]);
1291 int index = 0;
1292 for (const int grid : nodes[i].grids()) {
1293 const IndexRange grid_range = bke::ccg::grid_range(key, grid);
1294 for (const int i : IndexRange(key.grid_area)) {
1295 if (grid_hidden.is_empty() || !grid_hidden[grid][i]) {
1296 positions[grid_range[i]] = orig_data.positions[index];
1297 }
1298 index++;
1299 }
1300 }
1301 },
1303 pbvh.tag_positions_changed(node_mask);
1304 break;
1305 }
1306 }
1307}
1308
1309static void restore_from_undo_step(const Depsgraph &depsgraph, const Sculpt &sd, Object &object)
1310{
1311 SculptSession &ss = *object.runtime->sculpt_session;
1313
1314 switch (brush->sculpt_brush_type) {
1317 break;
1322 break;
1325 restore_position_from_undo_step(depsgraph, object);
1326 bke::pbvh::update_normals(depsgraph, object, *bke::object::pbvh_get(object));
1327 }
1328 else {
1330 }
1331 break;
1332 default:
1333 restore_position_from_undo_step(depsgraph, object);
1334 bke::pbvh::update_normals(depsgraph, object, *bke::object::pbvh_get(object));
1335 break;
1336 }
1337}
1338
1339} // namespace undo
1340
1341const float *brush_frontface_normal_from_falloff_shape(const SculptSession &ss, char falloff_shape)
1342{
1343 if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
1344 return ss.cache->sculpt_normal_symm;
1345 }
1346 BLI_assert(falloff_shape == PAINT_FALLOFF_SHAPE_TUBE);
1347 return ss.cache->view_normal_symm;
1348}
1349
1351
1352/* -------------------------------------------------------------------- */
1365
1367 /* 0 = towards view, 1 = flipped */
1368 std::array<float3, 2> area_cos;
1369 std::array<int, 2> count_co;
1370
1371 std::array<float3, 2> area_nos;
1372 std::array<int, 2> count_no;
1373};
1374
1376{
1377 float test_radius = ss.cache ? ss.cache->radius : ss.cursor_radius;
1378 if (brush.ob_mode == OB_MODE_SCULPT) {
1379 test_radius *= brush.normal_radius_factor;
1380 }
1381 return test_radius;
1382}
1383
1385 const Brush &brush)
1386{
1387 float test_radius = ss.cache ? ss.cache->radius : ss.cursor_radius;
1388 if (brush.ob_mode == OB_MODE_SCULPT) {
1389 /* Layer brush produces artifacts with normal and area radius */
1390 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_PLANE && brush.area_radius_factor > 0.0f) {
1391 test_radius *= brush.area_radius_factor;
1392 if (ss.cache && brush.flag2 & BRUSH_AREA_RADIUS_PRESSURE) {
1393 test_radius *= ss.cache->pressure;
1394 }
1395 }
1396 else {
1397 test_radius *= brush.normal_radius_factor;
1398 }
1399 }
1400 return test_radius;
1401}
1402
1403/* Weight the normals towards the center. */
1404static float area_normal_calc_weight(const float distance, const float radius_inv)
1405{
1406 float p = 1.0f - (distance * radius_inv);
1407 return std::clamp(3.0f * p * p - 2.0f * p * p * p, 0.0f, 1.0f);
1408}
1409
1410/* Weight the coordinates towards the center. */
1411static float3 area_center_calc_weighted(const float3 &test_location,
1412 const float distance,
1413 const float radius_inv,
1414 const float3 &co)
1415{
1416 /* Weight the coordinates towards the center. */
1417 float p = 1.0f - (distance * radius_inv);
1418 const float afactor = std::clamp(3.0f * p * p - 2.0f * p * p * p, 0.0f, 1.0f);
1419
1420 const float3 disp = (co - test_location) * (1.0f - afactor);
1421 return test_location + disp;
1422}
1423
1424static void accumulate_area_center(const float3 &test_location,
1425 const float3 &position,
1426 const float distance,
1427 const float radius_inv,
1428 const int flip_index,
1429 AreaNormalCenterData &anctd)
1430{
1431 anctd.area_cos[flip_index] += area_center_calc_weighted(
1432 test_location, distance, radius_inv, position);
1433 anctd.count_co[flip_index] += 1;
1434}
1435
1436static void accumulate_area_normal(const float3 &normal,
1437 const float distance,
1438 const float radius_inv,
1439 const int flip_index,
1440 AreaNormalCenterData &anctd)
1441{
1442 anctd.area_nos[flip_index] += normal * area_normal_calc_weight(distance, radius_inv);
1443 anctd.count_no[flip_index] += 1;
1444}
1445
1450
1452 Position = 1 << 0,
1453 Normal = 1 << 1,
1454
1456};
1458
1460 const Span<float3> vert_positions,
1461 const Span<float3> vert_normals,
1462 const Span<bool> hide_vert,
1463 const Brush &brush,
1464 const AverageDataFlags flag,
1466 AreaNormalCenterData &anctd)
1467{
1469 const SculptSession &ss = *object.runtime->sculpt_session;
1470 const float3 &location = ss.cache ? ss.cache->location_symm : ss.cursor_location;
1471 const float3 &view_normal = ss.cache ? ss.cache->view_normal_symm : ss.cursor_view_normal;
1472 const float position_radius = area_normal_and_center_get_position_radius(ss, brush);
1473 const float position_radius_sq = position_radius * position_radius;
1474 const float position_radius_inv = math::rcp(position_radius);
1475 const float normal_radius = area_normal_and_center_get_normal_radius(ss, brush);
1476 const float normal_radius_sq = normal_radius * normal_radius;
1477 const float normal_radius_inv = math::rcp(normal_radius);
1478
1479 const Span<int> verts = node.verts();
1480
1481 Array<float, bke::pbvh::MESH_LEAF_LIMIT> distances_sq(verts.size());
1482
1483 if (ss.cache && !ss.cache->accum) {
1484 if (const std::optional<OrigPositionData> orig_data = orig_position_data_lookup_mesh(object,
1485 node))
1486 {
1487 const Span<float3> orig_positions = orig_data->positions;
1488 const Span<float3> orig_normals = orig_data->normals;
1489
1491 ss, orig_positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1492
1493 for (const int i : verts.index_range()) {
1494 const int vert = verts[i];
1495 if (!hide_vert.is_empty() && hide_vert[vert]) {
1496 continue;
1497 }
1498 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1499 distances_sq[i] <= normal_radius_sq;
1500 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1501 distances_sq[i] <= position_radius_sq;
1502 if (!needs_normal && !needs_center) {
1503 continue;
1504 }
1505 const float3 &normal = orig_normals[i];
1506 const float distance = std::sqrt(distances_sq[i]);
1507 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1508 if (needs_center) {
1510 location, orig_positions[i], distance, position_radius_inv, flip_index, anctd);
1511 }
1512 if (needs_normal) {
1513 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1514 }
1515 }
1516 return;
1517 }
1518 }
1519
1521 ss, vert_positions, verts, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1522
1523 for (const int i : verts.index_range()) {
1524 const int vert = verts[i];
1525 if (!hide_vert.is_empty() && hide_vert[vert]) {
1526 continue;
1527 }
1528 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1529 distances_sq[i] <= normal_radius_sq;
1530 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1531 distances_sq[i] <= position_radius_sq;
1532 if (!needs_normal && !needs_center) {
1533 continue;
1534 }
1535 const float3 &normal = vert_normals[vert];
1536 const float distance = std::sqrt(distances_sq[i]);
1537 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1538 if (needs_center) {
1540 location, vert_positions[vert], distance, position_radius_inv, flip_index, anctd);
1541 }
1542 if (needs_normal) {
1543 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1544 }
1545 }
1546}
1547
1549 const Brush &brush,
1550 const AverageDataFlags flag,
1552 SampleLocalData &tls,
1553 AreaNormalCenterData &anctd)
1554{
1556 const SculptSession &ss = *object.runtime->sculpt_session;
1557 const float3 &location = ss.cache ? ss.cache->location_symm : ss.cursor_location;
1558 const float3 &view_normal = ss.cache ? ss.cache->view_normal_symm : ss.cursor_view_normal;
1559 const float position_radius = area_normal_and_center_get_position_radius(ss, brush);
1560 const float position_radius_sq = position_radius * position_radius;
1561 const float position_radius_inv = math::rcp(position_radius);
1562 const float normal_radius = area_normal_and_center_get_normal_radius(ss, brush);
1563 const float normal_radius_sq = normal_radius * normal_radius;
1564 const float normal_radius_inv = math::rcp(normal_radius);
1565
1566 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
1568 const Span<float3> normals = subdiv_ccg.normals;
1569 const BitGroupVector<> &grid_hidden = subdiv_ccg.grid_hidden;
1570 const Span<int> grids = node.grids();
1571
1572 if (ss.cache && !ss.cache->accum) {
1573 if (const std::optional<OrigPositionData> orig_data = orig_position_data_lookup_grids(object,
1574 node))
1575 {
1576 const Span<float3> orig_positions = orig_data->positions;
1577 const Span<float3> orig_normals = orig_data->normals;
1578
1579 tls.distances.reinitialize(orig_positions.size());
1580 const MutableSpan<float> distances_sq = tls.distances;
1582 ss, orig_positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1583
1584 for (const int i : grids.index_range()) {
1585 const IndexRange grid_range_node = bke::ccg::grid_range(key, i);
1586 const int grid = grids[i];
1587 for (const int offset : IndexRange(key.grid_area)) {
1588 if (!grid_hidden.is_empty() && grid_hidden[grid][offset]) {
1589 continue;
1590 }
1591 const int node_vert = grid_range_node[offset];
1592
1593 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1594 distances_sq[node_vert] <= normal_radius_sq;
1595 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1596 distances_sq[node_vert] <= position_radius_sq;
1597 if (!needs_normal && !needs_center) {
1598 continue;
1599 }
1600 const float3 &normal = orig_normals[node_vert];
1601 const float distance = std::sqrt(distances_sq[node_vert]);
1602 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1603 if (needs_center) {
1604 accumulate_area_center(location,
1605 orig_positions[node_vert],
1606 distance,
1607 position_radius_inv,
1608 flip_index,
1609 anctd);
1610 }
1611 if (needs_normal) {
1612 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1613 }
1614 }
1615 }
1616 return;
1617 }
1618 }
1619
1620 const Span<float3> positions = gather_grids_positions(subdiv_ccg, grids, tls.positions);
1621 tls.distances.reinitialize(positions.size());
1622 const MutableSpan<float> distances_sq = tls.distances;
1624 ss, positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1625
1626 for (const int i : grids.index_range()) {
1627 const IndexRange grid_range_node = bke::ccg::grid_range(key, i);
1628 const int grid = grids[i];
1629 const IndexRange grid_range = bke::ccg::grid_range(key, grid);
1630 for (const int offset : IndexRange(key.grid_area)) {
1631 if (!grid_hidden.is_empty() && grid_hidden[grid][offset]) {
1632 continue;
1633 }
1634 const int node_vert = grid_range_node[offset];
1635 const int vert = grid_range[offset];
1636
1637 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1638 distances_sq[node_vert] <= normal_radius_sq;
1639 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1640 distances_sq[node_vert] <= position_radius_sq;
1641 if (!needs_normal && !needs_center) {
1642 continue;
1643 }
1644 const float3 &normal = normals[vert];
1645 const float distance = std::sqrt(distances_sq[node_vert]);
1646 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1647 if (needs_center) {
1649 location, positions[node_vert], distance, position_radius_inv, flip_index, anctd);
1650 }
1651 if (needs_normal) {
1652 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1653 }
1654 }
1655 }
1656}
1657
1659 const Brush &brush,
1660 const AverageDataFlags flag,
1661 const bool has_bm_orco,
1663 SampleLocalData &tls,
1664 AreaNormalCenterData &anctd)
1665{
1667 const SculptSession &ss = *object.runtime->sculpt_session;
1668 const float3 &location = ss.cache ? ss.cache->location_symm : ss.cursor_location;
1669 const float3 &view_normal = ss.cache ? ss.cache->view_normal_symm : ss.cursor_view_normal;
1670 const float position_radius = area_normal_and_center_get_position_radius(ss, brush);
1671 const float position_radius_sq = position_radius * position_radius;
1672 const float position_radius_inv = math::rcp(position_radius);
1673 const float normal_radius = area_normal_and_center_get_normal_radius(ss, brush);
1674 const float normal_radius_sq = normal_radius * normal_radius;
1675 const float normal_radius_inv = math::rcp(normal_radius);
1676
1677 bool use_original = false;
1678 if (ss.cache && !ss.cache->accum) {
1679 use_original = undo::has_bmesh_log_entry();
1680 }
1681
1682 /* When the mesh is edited we can't rely on original coords
1683 * (original mesh may not even have verts in brush radius). */
1684 if (use_original && has_bm_orco) {
1685 Span<float3> orig_positions;
1686 Span<int3> orig_tris;
1687 BKE_pbvh_node_get_bm_orco_data(node, orig_positions, orig_tris);
1688
1689 tls.positions.resize(orig_tris.size());
1690 const MutableSpan<float3> positions = tls.positions;
1691 for (const int i : orig_tris.index_range()) {
1692 const float *co_tri[3] = {
1693 orig_positions[orig_tris[i][0]],
1694 orig_positions[orig_tris[i][1]],
1695 orig_positions[orig_tris[i][2]],
1696 };
1697 closest_on_tri_to_point_v3(positions[i], location, UNPACK3(co_tri));
1698 }
1699
1700 tls.distances.reinitialize(positions.size());
1701 const MutableSpan<float> distances_sq = tls.distances;
1703 ss, positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1704
1705 for (const int i : orig_tris.index_range()) {
1706 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1707 distances_sq[i] <= normal_radius_sq;
1708 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1709 distances_sq[i] <= position_radius_sq;
1710 if (!needs_normal && !needs_center) {
1711 continue;
1712 }
1713 const float3 normal = math::normal_tri(float3(orig_positions[orig_tris[i][0]]),
1714 float3(orig_positions[orig_tris[i][1]]),
1715 float3(orig_positions[orig_tris[i][2]]));
1716
1717 const float distance = std::sqrt(distances_sq[i]);
1718 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1719 if (needs_center) {
1721 location, positions[i], distance, position_radius_inv, flip_index, anctd);
1722 }
1723 if (needs_normal) {
1724 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1725 }
1726 }
1727 return;
1728 }
1729
1731 &const_cast<bke::pbvh::BMeshNode &>(node));
1732 if (use_original) {
1733 tls.positions.resize(verts.size());
1734 const MutableSpan<float3> positions = tls.positions;
1735 Array<float3> normals(verts.size());
1736 orig_position_data_gather_bmesh(*ss.bm_log, verts, positions, normals);
1737
1738 tls.distances.reinitialize(positions.size());
1739 const MutableSpan<float> distances_sq = tls.distances;
1741 ss, positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1742
1743 int i = 0;
1744 for (BMVert *vert : verts) {
1745 if (BM_elem_flag_test(vert, BM_ELEM_HIDDEN)) {
1746 i++;
1747 continue;
1748 }
1749 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1750 distances_sq[i] <= normal_radius_sq;
1751 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1752 distances_sq[i] <= position_radius_sq;
1753 if (!needs_normal && !needs_center) {
1754 i++;
1755 continue;
1756 }
1757 const float3 &normal = normals[i];
1758 const float distance = std::sqrt(distances_sq[i]);
1759 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1760 if (needs_center) {
1762 location, positions[i], distance, position_radius_inv, flip_index, anctd);
1763 }
1764 if (needs_normal) {
1765 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1766 }
1767 i++;
1768 }
1769 return;
1770 }
1771
1772 const Span<float3> positions = gather_bmesh_positions(verts, tls.positions);
1773
1774 tls.distances.reinitialize(positions.size());
1775 const MutableSpan<float> distances_sq = tls.distances;
1777 ss, positions, eBrushFalloffShape(brush.falloff_shape), distances_sq);
1778
1779 int i = 0;
1780 for (BMVert *vert : verts) {
1781 if (BM_elem_flag_test(vert, BM_ELEM_HIDDEN)) {
1782 i++;
1783 continue;
1784 }
1785 const bool needs_normal = flag_is_set(flag, AverageDataFlags::Normal) &&
1786 distances_sq[i] <= normal_radius_sq;
1787 const bool needs_center = flag_is_set(flag, AverageDataFlags::Position) &&
1788 distances_sq[i] <= position_radius_sq;
1789 if (!needs_normal && !needs_center) {
1790 i++;
1791 continue;
1792 }
1793 const float3 normal = vert->no;
1794 const float distance = std::sqrt(distances_sq[i]);
1795 const int flip_index = math::dot(view_normal, normal) <= 0.0f;
1796 if (needs_center) {
1798 location, positions[i], distance, position_radius_inv, flip_index, anctd);
1799 }
1800 if (needs_normal) {
1801 accumulate_area_normal(normal, distance, normal_radius_inv, flip_index, anctd);
1802 }
1803 i++;
1804 }
1805}
1806
1808 const AreaNormalCenterData &b)
1809{
1810 AreaNormalCenterData joined{};
1811
1812 joined.area_cos[0] = a.area_cos[0] + b.area_cos[0];
1813 joined.area_cos[1] = a.area_cos[1] + b.area_cos[1];
1814 joined.count_co[0] = a.count_co[0] + b.count_co[0];
1815 joined.count_co[1] = a.count_co[1] + b.count_co[1];
1816
1817 joined.area_nos[0] = a.area_nos[0] + b.area_nos[0];
1818 joined.area_nos[1] = a.area_nos[1] + b.area_nos[1];
1819 joined.count_no[0] = a.count_no[0] + b.count_no[0];
1820 joined.count_no[1] = a.count_no[1] + b.count_no[1];
1821
1822 return joined;
1823}
1824
1825void calc_area_center(const Depsgraph &depsgraph,
1826 const Brush &brush,
1827 const Object &ob,
1828 const IndexMask &node_mask,
1829 float r_area_co[3])
1830{
1833 const SculptSession &ss = *ob.runtime->sculpt_session;
1834 int n;
1835
1838 switch (pbvh.type()) {
1839 case bke::pbvh::Type::Mesh: {
1840 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
1841 const Span<float3> vert_positions = bke::pbvh::vert_positions_eval(depsgraph, ob);
1842 const Span<float3> vert_normals = bke::pbvh::vert_normals_eval(depsgraph, ob);
1843 const bke::AttributeAccessor attributes = mesh.attributes();
1844 const VArraySpan hide_vert = *attributes.lookup<bool>(".hide_vert", bke::AttrDomain::Point);
1845
1848 node_mask.index_range(),
1849 1,
1851 [&](const IndexRange range, AreaNormalCenterData anctd) {
1852 node_mask.slice(range).foreach_index([&](const int i) {
1853 calc_area_normal_and_center_node_mesh(ob,
1854 vert_positions,
1855 vert_normals,
1856 hide_vert,
1857 brush,
1858 AverageDataFlags::Position,
1859 nodes[i],
1860 anctd);
1861 });
1862 return anctd;
1863 },
1865 break;
1866 }
1868 const bool has_bm_orco = ss.bm && dyntopo::stroke_is_dyntopo(ob, brush);
1869
1872 node_mask.index_range(),
1873 1,
1875 [&](const IndexRange range, AreaNormalCenterData anctd) {
1876 SampleLocalData &tls = all_tls.local();
1877 node_mask.slice(range).foreach_index([&](const int i) {
1878 calc_area_normal_and_center_node_bmesh(
1879 ob, brush, AverageDataFlags::Position, has_bm_orco, nodes[i], tls, anctd);
1880 });
1881 return anctd;
1882 },
1884 break;
1885 }
1889 node_mask.index_range(),
1890 1,
1892 [&](const IndexRange range, AreaNormalCenterData anctd) {
1893 SampleLocalData &tls = all_tls.local();
1894 node_mask.slice(range).foreach_index([&](const int i) {
1895 calc_area_normal_and_center_node_grids(
1896 ob, brush, AverageDataFlags::Position, nodes[i], tls, anctd);
1897 });
1898 return anctd;
1899 },
1901 break;
1902 }
1903 }
1904
1905 /* For flatten center. */
1906 for (n = 0; n < anctd.area_cos.size(); n++) {
1907 if (anctd.count_co[n] == 0) {
1908 continue;
1909 }
1910
1911 mul_v3_v3fl(r_area_co, anctd.area_cos[n], 1.0f / anctd.count_co[n]);
1912 break;
1913 }
1914
1915 if (n == 2) {
1916 zero_v3(r_area_co);
1917 }
1918
1919 if (anctd.count_co[0] == 0 && anctd.count_co[1] == 0) {
1920 if (ss.cache) {
1921 copy_v3_v3(r_area_co, ss.cache->location_symm);
1922 }
1923 }
1924}
1925
1926std::optional<float3> calc_area_normal(const Depsgraph &depsgraph,
1927 const Brush &brush,
1928 const Object &ob,
1929 const IndexMask &node_mask)
1930{
1934
1937 switch (pbvh.type()) {
1938 case bke::pbvh::Type::Mesh: {
1939 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
1940 const Span<float3> vert_positions = bke::pbvh::vert_positions_eval(depsgraph, ob);
1941 const Span<float3> vert_normals = bke::pbvh::vert_normals_eval(depsgraph, ob);
1942 const bke::AttributeAccessor attributes = mesh.attributes();
1943 const VArraySpan hide_vert = *attributes.lookup<bool>(".hide_vert", bke::AttrDomain::Point);
1944
1947 node_mask.index_range(),
1948 1,
1950 [&](const IndexRange range, AreaNormalCenterData anctd) {
1951 node_mask.slice(range).foreach_index([&](const int i) {
1952 calc_area_normal_and_center_node_mesh(ob,
1953 vert_positions,
1954 vert_normals,
1955 hide_vert,
1956 brush,
1957 AverageDataFlags::Normal,
1958 nodes[i],
1959 anctd);
1960 });
1961 return anctd;
1962 },
1964 break;
1965 }
1967 const bool has_bm_orco = ss.bm && dyntopo::stroke_is_dyntopo(ob, brush);
1968
1971 node_mask.index_range(),
1972 1,
1974 [&](const IndexRange range, AreaNormalCenterData anctd) {
1975 SampleLocalData &tls = all_tls.local();
1976 node_mask.slice(range).foreach_index([&](const int i) {
1977 calc_area_normal_and_center_node_bmesh(
1978 ob,
1979 brush,
1980 AverageDataFlags::Normal,
1981 has_bm_orco,
1982 static_cast<const bke::pbvh::BMeshNode &>(nodes[i]),
1983 tls,
1984 anctd);
1985 });
1986 return anctd;
1987 },
1989 break;
1990 }
1994 node_mask.index_range(),
1995 1,
1997 [&](const IndexRange range, AreaNormalCenterData anctd) {
1998 SampleLocalData &tls = all_tls.local();
1999 node_mask.slice(range).foreach_index([&](const int i) {
2000 calc_area_normal_and_center_node_grids(
2001 ob, brush, AverageDataFlags::Normal, nodes[i], tls, anctd);
2002 });
2003 return anctd;
2004 },
2006 break;
2007 }
2008 }
2009
2010 for (const int i : {0, 1}) {
2011 if (anctd.count_no[i] != 0) {
2012 if (!math::is_zero(anctd.area_nos[i])) {
2013 return math::normalize(anctd.area_nos[i]);
2014 }
2015 }
2016 }
2017 return std::nullopt;
2018}
2019
2020/*
2021 * Stabilizes the position (center) and orientation (normal) of the brush plane during a stroke.
2022 * Implements a smoothing mechanism based on a weighted moving average for both the plane normal
2023 * and the plane center.
2024 *
2025 * The stabilized normal (`r_stabilized_normal`) is computed as the average of the last
2026 * `max_normal_index` plane normals, where `max_normal_index` is determined by the
2027 * `stabilize_normal` parameter of the brush. Each new plane normal is interpolated with the
2028 * previous plane normal, with `stabilize_normal` controlling the interpolation factor.
2029 *
2030 * The stabilized center (`r_stabilized_center`) is computed based on the signed distances
2031 * of the stored plane centers from a reference plane defined by the current stroke step's center
2032 * and the stabilized normal. The signed distances are averaged, and this average is used to
2033 * adjust the position of the stabilized center such that it maintains the average offset of the
2034 * stored centers relative to the reference plane.
2035 */
2037 StrokeCache &cache,
2038 const float3 &plane_normal,
2039 const float3 &plane_center,
2040 float3 &r_stabilized_normal,
2041 float3 &r_stabilized_center)
2042{
2043 auto &plane_cache = cache.plane_brush;
2044
2045 const float normal_weight = brush.stabilize_normal;
2046 const float center_weight = brush.stabilize_plane;
2047
2048 float3 new_plane_normal;
2049 float3 new_plane_center;
2050
2051 if (plane_cache.first_time) {
2052 new_plane_normal = plane_normal;
2053 new_plane_center = plane_center;
2054
2055 const int max_normal_index = int(1 +
2056 normal_weight * (plane_brush_max_rolling_average_num - 1));
2057 const int max_center_index = int(1 +
2058 center_weight * (plane_brush_max_rolling_average_num - 1));
2059
2060 plane_cache.normals.reinitialize(max_normal_index);
2061 plane_cache.centers.reinitialize(max_center_index);
2062 plane_cache.normals.fill(plane_normal);
2063 plane_cache.centers.fill(plane_center);
2064
2065 plane_cache.normal_index = 0;
2066 plane_cache.center_index = 0;
2067 plane_cache.first_time = false;
2068 }
2069 else {
2070 const float3 last_normal = plane_cache.last_normal.value();
2071 const float3 last_center = plane_cache.last_center.value();
2072
2073 /* Interpolate between `plane_normal` and the last plane normal. */
2074 new_plane_normal = math::normalize(
2075 math::interpolate(plane_normal, last_normal, normal_weight));
2076
2077 float4 last_plane;
2078 plane_from_point_normal_v3(last_plane, last_center, last_normal);
2079
2080 /* Projection of `plane_center` on the last plane. */
2081 float3 projected_plane_center;
2082 closest_to_plane_normalized_v3(projected_plane_center, last_plane, plane_center);
2083
2084 new_plane_center = math::interpolate(plane_center, projected_plane_center, center_weight);
2085 }
2086
2087 plane_cache.normals[plane_cache.normal_index] = new_plane_normal;
2088 plane_cache.centers[plane_cache.center_index] = new_plane_center;
2089
2090 plane_cache.normal_index = (plane_cache.normal_index + 1) % plane_cache.normals.size();
2091 plane_cache.center_index = (plane_cache.center_index + 1) % plane_cache.centers.size();
2092
2093 r_stabilized_normal = float3(0.0f);
2094
2095 for (const int i : plane_cache.normals.index_range()) {
2096 r_stabilized_normal += plane_cache.normals[i];
2097 }
2098 r_stabilized_normal = math::normalize(r_stabilized_normal);
2099
2100 float4 reference_plane;
2101 plane_from_point_normal_v3(reference_plane, new_plane_center, r_stabilized_normal);
2102 float total_signed_distance = 0.0f;
2103
2104 for (const int i : plane_cache.centers.index_range()) {
2105 float signed_distance = math::dot(r_stabilized_normal, plane_cache.centers[i]) -
2106 reference_plane.w;
2107 total_signed_distance += signed_distance;
2108 }
2109
2110 const float avg_signed_distance = total_signed_distance / plane_cache.centers.size();
2111 const float new_center_signed_distance = math::dot(r_stabilized_normal, new_plane_center) -
2112 reference_plane.w;
2113 const float adjusted_distance = new_center_signed_distance - avg_signed_distance;
2114 r_stabilized_center = new_plane_center - r_stabilized_normal * adjusted_distance;
2115
2116 plane_cache.last_normal = r_stabilized_normal;
2117 plane_cache.last_center = r_stabilized_center;
2118}
2119
2120void calc_area_normal_and_center(const Depsgraph &depsgraph,
2121 const Brush &brush,
2122 const Object &ob,
2123 const IndexMask &node_mask,
2124 float r_area_no[3],
2125 float r_area_co[3])
2126{
2129 int n;
2130
2133 switch (pbvh.type()) {
2134 case bke::pbvh::Type::Mesh: {
2135 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
2136 const Span<float3> vert_positions = bke::pbvh::vert_positions_eval(depsgraph, ob);
2137 const Span<float3> vert_normals = bke::pbvh::vert_normals_eval(depsgraph, ob);
2138 const bke::AttributeAccessor attributes = mesh.attributes();
2139 const VArraySpan hide_vert = *attributes.lookup<bool>(".hide_vert", bke::AttrDomain::Point);
2140
2143 node_mask.index_range(),
2144 1,
2146 [&](const IndexRange range, AreaNormalCenterData anctd) {
2147 node_mask.slice(range).foreach_index([&](const int i) {
2148 calc_area_normal_and_center_node_mesh(ob,
2149 vert_positions,
2150 vert_normals,
2151 hide_vert,
2152 brush,
2153 AverageDataFlags::All,
2154 nodes[i],
2155 anctd);
2156 });
2157 return anctd;
2158 },
2160 break;
2161 }
2163 const bool has_bm_orco = ss.bm && dyntopo::stroke_is_dyntopo(ob, brush);
2164
2167 node_mask.index_range(),
2168 1,
2170 [&](const IndexRange range, AreaNormalCenterData anctd) {
2171 SampleLocalData &tls = all_tls.local();
2172 node_mask.slice(range).foreach_index([&](const int i) {
2173 calc_area_normal_and_center_node_bmesh(
2174 ob, brush, AverageDataFlags::All, has_bm_orco, nodes[i], tls, anctd);
2175 });
2176 return anctd;
2177 },
2179 break;
2180 }
2184 node_mask.index_range(),
2185 1,
2187 [&](const IndexRange range, AreaNormalCenterData anctd) {
2188 SampleLocalData &tls = all_tls.local();
2189 node_mask.slice(range).foreach_index([&](const int i) {
2190 calc_area_normal_and_center_node_grids(
2191 ob, brush, AverageDataFlags::All, nodes[i], tls, anctd);
2192 });
2193 return anctd;
2194 },
2196 break;
2197 }
2198 }
2199
2200 /* For flatten center. */
2201 for (n = 0; n < anctd.area_cos.size(); n++) {
2202 if (anctd.count_co[n] == 0) {
2203 continue;
2204 }
2205
2206 mul_v3_v3fl(r_area_co, anctd.area_cos[n], 1.0f / anctd.count_co[n]);
2207 break;
2208 }
2209
2210 if (n == 2) {
2211 zero_v3(r_area_co);
2212 }
2213
2214 if (anctd.count_co[0] == 0 && anctd.count_co[1] == 0) {
2215 if (ss.cache) {
2216 copy_v3_v3(r_area_co, ss.cache->location_symm);
2217 }
2218 }
2219
2220 /* For area normal. */
2221 for (n = 0; n < anctd.area_nos.size(); n++) {
2222 if (normalize_v3_v3(r_area_no, anctd.area_nos[n]) != 0.0f) {
2223 break;
2224 }
2225 }
2226
2227 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_PLANE) {
2228 float3 stabilized_normal;
2229 float3 stabilized_center;
2230
2232 brush, *ss.cache, r_area_no, r_area_co, stabilized_normal, stabilized_center);
2233
2234 copy_v3_v3(r_area_no, stabilized_normal);
2235 copy_v3_v3(r_area_co, stabilized_center);
2236 }
2237}
2238
2240
2241/* -------------------------------------------------------------------- */
2244
2249static float brush_flip(const Brush &brush, const StrokeCache &cache)
2250{
2251 const float dir = (brush.flag & BRUSH_DIR_IN) ? -1.0f : 1.0f;
2252 const float invert = cache.toggle_settings.invert ? -1.0f : 1.0f;
2253
2254 return dir * invert;
2255}
2256
2262static float brush_strength(const Sculpt &sd, const StrokeCache &cache)
2263{
2265 const bke::PaintRuntime &paint_runtime = *sd.paint.runtime;
2266
2267 /* Primary strength input; square it to make lower values more sensitive. */
2268 const float root_alpha = BKE_brush_alpha_get(&sd.paint, &brush);
2269 const float alpha = root_alpha * root_alpha;
2270 const float pressure = BKE_brush_use_alpha_pressure(&brush) ?
2271 BKE_curvemapping_evaluateF(brush.curve_strength, 0, cache.pressure) :
2272 1.0f;
2273 /* TODO: Rip out overlap factor and extract to more generic processing */
2274 float overlap = paint_runtime.overlap_factor;
2275 /* Spacing is integer percentage of radius, divide by 50 to get
2276 * normalized diameter. */
2277
2278 const float flip = brush_flip(brush, cache);
2279
2280 /* Pressure final value after being tweaked depending on the brush. */
2281 float final_pressure;
2282
2283 switch (brush.sculpt_brush_type) {
2285 final_pressure = pow4f(pressure);
2286 overlap = (1.0f + overlap) / 2.0f;
2287 return 0.25f * alpha * flip * final_pressure * overlap;
2291 return alpha * flip * pressure * overlap;
2293 return alpha * pressure * overlap;
2295 if (brush.cloth_deform_type == BRUSH_CLOTH_DEFORM_GRAB) {
2296 /* Grab deform uses the same falloff as a regular grab brush. */
2297 return root_alpha;
2298 }
2299 else if (brush.cloth_deform_type == BRUSH_CLOTH_DEFORM_SNAKE_HOOK) {
2300 return root_alpha * pressure * overlap;
2301 }
2302 else if (brush.cloth_deform_type == BRUSH_CLOTH_DEFORM_EXPAND) {
2303 /* Expand is more sensible to strength as it keeps expanding the cloth when sculpting over
2304 * the same vertices. */
2305 return 0.1f * alpha * flip * pressure * overlap;
2306 }
2307 else {
2308 /* Multiply by 10 by default to get a larger range of strength depending on the size of the
2309 * brush and object. */
2310 return 10.0f * alpha * flip * pressure * overlap;
2311 }
2313 return alpha * pressure * overlap;
2315 return alpha * pressure * overlap * 2.0f;
2317 final_pressure = pressure * pressure;
2318 return final_pressure * overlap;
2322 return alpha * pressure * overlap;
2324 /* Clay Strips needs less strength to compensate the curve. */
2325 final_pressure = powf(pressure, 1.5f);
2326 return alpha * flip * final_pressure * overlap * 0.3f;
2328 final_pressure = pressure * pressure;
2329 return alpha * flip * final_pressure * overlap * 1.3f;
2330
2332 overlap = (1.0f + overlap) / 2.0f;
2333 switch (BrushMaskTool(brush.mask_tool)) {
2334 case BRUSH_MASK_DRAW:
2335 return alpha * flip * pressure * overlap;
2336 case BRUSH_MASK_SMOOTH:
2337 return alpha * pressure;
2338 }
2339 break;
2342 return alpha * flip * pressure * overlap;
2343
2345 if (flip > 0.0f) {
2346 return 0.250f * alpha * flip * pressure * overlap;
2347 }
2348 else {
2349 return 0.125f * alpha * flip * pressure * overlap;
2350 }
2351
2353 overlap = (1.0f + overlap) / 2.0f;
2354 return alpha * flip * pressure * overlap;
2355
2357 if (flip > 0.0f || brush.plane_inversion_mode == BRUSH_PLANE_SWAP_HEIGHT_AND_DEPTH) {
2358 overlap = (1.0f + overlap) / 2.0f;
2359 return alpha * pressure * overlap;
2360 }
2361 /* When the brush is inverted with the Invert Displacement mode (i.e. when the brush adds
2362 * contrast), use a different formula that results in a lower strength. This is done because,
2363 * from an artistic point of view, the contrast would otherwise generally be too strong. Note
2364 * that this behavior is coherent with the way Fill, Scrape and Flatten work. See #136211. */
2365 else {
2366 return 0.5f * alpha * pressure * overlap;
2367 }
2369 return flip * alpha * pressure;
2370
2372 if (flip > 0.0f) {
2373 return alpha * flip * pressure * overlap;
2374 }
2375 else {
2376 return 0.25f * alpha * flip * pressure * overlap;
2377 }
2378
2380 overlap = (1.0f + overlap) / 2.0f;
2381 return alpha * pressure * overlap;
2382
2384 return alpha * pressure;
2385
2387 return root_alpha;
2388
2390 return root_alpha;
2391
2393 return alpha * pressure;
2394
2398 return root_alpha;
2400 /* The Dyntopo Density brush does not use a normal brush workflow to calculate the effect,
2401 * and this strength value is unused. */
2402 return 0.0f;
2404 return flip * alpha * pressure * overlap;
2405 }
2407 return 0.0f;
2408}
2409
2410void apply_brush_texture(const PaintMode paint_mode,
2411 const SculptSession &ss,
2412 const Brush &brush,
2413 const float brush_point[3],
2414 const int thread_id,
2415 float *r_value,
2416 float4 &r_rgba)
2417{
2418 const StrokeCache &cache = *ss.cache;
2419 const MTex *mtex = BKE_brush_mask_texture_get(&brush, paint_mode);
2420
2421 if (!mtex->tex) {
2422 *r_value = 1.0f;
2423 copy_v4_fl(r_rgba, 1.0f);
2424 return;
2425 }
2426
2427 float point[3];
2428 sub_v3_v3v3(point, brush_point, cache.plane_offset);
2429
2430 if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
2431 /* Get strength by feeding the vertex location directly into a texture. */
2432 *r_value = BKE_brush_sample_tex_3d(cache.paint, &brush, mtex, point, r_rgba, 0, ss.tex_pool);
2433 }
2434 else {
2435 /* If the active area is being applied for symmetry, flip it
2436 * across the symmetry axis and rotate it back to the original
2437 * position in order to project it. This insures that the
2438 * brush texture will be oriented correctly. */
2439 if (cache.radial_symmetry_pass) {
2440 mul_m4_v3(cache.symm_rot_mat_inv.ptr(), point);
2441 }
2442 float3 symm_point = symmetry_flip(point, cache.mirror_symmetry_pass);
2443
2444 /* Still no symmetry supported for other paint modes.
2445 * Sculpt does it DIY. */
2446 if (mtex->brush_map_mode == MTEX_MAP_MODE_AREA) {
2447 /* Similar to fixed mode, but projects from brush angle
2448 * rather than view direction. */
2449
2450 mul_m4_v3(cache.brush_local_mat.ptr(), symm_point);
2451
2452 float x = symm_point[0];
2453 float y = symm_point[1];
2454
2455 x *= mtex->size[0];
2456 y *= mtex->size[1];
2457
2458 x += mtex->ofs[0];
2459 y += mtex->ofs[1];
2460
2461 paint_get_tex_pixel(mtex, x, y, ss.tex_pool, thread_id, r_value, r_rgba);
2462
2463 add_v3_fl(r_rgba, brush.texture_sample_bias); // v3 -> Ignore alpha
2464 *r_value -= brush.texture_sample_bias;
2465 }
2466 else {
2467 const float2 point_2d = ED_view3d_project_float_v2_m4(
2468 cache.vc->region, symm_point, cache.projection_mat);
2469 const float point_3d[3] = {point_2d[0], point_2d[1], 0.0f};
2470 *r_value = BKE_brush_sample_tex_3d(
2471 cache.paint, &brush, mtex, point_3d, r_rgba, 0, ss.tex_pool);
2472 }
2473 }
2474}
2475
2476void calc_vertex_displacement(const SculptSession &ss, const Brush &brush, float translation[3])
2477{
2478 mul_v3_fl(translation, ss.cache->bstrength);
2479 /* Handle brush inversion */
2480 if (ss.cache->bstrength < 0) {
2481 translation[0] *= -1;
2482 translation[1] *= -1;
2483 }
2484
2485 /* Apply texture size */
2486 for (int i = 0; i < 3; ++i) {
2487 translation[i] *= math::safe_divide(1.0f, pow2f(brush.mtex.size[i]));
2488 }
2489
2490 /* Transform vector to object space */
2491 mul_mat3_m4_v3(ss.cache->brush_local_mat_inv.ptr(), translation);
2492
2493 /* Handle symmetry */
2494 if (ss.cache->radial_symmetry_pass) {
2495 mul_m4_v3(ss.cache->symm_rot_mat.ptr(), translation);
2496 }
2497 copy_v3_v3(translation, symmetry_flip(translation, ss.cache->mirror_symmetry_pass));
2498}
2499
2501{
2503 return true;
2504 }
2506 return true;
2507 }
2508 return false;
2509}
2510
2512 const float3 &location,
2513 const float radius_sq,
2514 const bool original)
2515{
2516 const Bounds<float3> &bounds = original ? node.bounds_orig() : node.bounds();
2517 const float3 nearest = math::clamp(location, bounds.min, bounds.max);
2518 return math::distance_squared(location, nearest) < radius_sq;
2519}
2520
2521bool node_in_cylinder(const DistRayAABB_Precalc &ray_dist_precalc,
2522 const bke::pbvh::Node &node,
2523 const float radius_sq,
2524 const bool original)
2525{
2526 const Bounds<float3> &bounds = original ? node.bounds_orig() : node.bounds();
2527
2528 float dummy_co[3], dummy_depth;
2529 const float dist_sq = dist_squared_ray_to_aabb_v3(
2530 &ray_dist_precalc, bounds.min, bounds.max, dummy_co, &dummy_depth);
2531
2532 /* TODO: Solve issues and enable distance check. */
2533 return dist_sq < radius_sq || true;
2534}
2535
2536bool node_in_box(const float4x4 &mat,
2537 const Bounds<float3> &bounds,
2538 const float3 &brush_center,
2539 const float3 &brush_half_lengths,
2540 const bool test_z_axis)
2541{
2542 const float3 node_center = math::transform_point(mat, (bounds.max + bounds.min) * 0.5f);
2543 const float3 center_diff = brush_center - node_center;
2544
2545 const float3 node_half_lengths = (bounds.max - bounds.min) * 0.5f;
2546
2547 /* Gets the axes of object space described in brush space. */
2548 const float3 &node_x_axis = mat.x_axis();
2549 const float3 &node_y_axis = mat.y_axis();
2550 const float3 &node_z_axis = mat.z_axis();
2551
2552 auto axis_separates_boxes = [&](const float3 &axis) {
2553 const float radius1 = math::dot(math::abs(axis), brush_half_lengths);
2554 const float radius2 = math::abs(math::dot(axis, node_x_axis)) * node_half_lengths.x +
2555 math::abs(math::dot(axis, node_y_axis)) * node_half_lengths.y +
2556 math::abs(math::dot(axis, node_z_axis)) * node_half_lengths.z;
2557
2558 const float projection = math::abs(math::dot(center_diff, axis));
2559 return projection > radius1 + radius2;
2560 };
2561
2562 const blender::Array<float3> brush_axes = test_z_axis ?
2563 blender::Array<float3>{float3{1.0f, 0.0f, 0.0f},
2564 float3{0.0f, 1.0f, 0.0f},
2565 float3{0.0f, 0.0f, 1.0f}} :
2566 blender::Array<float3>{float3{1.0f, 0.0f, 0.0f},
2567 float3{0.0f, 1.0f, 0.0f}};
2568
2569 const std::array<float3, 3> node_axes = {node_x_axis, node_y_axis, node_z_axis};
2570
2576
2577 /* 1. Test axes aligned with the region affected by the brush. */
2578 for (const float3 &axis : brush_axes) {
2579 if (axis_separates_boxes(axis)) {
2580 return false;
2581 }
2582 }
2583
2584 /* 2. Test axes aligned with the node bounds. */
2585 for (const float3 &axis : node_axes) {
2586 if (axis_separates_boxes(float3(axis.x, axis.y, axis.z * test_z_axis))) {
2587 return false;
2588 }
2589 }
2590
2591 /* 3. Test all their cross products. */
2592 if (test_z_axis) {
2593 for (const float3 &brush_axis : brush_axes) {
2594 for (const float3 &node_axis : node_axes) {
2595 if (axis_separates_boxes(math::cross(brush_axis, node_axis))) {
2596 return false;
2597 }
2598 }
2599 }
2600 }
2601
2602 /* None of the axes separates the boxes: they intersect. */
2603 return true;
2604}
2605
2607{
2608 return node_in_box(mat, bounds, float3(0.0f, 0.0f, 0.5f), float3(1.0f, 1.0f, 0.5f), true);
2609}
2610
2611static IndexMask pbvh_gather_cursor_update(Object &ob, bool use_original, IndexMaskMemory &memory)
2612{
2615 const float3 center = ss.cache ? ss.cache->location_symm : ss.cursor_location;
2616 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2617 return node_in_sphere(node, center, ss.cursor_radius, use_original);
2618 });
2619}
2620
2623 const Brush &brush,
2624 const bool use_original,
2625 const float radius_scale,
2626 IndexMaskMemory &memory)
2627{
2630
2631 const float3 center = ss.cache->location_symm;
2632 const float radius_sq = math::square(ss.cache->radius * radius_scale);
2633 const bool ignore_ineffective = brush.sculpt_brush_type != SCULPT_BRUSH_TYPE_MASK;
2634 switch (brush.falloff_shape) {
2636 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2637 if (ignore_ineffective && node_fully_masked_or_hidden(node)) {
2638 return false;
2639 }
2640 return node_in_sphere(node, center, radius_sq, use_original);
2641 });
2642 }
2643
2646 center, ss.cache->view_normal_symm);
2647 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2648 if (ignore_ineffective && node_fully_masked_or_hidden(node)) {
2649 return false;
2650 }
2651 return node_in_cylinder(ray_dist_precalc, node, radius_sq, use_original);
2652 });
2653 }
2654 }
2655
2656 return {};
2657}
2658
2660 const Brush &brush,
2661 const float4x4 &brush_local_mat,
2662 const bool use_original,
2663 IndexMaskMemory &memory)
2664{
2666 if (math::is_zero(brush_local_mat)) {
2667 BLI_assert_msg(0, "Unable to calculate cube test with empty 'brush_local_mat'");
2668 return {};
2669 }
2670 const bool ignore_ineffective = brush.sculpt_brush_type != SCULPT_BRUSH_TYPE_MASK;
2671
2672 switch (brush.falloff_shape) {
2674 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2675 if (ignore_ineffective && node_fully_masked_or_hidden(node)) {
2676 return false;
2677 }
2678 const Bounds<float3> &bounds = use_original ? node.bounds_orig() : node.bounds();
2679 return node_in_box(brush_local_mat, bounds);
2680 });
2681
2683 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2684 if (ignore_ineffective && node_fully_masked_or_hidden(node)) {
2685 return false;
2686 }
2687 const Bounds<float3> &bounds = use_original ? node.bounds_orig() : node.bounds();
2688 return node_in_box(brush_local_mat, bounds, float3(0.0f), float3(1.0f, 1.0f, 1.0f), false);
2689 });
2690 }
2691
2693 return {};
2694}
2695
2697 const eBrushFalloffShape falloff_shape,
2698 const bool use_original,
2699 const float3 &location,
2700 const float radius_sq,
2701 const std::optional<float3> &ray_direction,
2702 IndexMaskMemory &memory)
2703{
2705 switch (falloff_shape) {
2707 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2709 return false;
2710 }
2711 return node_in_sphere(node, location, radius_sq, use_original);
2712 });
2713 }
2714
2716 BLI_assert(ray_direction);
2718 location, ray_direction.value_or(float3(0.0f)));
2719 return bke::pbvh::search_nodes(pbvh, memory, [&](const bke::pbvh::Node &node) {
2721 return false;
2722 }
2723 return node_in_cylinder(ray_dist_precalc, node, radius_sq, use_original);
2724 });
2725 }
2726 }
2728 return {};
2729}
2730
2731/* Calculate primary direction of movement for many brushes. */
2732static float3 calc_sculpt_normal(const Depsgraph &depsgraph,
2733 const Sculpt &sd,
2734 Object &ob,
2735 const IndexMask &node_mask)
2736{
2738 const SculptSession &ss = *ob.runtime->sculpt_session;
2739 switch (brush.sculpt_plane) {
2741 return calc_area_normal(depsgraph, brush, ob, node_mask).value_or(float3(0));
2743 return ss.cache->view_normal;
2744 case SCULPT_DISP_DIR_X:
2745 return float3(1, 0, 0);
2746 case SCULPT_DISP_DIR_Y:
2747 return float3(0, 1, 0);
2748 case SCULPT_DISP_DIR_Z:
2749 return float3(0, 0, 1);
2750 }
2752 return {};
2753}
2754
2755static void update_sculpt_normal(const Depsgraph &depsgraph,
2756 const Sculpt &sd,
2757 Object &ob,
2758 const brushes::CursorSampleResult &cursor_sample_result)
2759{
2762 StrokeCache &cache = *ob.runtime->sculpt_session->cache;
2763 /* Grab brush does not update the sculpt normal during a stroke. */
2764 const bool update_normal = !(brush.flag & BRUSH_ORIGINAL_NORMAL) &&
2765 !(brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_GRAB) &&
2766 !(brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_THUMB &&
2767 !(brush.stroke_method == BRUSH_STROKE_ANCHORED)) &&
2768 !(brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_ELASTIC_DEFORM) &&
2769 !(brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SNAKE_HOOK &&
2771 0.0f);
2772
2773 if (cache.mirror_symmetry_pass == 0 && cache.radial_symmetry_pass == 0 &&
2774 (stroke_is_first_brush_step_of_symmetry_pass(cache) || update_normal))
2775 {
2776 if (cursor_sample_result.plane_normal) {
2777 cache.sculpt_normal = *cursor_sample_result.plane_normal;
2778 }
2779 else {
2780 cache.sculpt_normal = calc_sculpt_normal(depsgraph, sd, ob, cursor_sample_result.node_mask);
2781 if (brush.falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
2784 }
2785 }
2787 }
2788 else {
2791 }
2792}
2793
2795 const float center[3],
2796 const float screen_dir[2],
2797 float r_local_dir[3])
2798{
2799 Object &ob = *vc.obact;
2800 float loc[3];
2801
2802 mul_v3_m4v3(loc, ob.object_to_world().ptr(), center);
2803 const float zfac = ED_view3d_calc_zfac(vc.rv3d, loc);
2804
2805 ED_view3d_win_to_delta(vc.region, screen_dir, zfac, r_local_dir);
2806 normalize_v3(r_local_dir);
2807
2808 add_v3_v3(r_local_dir, ob.loc);
2809 mul_m4_v3(ob.world_to_object().ptr(), r_local_dir);
2810}
2811
2813 const float3 &tip_location,
2814 const float angle)
2815{
2816 Object &ob = *vc.obact;
2817
2818 /* Ensure `ob.world_to_object` is up to date. */
2819 invert_m4_m4(ob.runtime->world_to_object.ptr(), ob.object_to_world().ptr());
2820
2821 /* By convention, motion direction points down the brush's Y axis, the angle represents the X
2822 * axis, normal is a 90 deg CCW rotation of the motion direction. */
2823 const float2 motion_normal_screen = {cosf(angle), sinf(angle)};
2824 /* Convert view's brush normal direction to object-space. */
2825 float3 motion_normal_local;
2826 calc_local_from_screen(vc, tip_location, motion_normal_screen, motion_normal_local);
2827 return motion_normal_local;
2828}
2829
2830void calc_brush_local_mat(const float3 &tip_normal,
2831 const float3 &motion_normal_local,
2832 const float3 &tip_location,
2833 const float radius,
2834 float local_mat[4][4],
2835 float local_mat_inv[4][4])
2836{
2837 float tmat[4][4];
2838 float mat[4][4];
2839 float scale[4][4];
2840 float v[3];
2841
2842 /* Initialize last column of matrix. */
2843 mat[0][3] = 0.0f;
2844 mat[1][3] = 0.0f;
2845 mat[2][3] = 0.0f;
2846 mat[3][3] = 1.0f;
2847
2848 /* Calculate the movement direction for the local matrix.
2849 * Note that there is a deliberate prioritization here: Our calculations are
2850 * designed such that the _motion vector_ gets projected into the tangent space;
2851 * in most cases this will be more intuitive than projecting the transverse
2852 * direction (which is orthogonal to the motion direction and therefore less
2853 * apparent to the user).
2854 * The Y-axis of the brush-local frame has to lie in the intersection of the tangent plane
2855 * and the motion plane. */
2856 cross_v3_v3v3(v, tip_normal, motion_normal_local);
2857 normalize_v3_v3(mat[1], v);
2858 /* Get other axes. */
2859 cross_v3_v3v3(mat[0], mat[1], tip_normal);
2860 copy_v3_v3(mat[2], tip_normal);
2861
2862 /* Set location. */
2863 copy_v3_v3(mat[3], tip_location);
2864
2865 /* Scale by brush radius. */
2866 normalize_m4(mat);
2867 scale_m4_fl(scale, radius);
2868 mul_m4_m4m4(tmat, mat, scale);
2869
2870 /* Return tmat as is (for converting from local area coords to model-space coords). */
2871 copy_m4_m4(local_mat_inv, tmat);
2872 /* Return inverse (for converting from model-space coords to local area coords). */
2873 invert_m4_m4(local_mat, tmat);
2874}
2875
2877 const float4x4 &view_inverse,
2878 const float3 &normal,
2879 const float2 &tilt,
2880 const float tilt_strength)
2881{
2882 const float3 world_space = math::transform_direction(object.object_to_world(), normal);
2883
2884 /* Tweaked based on initial user feedback, with a value of 1.0, higher brush tilt strength
2885 * lead to the stroke surface direction becoming inverted due to extreme rotations. */
2886 constexpr float tilt_sensitivity = 0.7f;
2887 const float rot_max = M_PI_2 * tilt_strength * tilt_sensitivity;
2888 const float3 normal_tilt_y = math::rotate_direction_around_axis(
2889 world_space, view_inverse.x_axis(), tilt.y * rot_max);
2890 const float3 normal_tilt_xy = math::rotate_direction_around_axis(
2891 normal_tilt_y, view_inverse.y_axis(), tilt.x * rot_max);
2892
2893 return math::normalize(math::transform_direction(object.world_to_object(), normal_tilt_xy));
2894}
2895
2897 const StrokeCache &cache,
2898 const float tilt_strength)
2899{
2900 return tilt_apply_to_normal(
2901 *cache.vc->obact, float4x4(cache.vc->rv3d->viewinv), normal, cache.tilt, tilt_strength);
2902}
2903
2905{
2906 return tilt_apply_to_normal(ss.cache->sculpt_normal_symm, *ss.cache, brush.tilt_strength_factor);
2907}
2908
2909static void update_brush_local_mat(const Sculpt &sd, Object &ob)
2910{
2913
2914 if (cache->mirror_symmetry_pass == 0 && cache->radial_symmetry_pass == 0) {
2917 const float3 tip_normal = eBrushFalloffShape(brush->falloff_shape) ==
2919 cache->sculpt_normal_symm :
2920 cache->view_normal_symm;
2921 const float3 motion_normal = calc_motion_normal_from_angle(
2922 *cache->vc, cache->location_symm, mask_tex->rot + sd.paint.runtime->brush_rotation);
2923 calc_brush_local_mat(tip_normal,
2924 motion_normal,
2925 cache->location_symm,
2926 cache->radius,
2927 cache->brush_local_mat.ptr(),
2928 cache->brush_local_mat_inv.ptr());
2929 }
2930}
2931
2933
2934/* -------------------------------------------------------------------- */
2960
2978
2980{
2982 if (co[0] < 0.0f) {
2983 symm_area |= PAINT_SYMM_AREA_X;
2984 }
2985 if (co[1] < 0.0f) {
2986 symm_area |= PAINT_SYMM_AREA_Y;
2987 }
2988 if (co[2] < 0.0f) {
2989 symm_area |= PAINT_SYMM_AREA_Z;
2990 }
2991 return symm_area;
2992}
2993
2994static void flip_qt_qt(float out[4], const float in[4], const ePaintSymmetryFlags symm)
2995{
2996 float axis[3], angle;
2997
2998 quat_to_axis_angle(axis, &angle, in);
2999 normalize_v3(axis);
3000
3001 if (symm & PAINT_SYMM_X) {
3002 axis[0] *= -1.0f;
3003 angle *= -1.0f;
3004 }
3005 if (symm & PAINT_SYMM_Y) {
3006 axis[1] *= -1.0f;
3007 angle *= -1.0f;
3008 }
3009 if (symm & PAINT_SYMM_Z) {
3010 axis[2] *= -1.0f;
3011 angle *= -1.0f;
3012 }
3013
3015}
3016
3017static void flip_qt(float quat[4], const ePaintSymmetryFlags symm)
3018{
3019 flip_qt_qt(quat, quat, symm);
3020}
3021
3023 const ePaintSymmetryFlags symm,
3024 const ePaintSymmetryAreas symmarea,
3025 const float3 &pivot)
3026{
3027 float3 result = vector;
3028 for (int i = 0; i < 3; i++) {
3029 ePaintSymmetryFlags symm_it = ePaintSymmetryFlags(1 << i);
3030 if (!(symm & symm_it)) {
3031 continue;
3032 }
3033 if (symmarea & ePaintSymmetryAreas(symm_it)) {
3034 result = symmetry_flip(result, symm_it);
3035 }
3036 if (pivot[i] < 0.0f) {
3037 result = symmetry_flip(result, symm_it);
3038 }
3039 }
3040 return result;
3041}
3042
3043void flip_quat_by_symm_area(float quat[4],
3044 const ePaintSymmetryFlags symm,
3045 const ePaintSymmetryAreas symmarea,
3046 const float pivot[3])
3047{
3048 for (int i = 0; i < 3; i++) {
3049 ePaintSymmetryFlags symm_it = ePaintSymmetryFlags(1 << i);
3050 if (!(symm & symm_it)) {
3051 continue;
3052 }
3053 if (symmarea & ePaintSymmetryAreas(symm_it)) {
3054 flip_qt(quat, symm_it);
3055 }
3056 if (pivot[i] < 0.0f) {
3057 flip_qt(quat, symm_it);
3058 }
3059 }
3060}
3061
3062void calc_brush_plane(const Depsgraph &depsgraph,
3063 const Brush &brush,
3064 Object &ob,
3065 const IndexMask &node_mask,
3066 float3 &r_area_no,
3067 float3 &r_area_co)
3068{
3069 const SculptSession &ss = *ob.runtime->sculpt_session;
3070
3071 r_area_no = float3(0.0f);
3072 r_area_co = float3(0.0f);
3073
3074 const bool use_original_plane = (brush.flag & BRUSH_ORIGINAL_PLANE) &&
3075 brush.sculpt_brush_type != SCULPT_BRUSH_TYPE_PLANE;
3076 const bool use_original_normal = (brush.flag & BRUSH_ORIGINAL_NORMAL) &&
3077 brush.sculpt_brush_type != SCULPT_BRUSH_TYPE_PLANE;
3078
3079 const bool needs_recalculation = stroke_is_first_brush_step_of_symmetry_pass(*ss.cache) ||
3080 !use_original_plane || !use_original_normal;
3081
3082 if (stroke_is_main_symmetry_pass(*ss.cache) && needs_recalculation) {
3083 switch (brush.sculpt_plane) {
3085 r_area_no = ss.cache->view_normal;
3086 break;
3087
3088 case SCULPT_DISP_DIR_X:
3089 r_area_no = float3(1.0f, 0.0f, 0.0f);
3090 break;
3091
3092 case SCULPT_DISP_DIR_Y:
3093 r_area_no = float3(0.0f, 1.0f, 0.0f);
3094 break;
3095
3096 case SCULPT_DISP_DIR_Z:
3097 r_area_no = float3(0.0f, 0.0f, 1.0f);
3098 break;
3099
3101 calc_area_normal_and_center(depsgraph, brush, ob, node_mask, r_area_no, r_area_co);
3102 if (brush.falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
3103 project_plane_v3_v3v3(r_area_no, r_area_no, ss.cache->view_normal_symm);
3104 r_area_no = math::normalize(r_area_no);
3105 }
3106 break;
3107 }
3108
3109 /* Flatten center has not been calculated yet if we are not using the area normal. */
3110 if (brush.sculpt_plane != SCULPT_DISP_DIR_AREA) {
3111 BLI_assert(math::is_zero(r_area_co));
3112 calc_area_center(depsgraph, brush, ob, node_mask, r_area_co);
3113 }
3114
3115 if (!stroke_is_first_brush_step_of_symmetry_pass(*ss.cache) && use_original_normal) {
3116 r_area_no = ss.cache->sculpt_normal;
3117 }
3118 else {
3119 ss.cache->sculpt_normal = r_area_no;
3120 }
3121
3122 if (!stroke_is_first_brush_step_of_symmetry_pass(*ss.cache) && use_original_plane) {
3123 r_area_co = ss.cache->last_center;
3124 }
3125 else {
3126 ss.cache->last_center = r_area_co;
3127 }
3128 }
3129 else {
3131
3132 r_area_no = ss.cache->sculpt_normal;
3133 r_area_no = symmetry_flip(r_area_no, ss.cache->mirror_symmetry_pass);
3134 r_area_no = math::transform_direction(ss.cache->symm_rot_mat, r_area_no);
3135
3136 r_area_co = ss.cache->last_center;
3137 r_area_co = symmetry_flip(r_area_co, ss.cache->mirror_symmetry_pass);
3138 r_area_co = math::transform_point(ss.cache->symm_rot_mat, r_area_co);
3139
3140 /* Shift the plane for the current tile. */
3141 r_area_co += ss.cache->plane_offset;
3142 }
3143}
3144
3146{
3147 return brush.flag & BRUSH_OFFSET_PRESSURE ? brush.plane_offset * ss.cache->pressure :
3148 brush.plane_offset;
3149}
3150
3152
3153/* -------------------------------------------------------------------- */
3156
3157static void dynamic_topology_update(const Depsgraph &depsgraph,
3158 const Scene &scene,
3159 const Brush &brush,
3160 Object &ob,
3161 PaintModeData * /*paint_mode_data*/)
3162{
3163 Sculpt &sd = *scene.toolsettings->sculpt;
3166
3167 /* Build a list of all nodes that are potentially within the brush's area of influence. */
3168 const bool use_original = brush_type_needs_original(brush.sculpt_brush_type) ? true :
3169 !ss.cache->accum;
3170 constexpr float radius_scale = 1.25f;
3171
3172 IndexMaskMemory memory;
3173 const IndexMask node_mask = pbvh_gather_generic(ob, brush, use_original, radius_scale, memory);
3174 if (node_mask.is_empty()) {
3175 return;
3176 }
3177
3179
3180 /* Free index based vertex info as it will become invalid after modifying the topology during the
3181 * stroke. */
3182 ss.boundary_info_cache.reset();
3183
3185
3186 if (!(sd.flags & SCULPT_DYNTOPO_DETAIL_MANUAL)) {
3188 mode |= PBVH_Subdivide;
3189 }
3190
3191 if ((sd.flags & SCULPT_DYNTOPO_COLLAPSE) ||
3192 (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SIMPLIFY))
3193 {
3194 mode |= PBVH_Collapse;
3195 }
3196 }
3197
3198 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
3199 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::Mask);
3200 }
3201 else {
3202 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::Position);
3203 }
3204 pbvh.tag_positions_changed(node_mask);
3205 pbvh.tag_topology_changed(node_mask);
3206 node_mask.foreach_index([&](const int i) { BKE_pbvh_node_mark_topology_update(nodes[i]); });
3207 node_mask.foreach_index(
3208 [&](const int i) { BKE_pbvh_bmesh_node_save_orig(ss.bm, ss.bm_log, &nodes[i], false); },
3210
3211 float max_edge_len;
3214 }
3215 else if (sd.flags & SCULPT_DYNTOPO_DETAIL_BRUSH) {
3217 }
3218 else {
3220 sd.detail_size, ss.cache->radius, ss.cache->dyntopo_pixel_radius, U.pixelsize);
3221 }
3222 const float min_edge_len = max_edge_len * dyntopo::detail_size::EDGE_LENGTH_MIN_FACTOR;
3223
3225 pbvh,
3226 *ss.bm_log,
3227 mode,
3228 min_edge_len,
3229 max_edge_len,
3230 ss.cache->location_symm,
3232 ss.cache->radius,
3233 (brush.flag & BRUSH_FRONTFACE) != 0,
3234 (brush.falloff_shape != PAINT_FALLOFF_SHAPE_SPHERE));
3235}
3236
3238{
3239 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_ELASTIC_DEFORM) {
3240 /* Elastic deformations in any brush need all nodes to avoid artifacts as the effect
3241 * of the Kelvinlet is not constrained by the radius. */
3242 return true;
3243 }
3244
3245 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_POSE) {
3246 /* Pose needs all nodes because it applies all symmetry iterations at the same time
3247 * and the IK chain can grow to any area of the model. */
3248 /* TODO: This can be optimized by filtering the nodes after calculating the chain. */
3249 return true;
3250 }
3251
3252 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_BOUNDARY) {
3253 /* Boundary needs all nodes because it is not possible to know where the boundary
3254 * deformation is going to be propagated before calculating it. */
3255 /* TODO: after calculating the boundary info in the first iteration, it should be
3256 * possible to get the nodes that have vertices included in any boundary deformation
3257 * and cache them. */
3258 return true;
3259 }
3260
3261 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SNAKE_HOOK &&
3262 brush.snake_hook_deform_type == BRUSH_SNAKE_HOOK_DEFORM_ELASTIC)
3263 {
3264 /* Snake hook in elastic deform type has same requirements as the elastic deform brush. */
3265 return true;
3266 }
3267 return false;
3268}
3269
3271static brushes::CursorSampleResult calc_brush_node_mask(const Depsgraph &depsgraph,
3272 const Sculpt &sd,
3273 Object &ob,
3274 const Brush &brush,
3275 IndexMaskMemory &memory)
3276{
3278 const SculptSession &ss = *ob.runtime->sculpt_session;
3280
3281 const bool use_original = brush_type_needs_original(brush.sculpt_brush_type) ? true :
3282 !ss.cache->accum;
3283 /* Build a list of all nodes that are potentially within the brush's area of influence */
3284
3286 /* These brushes need to update all nodes as they are not constrained by the brush radius */
3287 return {all_leaf_nodes(pbvh, memory), std::nullopt, std::nullopt};
3288 }
3289 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_PLANE) {
3290 return brushes::plane::calc_node_mask(depsgraph, ob, brush, memory);
3291 }
3292 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_CLAY_STRIPS) {
3293 return brushes::clay_strips::calc_node_mask(depsgraph, ob, brush, memory);
3294 }
3295 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_CLOTH) {
3296 return {cloth::brush_affected_nodes_gather(ob, brush, memory), std::nullopt, std::nullopt};
3297 }
3298
3299 float radius_scale = 1.0f;
3300
3301 /* With these options enabled not all required nodes are inside the original brush radius, so
3302 * the brush can produce artifacts in some situations. */
3303 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_DRAW && brush.flag & BRUSH_ORIGINAL_NORMAL) {
3304 radius_scale = 2.0f;
3305 }
3306 /* TODO: Test if gather_generic_cube is good enough for the case above. If true, move the
3307 * following above radius_scale definition. */
3309 float3 tip_normal;
3310
3311 if (brush.falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
3312 /* Calculate sculpt normal from a estimate of the surface normal. */
3313
3314 const float initial_radius = math::square(ss.cache->radius * std::numbers::sqrt3);
3315 const IndexMask initial_node_mask = gather_nodes(pbvh,
3316 eBrushFalloffShape(brush.falloff_shape),
3317 use_original,
3318 ss.cache->location_symm,
3319 initial_radius,
3321 memory);
3322 tip_normal = calc_sculpt_normal(depsgraph, sd, ob, initial_node_mask);
3323
3324 if (math::is_zero(tip_normal)) {
3325 /* The brush local matrix is degenerate: return an empty index mask. */
3326 return {IndexMask(), std::nullopt, std::nullopt};
3327 }
3328 }
3329 else {
3330 tip_normal = ss.cache->view_normal_symm;
3331 }
3332
3334 /* The brush local matrix is degenerate: return an empty index mask. */
3335 return {IndexMask(), std::nullopt, std::nullopt};
3336 }
3337
3338 tip_normal = tilt_apply_to_normal(tip_normal, *ss.cache, brush.tilt_strength_factor);
3339
3340 float4x4 brush_local_mat;
3341 float4x4 brush_local_mat_inv;
3342 calc_brush_local_mat(tip_normal,
3344 ss.cache->location_symm,
3345 ss.cache->radius,
3346 brush_local_mat.ptr(),
3347 brush_local_mat_inv.ptr());
3348
3349 std::optional<float3> plane_normal = brush.falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE ?
3350 std::optional{tip_normal} :
3351 std::nullopt;
3352 return {pbvh_gather_generic_cube(ob, brush, brush_local_mat, use_original, memory),
3353 std::nullopt,
3354 plane_normal};
3355 }
3356
3357 return {pbvh_gather_generic(ob, brush, use_original, radius_scale, memory),
3358 std::nullopt,
3359 std::nullopt};
3360}
3361
3362static void push_undo_nodes(const Depsgraph &depsgraph,
3363 Object &ob,
3364 const Brush &brush,
3365 const IndexMask &node_mask)
3366{
3369 bool need_coords = ss.cache->supports_gravity;
3370
3371 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_DRAW_FACE_SETS) {
3372 /* Draw face sets in smooth mode moves the vertices. */
3374 need_coords = true;
3375 }
3376 else {
3377 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::FaceSet);
3378 }
3379 }
3380 else if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
3381 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::Mask);
3382 }
3383 else if (brush_type_is_paint(brush.sculpt_brush_type)) {
3384 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::Color);
3385 }
3386 else {
3387 need_coords = true;
3388 }
3389
3390 if (need_coords) {
3391 undo::push_nodes(depsgraph, ob, node_mask, undo::Type::Position);
3392 }
3393}
3394
3395static const char *sculpt_brush_type_name(const Brush &brush)
3396{
3397 switch (eBrushSculptType(brush.sculpt_brush_type)) {
3399 return "Draw Brush";
3401 return "Smooth Brush";
3403 return "Crease Brush";
3405 return "Blob Brush";
3407 return "Pinch Brush";
3409 return "Inflate Brush";
3411 return "Grab Brush";
3413 return "Nudge Brush";
3415 return "Thumb Brush";
3417 return "Layer Brush";
3419 return "Clay Brush";
3421 return "Clay Strips Brush";
3423 return "Clay Thumb Brush";
3425 return "Snake Hook Brush";
3427 return "Rotate Brush";
3429 return "Mask Brush";
3431 return "Simplify Brush";
3433 return "Draw Sharp Brush";
3435 return "Elastic Deform Brush";
3437 return "Pose Brush";
3439 return "Multi-plane Scrape Brush";
3441 return "Slide/Relax Brush";
3443 return "Boundary Brush";
3445 return "Cloth Brush";
3447 return "Draw Face Sets";
3449 return "Multires Displacement Eraser";
3451 return "Multires Displacement Smear";
3453 return "Paint Brush";
3455 return "Smear Brush";
3457 return "Plane Brush";
3459 return "Blur Brush";
3461 return "Scene Project Brush";
3462 }
3463
3464 return "Sculpting";
3465}
3466
3467static void do_brush_action(const Depsgraph &depsgraph,
3468 const Scene &scene,
3469 const Brush &brush,
3470 Object &ob,
3471 PaintModeData * /*paint_mode_data*/)
3472{
3475 Sculpt &sd = *scene.toolsettings->sculpt;
3477 IndexMaskMemory memory;
3478
3479 const brushes::CursorSampleResult cursor_sample_result = calc_brush_node_mask(
3480 depsgraph, sd, ob, brush, memory);
3481 const IndexMask node_mask = cursor_sample_result.node_mask;
3482
3483 /* Only act if some verts are inside the brush area. */
3484 if (node_mask.is_empty()) {
3485 return;
3486 }
3487
3488 if (auto_mask::is_enabled(sd.paint, ob, &brush)) {
3489 auto_mask::Cache &cache = auto_mask::stroke_cache_ensure(depsgraph, sd.paint, &brush, ob);
3491 cache.calc_cavity_factor(depsgraph, ob, node_mask);
3492 }
3493 }
3494
3495 push_undo_nodes(depsgraph, ob, brush, node_mask);
3496
3497 /* There are issues with the underlying normals cache / mesh data that can cause the data to
3498 * become out of date.
3499 *
3500 * For EEVEE and Workbench, this is partially mitigated by the fact that the Paint BVH is used
3501 * to signal this update when drawing.
3502 *
3503 * TODO: See #141417
3504 */
3505 const bool external_engine = ss.rv3d && ss.rv3d->view_render != nullptr;
3506 if (external_engine) {
3508 bke::pbvh::update_normals(depsgraph, ob, pbvh);
3509 }
3511 update_sculpt_normal(depsgraph, sd, ob, cursor_sample_result);
3512 }
3513
3514 update_brush_local_mat(sd, ob);
3515
3516 /* Cube tipped brushes cannot run on the first brush step due to needing the screen delta to
3517 * calculate tip alignment. */
3520 {
3521 return;
3522 }
3523
3524 if (brush.deform_target == BRUSH_DEFORM_TARGET_CLOTH_SIM) {
3525 if (!ss.cache->cloth_sim) {
3527 depsgraph, ob, 1.0f, 0.0f, 0.0f, false, true);
3528 }
3531 ob,
3532 node_mask,
3533 *ss.cache->cloth_sim,
3534 ss.cache->location_symm,
3535 std::numeric_limits<float>::max());
3536 }
3537
3538 /* Apply one type of brush action. */
3539 switch (brush.sculpt_brush_type) {
3542 brushes::do_draw_vector_displacement_brush(depsgraph, sd, ob, node_mask);
3543 }
3544 else {
3545 brushes::do_draw_brush(depsgraph, sd, ob, node_mask);
3546 }
3547 break;
3548 }
3550 if (brush.smooth_deform_type == BRUSH_SMOOTH_DEFORM_LAPLACIAN) {
3551 /* NOTE: The enhance brush needs to initialize its state on the first brush step. The
3552 * stroke strength can become 0 during the stroke, but it can not change sign (the sign is
3553 * determined in the beginning of the stroke). So here it is important to not switch to
3554 * enhance brush in the middle of the stroke. */
3556 /* Invert mode, intensify details. */
3557 brushes::do_enhance_details_brush(depsgraph, sd, ob, node_mask);
3558 }
3559 else {
3561 depsgraph, sd, ob, node_mask, std::clamp(ss.cache->bstrength, 0.0f, 1.0f));
3562 }
3563 }
3564 else if (brush.smooth_deform_type == BRUSH_SMOOTH_DEFORM_SURFACE) {
3565 brushes::do_surface_smooth_brush(depsgraph, sd, ob, node_mask);
3566 }
3567 break;
3569 brushes::do_crease_brush(depsgraph, sd, ob, node_mask);
3570 break;
3572 brushes::do_blob_brush(depsgraph, sd, ob, node_mask);
3573 break;
3575 brushes::do_pinch_brush(depsgraph, sd, ob, node_mask);
3576 break;
3578 brushes::do_inflate_brush(depsgraph, sd, ob, node_mask);
3579 break;
3581 brushes::do_grab_brush(depsgraph, sd, ob, node_mask);
3582 break;
3584 brushes::do_rotate_brush(depsgraph, sd, ob, node_mask);
3585 break;
3587 brushes::do_snake_hook_brush(depsgraph, sd, ob, node_mask);
3588 break;
3590 brushes::do_nudge_brush(depsgraph, sd, ob, node_mask);
3591 break;
3593 brushes::do_thumb_brush(depsgraph, sd, ob, node_mask);
3594 break;
3596 brushes::do_layer_brush(depsgraph, sd, ob, node_mask);
3597 break;
3599 brushes::do_clay_brush(depsgraph, sd, ob, node_mask);
3600 break;
3602 BLI_assert(cursor_sample_result.plane_normal && cursor_sample_result.plane_center);
3604 sd,
3605 ob,
3606 node_mask,
3607 *cursor_sample_result.plane_normal,
3608 *cursor_sample_result.plane_center);
3609 break;
3611 brushes::do_multiplane_scrape_brush(depsgraph, sd, ob, node_mask);
3612 break;
3614 brushes::do_clay_thumb_brush(depsgraph, sd, ob, node_mask);
3615 break;
3617 switch (BrushMaskTool(brush.mask_tool)) {
3618 case BRUSH_MASK_DRAW:
3619 brushes::do_mask_brush(depsgraph, sd, ob, node_mask);
3620 break;
3621 case BRUSH_MASK_SMOOTH:
3622 brushes::do_smooth_mask_brush(depsgraph, sd, ob, node_mask, ss.cache->bstrength);
3623 break;
3624 }
3625 break;
3627 pose::do_pose_brush(depsgraph, sd, ob, node_mask);
3628 break;
3630 brushes::do_draw_sharp_brush(depsgraph, sd, ob, node_mask);
3631 break;
3633 brushes::do_elastic_deform_brush(depsgraph, sd, ob, node_mask);
3634 break;
3637 brushes::do_topology_relax_brush(depsgraph, sd, ob, node_mask);
3638 }
3639 else {
3640 brushes::do_topology_slide_brush(depsgraph, sd, ob, node_mask);
3641 }
3642 break;
3644 boundary::do_boundary_brush(depsgraph, sd, ob, node_mask);
3645 break;
3647 cloth::do_cloth_brush(depsgraph, sd, ob, node_mask);
3648 break;
3650 if (!ss.cache->toggle_settings.alt_smooth) {
3651 brushes::do_draw_face_sets_brush(depsgraph, sd, ob, node_mask);
3652 }
3653 else {
3654 brushes::do_relax_face_sets_brush(depsgraph, sd, ob, node_mask);
3655 }
3656 break;
3658 brushes::do_displacement_eraser_brush(depsgraph, sd, ob, node_mask);
3659 break;
3661 brushes::do_displacement_smear_brush(depsgraph, sd, ob, node_mask);
3662 break;
3664 color::do_paint_brush(depsgraph, sd, ob, node_mask);
3665 break;
3667 color::do_smear_brush(depsgraph, sd, ob, node_mask);
3668 break;
3670 BLI_assert(cursor_sample_result.plane_normal && cursor_sample_result.plane_center);
3671 brushes::do_plane_brush(depsgraph,
3672 sd,
3673 ob,
3674 node_mask,
3675 *cursor_sample_result.plane_normal,
3676 *cursor_sample_result.plane_center);
3677 break;
3679 color::do_blur_brush(depsgraph, sd, ob, node_mask);
3680 break;
3682 brushes::do_scene_project_brush(depsgraph, sd, ob, node_mask);
3683 break;
3685 break;
3686 }
3687
3688 if (!ELEM(brush.sculpt_brush_type, SCULPT_BRUSH_TYPE_SMOOTH, SCULPT_BRUSH_TYPE_MASK) &&
3689 brush.autosmooth_factor > 0)
3690 {
3692 const float auto_smooth_factor = brush.autosmooth_factor *
3694 brush.curve_auto_smooth, 0, ss.cache->pressure);
3695 brushes::do_smooth_brush(depsgraph, sd, ob, node_mask, auto_smooth_factor);
3696 }
3697 else {
3698 brushes::do_smooth_brush(depsgraph, sd, ob, node_mask, brush.autosmooth_factor);
3699 }
3700 }
3701
3704 depsgraph, sd, ob, node_mask, brush.topology_rake_factor);
3705 }
3706
3707 /* The cloth brush adds the gravity as a regular force and it is processed in the solver. */
3708 if (ss.cache->supports_gravity && brush.sculpt_brush_type != SCULPT_BRUSH_TYPE_CLOTH) {
3709 brushes::do_gravity_brush(depsgraph, sd, ob, node_mask);
3710 }
3711
3712 if (brush.deform_target == BRUSH_DEFORM_TARGET_CLOTH_SIM) {
3714 cloth::sim_activate_nodes(ob, *ss.cache->cloth_sim, node_mask);
3715 cloth::do_simulation_step(depsgraph, sd, ob, *ss.cache->cloth_sim, node_mask);
3716 }
3717 }
3718
3719 /* Update average stroke position. */
3720 const float3 world_location = math::project_point(ob.object_to_world(), ss.cache->location);
3721
3722 bke::paint::stroke_track_location(sd.paint, world_location);
3723}
3724
3726 const ePaintSymmetryFlags symm,
3727 const char axis,
3728 const float angle)
3729{
3730 cache.location_symm = symmetry_flip(cache.location, symm);
3731 cache.last_location_symm = symmetry_flip(cache.last_location, symm);
3732 cache.grab_delta_symm = symmetry_flip(cache.grab_delta, symm);
3733 cache.view_normal_symm = symmetry_flip(cache.view_normal, symm);
3734
3738
3739 /* XXX This reduces the length of the grab delta if it approaches the line of symmetry
3740 * XXX However, a different approach appears to be needed. */
3741#if 0
3742 if (sd->paint.symmetry_flags & PAINT_SYMMETRY_FEATHER) {
3743 float frac = 1.0f / max_overlap_count(sd);
3744 float reduce = (feather - frac) / (1.0f - frac);
3745
3746 printf("feather: %f frac: %f reduce: %f\n", feather, frac, reduce);
3747
3748 if (frac < 1.0f) {
3749 mul_v3_fl(cache.grab_delta_symmetry, reduce);
3750 }
3751 }
3752#endif
3753
3756 zero_v3(cache.plane_offset);
3757
3758 /* Expects XYZ. */
3759 if (axis) {
3760 rotate_m4(cache.symm_rot_mat.ptr(), axis, angle);
3761 rotate_m4(cache.symm_rot_mat_inv.ptr(), axis, -angle);
3762 }
3763
3764 mul_m4_v3(cache.symm_rot_mat.ptr(), cache.location_symm);
3765 mul_m4_v3(cache.symm_rot_mat.ptr(), cache.grab_delta_symm);
3766
3768
3769 if (cache.supports_gravity) {
3772 }
3773
3774 if (cache.rake_rotation) {
3775 float4 new_quat;
3776 float4 existing(cache.rake_rotation->w,
3777 cache.rake_rotation->x,
3778 cache.rake_rotation->y,
3779 cache.rake_rotation->z);
3780 flip_qt_qt(new_quat, existing, symm);
3781 cache.rake_rotation_symm = math::Quaternion(new_quat);
3782 }
3783}
3784
3789static void sculpt_fix_noise_tear(const Sculpt &sd, Object &ob)
3790{
3794
3795 if (ss.multires_modifier && mtex->tex && mtex->tex->type == TEX_NOISE) {
3797 }
3798}
3799
3801{
3803 return ob && ob->mode & OB_MODE_SCULPT;
3804}
3805
3810
3815
3824{
3827 ScrArea *area = CTX_wm_area(C);
3828 ARegion *region = CTX_wm_region(C);
3829
3830 if (paint && ob && BKE_paint_brush(paint) &&
3831 (area && ELEM(area->spacetype, SPACE_VIEW3D, SPACE_IMAGE)) &&
3832 (region && region->regiontype == RGN_TYPE_WINDOW))
3833 {
3834 bToolRef *tref = area->runtime.tool;
3835 if (tref && tref->runtime && tref->runtime->keymap[0]) {
3836 std::array<wmOperatorType *, 7> trim_operators = {
3837 WM_operatortype_find("SCULPT_OT_trim_box_gesture", false),
3838 WM_operatortype_find("SCULPT_OT_trim_lasso_gesture", false),
3839 WM_operatortype_find("SCULPT_OT_trim_line_gesture", false),
3840 WM_operatortype_find("SCULPT_OT_trim_polyline_gesture", false),
3841 WM_operatortype_find("SCULPT_OT_mesh_filter", false),
3842 WM_operatortype_find("SCULPT_OT_cloth_filter", false),
3843 WM_operatortype_find("SCULPT_OT_color_filter", false),
3844 };
3845
3846 return std::any_of(trim_operators.begin(), trim_operators.end(), [tref](wmOperatorType *ot) {
3847 PointerRNA ptr;
3848 return WM_toolsystem_ref_properties_get_from_operator(tref, ot, &ptr);
3849 });
3850 }
3851 }
3852 return false;
3853}
3854
3859
3860StrokeCache::StrokeCache() = default;
3861
3863{
3864 if (this->dial) {
3865 BLI_dial_free(this->dial);
3866 }
3867}
3868
3869} // namespace ed::sculpt_paint
3870
3871enum class StrokeFlags : uint8_t {
3875};
3876
3877namespace ed::sculpt_paint {
3878
3879/* Initialize mirror modifier clipping. */
3880static void sculpt_init_mirror_clipping(const Object &ob, const SculptSession &ss)
3881{
3883
3884 for (ModifierData &md : ob.modifiers) {
3885 if (!(md.type == eModifierType_Mirror && (md.mode & eModifierMode_Realtime))) {
3886 continue;
3887 }
3888 MirrorModifierData *mmd = reinterpret_cast<MirrorModifierData *>(&md);
3889
3890 if (!(mmd->flag & MOD_MIR_CLIPPING)) {
3891 continue;
3892 }
3893 /* Check each axis for mirroring. */
3894 for (int i = 0; i < 3; i++) {
3895 if (!(mmd->flag & (MOD_MIR_AXIS_X << i))) {
3896 continue;
3897 }
3898 /* Enable sculpt clipping. */
3900
3901 /* Update the clip tolerance. */
3902 ss.cache->mirror_modifier_clip.tolerance[i] = std::max(
3903 mmd->tolerance, ss.cache->mirror_modifier_clip.tolerance[i]);
3904
3905 /* Store matrix for mirror object clipping. */
3906 if (mmd->mirror_ob) {
3907 const float4x4 mirror_ob_inv = math::invert(mmd->mirror_ob->object_to_world());
3909 mirror_ob_inv.ptr(),
3910 ob.object_to_world().ptr());
3911 }
3912 }
3913 }
3915}
3916
3917static void smooth_brush_toggle_on(Main *bmain,
3918 Paint *paint,
3919 StrokeToggleSettings &toggle_settings)
3920{
3921 Brush *cur_brush = BKE_paint_brush(paint);
3922
3923 if (cur_brush->sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
3924 toggle_settings.original_brush_mask_tool = BrushMaskTool(cur_brush->mask_tool);
3925 cur_brush->mask_tool = BRUSH_MASK_SMOOTH;
3926 return;
3927 }
3928
3929 if (ELEM(cur_brush->sculpt_brush_type,
3932 {
3933 /* Do nothing, this brush has its own smooth mode. */
3934 return;
3935 }
3936
3937 /* Switch to the smooth brush if possible. */
3938 const char *target_asset = brush_type_is_paint(cur_brush->sculpt_brush_type) ? "Blur" : "Smooth";
3939 if (!BKE_paint_brush_set_essentials(bmain, paint, target_asset)) {
3940 BKE_paint_brush_set(paint, cur_brush);
3941 CLOG_WARN(&LOG, "Unable to switch to the '%s' essentials brush asset", target_asset);
3942 toggle_settings.original_active_brush = nullptr;
3943 return;
3944 }
3945
3946 Brush *smooth_brush = BKE_paint_brush(paint);
3947 int cur_brush_size = BKE_brush_size_get(paint, cur_brush);
3948
3949 toggle_settings.original_active_brush = cur_brush;
3950
3951 toggle_settings.original_brush_size = BKE_brush_size_get(paint, smooth_brush);
3952 BKE_brush_size_set(paint, smooth_brush, cur_brush_size);
3953}
3954
3956{
3958
3959 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
3961 return;
3962 }
3963
3964 if (ELEM(brush.sculpt_brush_type,
3967 {
3968 /* Do nothing. */
3969 return;
3970 }
3971
3972 /* If saved_active_brush is not set, brush was not switched/affected in
3973 * smooth_brush_toggle_on(). */
3977 cache->toggle_settings.original_active_brush = nullptr;
3978 }
3979}
3980
3981static void mask_brush_toggle_on(Main *bmain, Paint *paint, StrokeToggleSettings &toggle_settings)
3982{
3983 Brush *cur_brush = BKE_paint_brush(paint);
3984
3985 /* User is already using Mask brush */
3986 if (cur_brush->sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
3987 toggle_settings.original_brush_mask_tool = BrushMaskTool(cur_brush->mask_tool);
3988 toggle_settings.original_active_brush = nullptr;
3989 return;
3990 }
3991
3992 /* Save current brush */
3993 toggle_settings.original_active_brush = cur_brush;
3994
3995 /* Switch to Mask essentials brush */
3996 if (!BKE_paint_brush_set_essentials(bmain, paint, "Mask")) {
3997 BKE_paint_brush_set(paint, cur_brush);
3998 toggle_settings.original_active_brush = nullptr;
3999 CLOG_WARN(&LOG, "Unable to switch to the 'Mask' essentials brush asset");
4000 return;
4001 }
4002
4003 Brush *mask_brush = BKE_paint_brush(paint);
4004
4005 /* Match brush size */
4006 const int cur_brush_size = BKE_brush_size_get(paint, cur_brush);
4007 toggle_settings.original_brush_size = BKE_brush_size_get(paint, mask_brush);
4008 BKE_brush_size_set(paint, mask_brush, cur_brush_size);
4009}
4010
4012{
4014
4015 /* User was already using mask brush */
4016 if (cache->toggle_settings.original_active_brush == nullptr) {
4017 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_MASK) {
4019 }
4020 return;
4021 }
4022
4023 /* Restore previous brush */
4026 cache->toggle_settings.original_active_brush = nullptr;
4027}
4028
4029static void init_scene_project_brush_targets(const Depsgraph &depsgraph,
4030 ViewLayer &view_layer,
4031 const View3D &v3d,
4032 const Object &active_object,
4033 StrokeCache &cache)
4034{
4035 cache.project_targets.clear();
4036
4037 for (Base &base : *BKE_view_layer_object_bases_get(&view_layer)) {
4038 const bool is_active_object = base.object == &active_object;
4039 const bool is_hidden = !BKE_base_is_visible(&v3d, &base);
4040 Object *object = DEG_get_evaluated(&depsgraph, base.object);
4041
4042 if (is_active_object || object->type != OB_MESH || is_hidden) {
4043 continue;
4044 }
4045
4046 const Mesh *mesh_eval = BKE_object_get_evaluated_mesh(object);
4047 if (!mesh_eval || mesh_eval->faces_num == 0) {
4048 continue;
4049 }
4050 const bke::bvh::Tree &tree_data = mesh_eval->bvh_tris();
4051 const float4x4 active_to_target_matrix = object->world_to_object() *
4052 active_object.object_to_world();
4053
4054 ProjectBrushTarget project_target{&tree_data, active_to_target_matrix};
4055 cache.project_targets.append(std::move(project_target));
4056 }
4057}
4058
4060 const StrokeCache &cache,
4061 float initial_size)
4062{
4063 const float pressure_eval = BKE_curvemapping_evaluateF(brush.curve_size, 0, cache.pressure);
4064 switch (brush.sculpt_brush_type) {
4066 return max_ff(initial_size * 0.20f, initial_size * pow3f(pressure_eval));
4068 return max_ff(initial_size * 0.30f, initial_size * powf(pressure_eval, 1.5f));
4070 float clay_stabilized_pressure = brushes::clay_thumb_get_stabilized_pressure(cache);
4071 return initial_size *
4072 BKE_curvemapping_evaluateF(brush.curve_size, 0, clay_stabilized_pressure);
4073 }
4074 default:
4075 return initial_size * pressure_eval;
4076 }
4077}
4078
4079/* In these brushes the grab delta is calculated always from the initial stroke location, which is
4080 * generally used to create grab deformations. */
4082{
4083 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SMEAR &&
4084 (brush.stroke_method == BRUSH_STROKE_ANCHORED))
4085 {
4086 return true;
4087 }
4088
4089 if (ELEM(brush.sculpt_brush_type,
4095 {
4096 return true;
4097 }
4098 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_CLOTH &&
4099 brush.cloth_deform_type == BRUSH_CLOTH_DEFORM_GRAB)
4100 {
4101 return true;
4102 }
4103 return false;
4104}
4105
4106/* In these brushes the grab delta is calculated from the previous stroke location, which is used
4107 * to calculate to orientate the brush tip and deformation towards the stroke direction. */
4109{
4110 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_CLOTH) {
4111 return brush.cloth_deform_type != BRUSH_CLOTH_DEFORM_GRAB;
4112 }
4113 return ELEM(brush.sculpt_brush_type,
4120}
4121
4122static void brush_delta_update(const Depsgraph &depsgraph,
4123 Paint &paint,
4124 const Object &ob,
4125 const Brush &brush)
4126{
4127 bke::PaintRuntime &paint_runtime = *paint.runtime;
4130 StrokeCache *cache = ss.cache;
4131 const float mval[2] = {
4132 cache->mouse_event[0],
4133 cache->mouse_event[1],
4134 };
4135 int brush_type = brush.sculpt_brush_type;
4136
4137 if (!ELEM(brush_type,
4154 {
4155 return;
4156 }
4157 float grab_location[3], imat[4][4], delta[3], loc[3];
4158
4160 if (brush_type == SCULPT_BRUSH_TYPE_GRAB && brush.flag & BRUSH_GRAB_ACTIVE_VERTEX &&
4161 !std::holds_alternative<std::monostate>(ss.active_vert()))
4162 {
4163 if (pbvh.type() == bke::pbvh::Type::Mesh) {
4164 const Span<float3> positions = vert_positions_for_grab_active_get(depsgraph, ob);
4165 cache->orig_grab_location = positions[std::get<int>(ss.active_vert())];
4166 }
4167 else {
4168 cache->orig_grab_location = ss.active_vert_position(depsgraph, ob);
4169 }
4170 }
4171 else {
4172 copy_v3_v3(cache->orig_grab_location, cache->location);
4173 }
4174 }
4175 else if (brush_type == SCULPT_BRUSH_TYPE_SNAKE_HOOK ||
4176 (brush_type == SCULPT_BRUSH_TYPE_CLOTH &&
4177 brush.cloth_deform_type == BRUSH_CLOTH_DEFORM_SNAKE_HOOK))
4178 {
4179 add_v3_v3(cache->location, cache->grab_delta);
4180 }
4181
4182 /* Compute 3d coordinate at same z from original location + mval. */
4183 mul_v3_m4v3(loc, ob.object_to_world().ptr(), cache->orig_grab_location);
4184 ED_view3d_win_to_3d(cache->vc->v3d, cache->vc->region, loc, mval, grab_location);
4185
4186 /* Compute delta to move verts by. */
4189 sub_v3_v3v3(delta, grab_location, cache->old_grab_location);
4190 invert_m4_m4(imat, ob.object_to_world().ptr());
4191 mul_mat3_m4_v3(imat, delta);
4192 add_v3_v3(cache->grab_delta, delta);
4193 }
4195 if (brush.stroke_method == BRUSH_STROKE_ANCHORED) {
4196 float orig[3];
4197 mul_v3_m4v3(orig, ob.object_to_world().ptr(), cache->orig_grab_location);
4198 sub_v3_v3v3(cache->grab_delta, grab_location, orig);
4199 }
4200 else {
4201 sub_v3_v3v3(cache->grab_delta, grab_location, cache->old_grab_location);
4202 }
4203 invert_m4_m4(imat, ob.object_to_world().ptr());
4204 mul_mat3_m4_v3(imat, cache->grab_delta);
4205 }
4206 else {
4207 /* Use for 'Brush.topology_rake_factor'. */
4208 sub_v3_v3v3(cache->grab_delta, grab_location, cache->old_grab_location);
4209 }
4210 }
4211 else {
4212 zero_v3(cache->grab_delta);
4213 }
4214
4215 if (brush.falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
4217 }
4218
4219 copy_v3_v3(cache->old_grab_location, grab_location);
4220
4222 /* Location stays the same for finding vertices in brush radius. */
4223 copy_v3_v3(cache->location, cache->orig_grab_location);
4224
4225 paint_runtime.draw_anchored = true;
4226 copy_v2_v2(paint_runtime.anchored_initial_mouse, cache->initial_mouse);
4227 paint_runtime.anchored_size = paint_runtime.pixel_radius;
4228 }
4229
4230 /* Handle 'rake' */
4231 cache->rake_rotation = std::nullopt;
4232 cache->rake_rotation_symm = std::nullopt;
4233 invert_m4_m4(imat, ob.object_to_world().ptr());
4234 mul_mat3_m4_v3(imat, grab_location);
4235
4237 copy_v3_v3(cache->rake_data.follow_co, grab_location);
4238 }
4239
4241 return;
4242 }
4244
4245 if (!is_zero_v3(cache->grab_delta)) {
4246 const float eps = 0.00001f;
4247
4248 float v1[3], v2[3];
4249
4250 copy_v3_v3(v1, cache->rake_data.follow_co);
4252 sub_v3_v3(v2, cache->grab_delta);
4253
4254 sub_v3_v3(v1, grab_location);
4255 sub_v3_v3(v2, grab_location);
4256
4257 if ((normalize_v3(v2) > eps) && (normalize_v3(v1) > eps) && (len_squared_v3v3(v1, v2) > eps)) {
4258 const float rake_dist_sq = len_squared_v3v3(cache->rake_data.follow_co, grab_location);
4259 const float rake_fade = (rake_dist_sq > square_f(cache->rake_data.follow_dist)) ?
4260 1.0f :
4261 sqrtf(rake_dist_sq) / cache->rake_data.follow_dist;
4262
4263 const math::AxisAngle between_vecs(v1, v2);
4264 const math::AxisAngle rotated(between_vecs.axis(),
4265 between_vecs.angle() * brush.rake_factor * rake_fade);
4266 cache->rake_rotation = math::to_quaternion(rotated);
4267 }
4268 }
4269 rake_data_update(&cache->rake_data, grab_location);
4270}
4271
4273{
4274 cache.paint_brush.flow = brush.flow;
4275 if (brush.paint_flags & BRUSH_PAINT_FLOW_PRESSURE) {
4276 cache.paint_brush.flow *= brush.paint_flags & BRUSH_PAINT_FLOW_PRESSURE_INVERT ?
4277 1.0f - cache.pressure :
4278 cache.pressure;
4279 }
4280
4281 cache.paint_brush.wet_mix = brush.wet_mix;
4282 if (brush.paint_flags & BRUSH_PAINT_WET_MIX_PRESSURE) {
4283 cache.paint_brush.wet_mix *= brush.paint_flags & BRUSH_PAINT_WET_MIX_PRESSURE_INVERT ?
4284 1.0f - cache.pressure :
4285 cache.pressure;
4286
4287 /* This makes wet mix more sensible in higher values, which allows to create brushes that have
4288 * a wider pressure range were they only blend colors without applying too much of the brush
4289 * color. */
4290 cache.paint_brush.wet_mix = 1.0f - pow2f(1.0f - cache.paint_brush.wet_mix);
4291 }
4292
4293 cache.paint_brush.wet_persistence = brush.wet_persistence;
4294 if (brush.paint_flags & BRUSH_PAINT_WET_PERSISTENCE_PRESSURE) {
4295 cache.paint_brush.wet_persistence = brush.paint_flags &
4297 1.0f - cache.pressure :
4298 cache.pressure;
4299 }
4300
4301 cache.paint_brush.density = brush.density;
4302 if (brush.paint_flags & BRUSH_PAINT_DENSITY_PRESSURE) {
4303 cache.paint_brush.density = brush.paint_flags & BRUSH_PAINT_DENSITY_PRESSURE_INVERT ?
4304 1.0f - cache.pressure :
4305 cache.pressure;
4306 }
4307}
4308
4309void stroke_modifiers_check(Depsgraph &depsgraph, Object &ob, const Brush *brush)
4310{
4312
4314 BLI_assert(ss.pbvh->type() == bke::pbvh::Type::Mesh);
4316 &depsgraph, &ob, brush_type_is_paint(brush->sculpt_brush_type));
4317 }
4318}
4319
4321{
4323 bool use_origco = false;
4324 Span<float3> origco;
4325 if (rd.use_original && rd.is_mid_stroke) {
4326 switch (pbvh.type()) {
4328 if (const std::optional<OrigPositionData> orig_data =
4330 *rd.object, static_cast<const bke::pbvh::MeshNode &>(node)))
4331 {
4332 use_origco = true;
4333 origco = orig_data->positions;
4334 }
4335 break;
4337 if (const std::optional<OrigPositionData> orig_data = orig_position_data_lookup_grids(
4338 *rd.object, static_cast<const bke::pbvh::GridsNode &>(node)))
4339 {
4340 use_origco = true;
4341 origco = orig_data->positions;
4342 }
4343 break;
4345 use_origco = true;
4346 break;
4347 }
4348 }
4349
4350 if (node.flag_ & bke::pbvh::Node::FullyHidden) {
4351 return;
4352 }
4353
4354 bool hit = false;
4355 switch (pbvh.type()) {
4356 case bke::pbvh::Type::Mesh: {
4357 int mesh_active_vert;
4359 origco,
4360 rd.vert_positions,
4361 rd.faces,
4362 rd.corner_verts,
4363 rd.corner_tris,
4364 rd.hide_poly,
4365 rd.ray_start,
4366 rd.ray_normal,
4367 &rd.isect_precalc,
4368 &rd.depth,
4369 mesh_active_vert,
4371 rd.face_normal);
4372 if (hit) {
4373 rd.active_vertex = mesh_active_vert;
4374 }
4375 break;
4376 }
4378 SubdivCCGCoord grids_active_vert;
4380 static_cast<bke::pbvh::GridsNode &>(node),
4381 origco,
4382 rd.ray_start,
4383 rd.ray_normal,
4384 &rd.isect_precalc,
4385 &rd.depth,
4386 grids_active_vert,
4388 rd.face_normal);
4389 if (hit) {
4390 rd.active_vertex = grids_active_vert.to_index(
4392 }
4393 break;
4394 }
4396 BMVert *bmesh_active_vert;
4398 rd.ray_start,
4399 rd.ray_normal,
4400 &rd.isect_precalc,
4401 &rd.depth,
4402 use_origco,
4403 &bmesh_active_vert,
4404 rd.face_normal);
4405 if (hit) {
4406 rd.active_vertex = bmesh_active_vert;
4407 }
4408 break;
4409 }
4410 }
4411
4412 if (hit) {
4413 rd.hit = true;
4414 *distance = rd.depth;
4415 }
4416}
4417
4419 FindNearestToRayData &fntrd,
4420 float *tmin)
4421{
4423 bool use_origco = false;
4424 Span<float3> origco;
4425 if (fntrd.use_original && fntrd.is_mid_stroke) {
4426 switch (pbvh.type()) {
4428 if (const std::optional<OrigPositionData> orig_data =
4430 *fntrd.object, static_cast<const bke::pbvh::MeshNode &>(node)))
4431 {
4432 use_origco = true;
4433 origco = orig_data->positions;
4434 }
4435 break;
4437 if (const std::optional<OrigPositionData> orig_data = orig_position_data_lookup_grids(
4438 *fntrd.object, static_cast<const bke::pbvh::GridsNode &>(node)))
4439 {
4440 use_origco = true;
4441 origco = orig_data->positions;
4442 }
4443
4444 break;
4446 use_origco = true;
4447 break;
4448 }
4449 }
4450
4452 node,
4453 origco,
4454 use_origco,
4455 fntrd.vert_positions,
4456 fntrd.faces,
4457 fntrd.corner_verts,
4458 fntrd.corner_tris,
4459 fntrd.hide_poly,
4460 fntrd.subdiv_ccg,
4461 fntrd.ray_start,
4462 fntrd.ray_normal,
4463 &fntrd.depth,
4464 &fntrd.dist_sq_to_ray))
4465 {
4466 fntrd.hit = true;
4467 *tmin = fntrd.dist_sq_to_ray;
4468 }
4469}
4470
4472 const float2 &mval,
4473 float3 &r_ray_start,
4474 float3 &r_ray_end,
4475 float3 &r_ray_normal,
4476 bool original)
4477{
4478 Object &ob = *vc->obact;
4479 RegionView3D *rv3d = vc->rv3d;
4480 View3D *v3d = vc->v3d;
4481
4482 /* TODO: what if the segment is totally clipped? (return == 0). */
4484 vc->depsgraph, vc->region, vc->v3d, mval, r_ray_start, r_ray_end, true);
4485
4486 const float4x4 &world_to_object = ob.world_to_object();
4487 r_ray_start = math::transform_point(world_to_object, r_ray_start);
4488 r_ray_end = math::transform_point(world_to_object, r_ray_end);
4489
4490 float dist;
4491 r_ray_normal = math::normalize_and_get_length(r_ray_end - r_ray_start, dist);
4492
4493 if (rv3d->is_persp || RV3D_CLIPPING_ENABLED(v3d, rv3d)) {
4494 return dist;
4495 }
4496
4497 /* Get the view origin without the addition
4498 * of -ray_normal * clip_start that
4499 * ED_view3d_win_to_segment_clipped gave us.
4500 * This is necessary to avoid floating point overflow.
4501 */
4502 float3 view_origin;
4503 ED_view3d_win_to_origin(vc->region, mval, view_origin);
4504 r_ray_start = math::transform_point(world_to_object, view_origin);
4505
4507 bke::pbvh::clip_ray_ortho(pbvh, original, r_ray_start, r_ray_end, r_ray_normal);
4508
4509 return math::distance(r_ray_start, r_ray_end);
4510}
4511
4512std::optional<ActiveElementInfo> active_element_info_get(ViewContext &vc, const float2 &mval)
4513{
4514 Object &ob = *vc.obact;
4516
4518
4520
4521 if (!pbvh || !vc.rv3d ||
4523 {
4524 return std::nullopt;
4525 }
4526
4528
4529 float3 ray_start;
4530 float3 ray_end;
4531 float3 ray_normal;
4532 float depth = raycast_init(&vc, mval, ray_start, ray_end, ray_normal, false);
4533
4534 RaycastData srd{};
4535 srd.object = &ob;
4536 srd.ray_start = ray_start;
4537 srd.ray_normal = ray_normal;
4538 srd.hit = false;
4539 srd.depth = depth;
4540
4541 srd.is_mid_stroke = false;
4542 srd.use_original = false;
4543 if (pbvh->type() == bke::pbvh::Type::Mesh) {
4544 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
4546 srd.faces = mesh.faces();
4547 srd.corner_verts = mesh.corner_verts();
4548 srd.corner_tris = mesh.corner_tris();
4549 const bke::AttributeAccessor attributes = mesh.attributes();
4550 srd.hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
4551 }
4552 else if (pbvh->type() == bke::pbvh::Type::Grids) {
4553 srd.subdiv_ccg = ss.subdiv_ccg;
4554 }
4555
4558 *pbvh,
4559 [&](bke::pbvh::Node &node, float *tmin) { sculpt_raycast_cb(node, srd, tmin); },
4560 ray_start,
4561 ray_normal,
4562 srd.use_original);
4563
4564 /* Cursor is not over the mesh, return default values. */
4565 if (!srd.hit) {
4566 return std::nullopt;
4567 }
4568
4569 ActiveElementInfo info;
4570 info.vert = srd.active_vertex;
4571 switch (pbvh->type()) {
4574 break;
4577 break;
4579 break;
4580 }
4581 return info;
4582}
4583
4584std::optional<CursorGeometryInfo> cursor_geometry_info_update(bContext *C,
4585 const float2 &mval,
4586 const bool use_sampled_normal)
4587{
4588 Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);
4589 const Sculpt &sd = *CTX_data_tool_settings(C)->sculpt;
4590 ViewContext vc = ED_view3d_viewcontext_init(C, depsgraph);
4591 const Base *base = CTX_data_active_base(C);
4592
4594 *depsgraph, sd.paint, &sd, vc, base, mval, use_sampled_normal);
4595}
4596
4597std::optional<CursorGeometryInfo> cursor_geometry_info_update(Depsgraph &depsgraph,
4598 const Paint &paint,
4599 const Sculpt *sd,
4600 ViewContext &vc,
4601 const Base *base,
4602 const float2 &mval,
4603 const bool use_sampled_normal)
4604{
4607 bool original = false;
4609
4610 Object &ob = *vc.obact;
4612
4614
4615 if (!pbvh || !vc.rv3d || !BKE_base_is_visible(vc.v3d, base)) {
4616 ss.clear_active_elements(false);
4617 return std::nullopt;
4618 }
4619
4620 /* bke::pbvh::Tree raycast to get active vertex and face normal. */
4621 float3 ray_start;
4622 float3 ray_end;
4623 float3 ray_normal;
4624 float depth = raycast_init(&vc, mval, ray_start, ray_end, ray_normal, original);
4625 if (sd) {
4626 stroke_modifiers_check(depsgraph, ob, &brush);
4627 }
4628
4629 RaycastData srd{};
4630 srd.use_original = original;
4631 srd.object = &ob;
4632 srd.is_mid_stroke = ob.runtime->sculpt_session->cache != nullptr;
4633 srd.hit = false;
4634 if (pbvh->type() == bke::pbvh::Type::Mesh) {
4635 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
4637 srd.faces = mesh.faces();
4638 srd.corner_verts = mesh.corner_verts();
4639 srd.corner_tris = mesh.corner_tris();
4640 const bke::AttributeAccessor attributes = mesh.attributes();
4641 srd.hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
4642 }
4643 else if (pbvh->type() == bke::pbvh::Type::Grids) {
4644 srd.subdiv_ccg = ss.subdiv_ccg;
4645 }
4647 srd.ray_start = ray_start;
4648 srd.ray_normal = ray_normal;
4649 srd.depth = depth;
4650
4653 *pbvh,
4654 [&](bke::pbvh::Node &node, float *distance) { sculpt_raycast_cb(node, srd, distance); },
4655 ray_start,
4656 ray_normal,
4657 srd.use_original);
4658
4659 /* Cursor is not over the mesh, return default values. */
4660 if (!srd.hit) {
4661 ss.clear_active_elements(true);
4662 return std::nullopt;
4663 }
4664
4665 /* Update the active vertex of the SculptSession. */
4667
4668 switch (pbvh->type()) {
4671 ss.active_grid_index = std::nullopt;
4672 break;
4674 ss.active_face_index = std::nullopt;
4676 break;
4678 ss.active_face_index = std::nullopt;
4679 ss.active_grid_index = std::nullopt;
4680 break;
4681 }
4682
4683 out.location = ray_start + ray_normal * srd.depth;
4684
4685 /* Option to return the face normal directly for performance o accuracy reasons. */
4686 if (!use_sampled_normal) {
4687 out.normal = srd.face_normal;
4688 return srd.hit ? std::make_optional(out) : std::nullopt;
4689 }
4690
4691 /* Sampled normal calculation. */
4692
4693 /* Update cursor data in SculptSession. */
4694 const float3 z_axis = {0.0f, 0.0f, 1.0f};
4695 ob.runtime->world_to_object = math::invert(ob.object_to_world());
4697 math::transform_direction(ob.world_to_object() * float4x4(vc.rv3d->viewinv), z_axis));
4698 ss.cursor_normal = srd.face_normal;
4699 ss.cursor_location = out.location;
4700 ss.rv3d = vc.rv3d;
4701 ss.v3d = vc.v3d;
4702
4704
4705 IndexMaskMemory memory;
4706 const IndexMask node_mask = pbvh_gather_cursor_update(ob, original, memory);
4707
4708 /* In case there are no nodes under the cursor, return the face normal. */
4709 if (node_mask.is_empty()) {
4710 out.normal = srd.face_normal;
4711 return std::make_optional(out);
4712 }
4713
4714 bke::pbvh::update_normals(depsgraph, ob, *pbvh);
4715
4716 /* Calculate the sampled normal. */
4717 if (const std::optional<float3> sampled_normal = calc_area_normal(
4718 depsgraph, brush, ob, node_mask))
4719 {
4720 out.normal = *sampled_normal;
4721 ss.cursor_sampled_normal = *sampled_normal;
4722 }
4723 else {
4724 /* Use face normal when there are no vertices to sample inside the cursor radius. */
4725 out.normal = srd.face_normal;
4726 }
4727 return std::make_optional(out);
4728}
4729
4735static std::optional<float3> stroke_get_location_bvh_ex(Depsgraph &depsgraph,
4736 ViewContext &vc,
4737 const Paint &paint,
4738 const Sculpt *sd,
4739 const float2 &mval,
4740 const bool force_original,
4741 const bool check_closest,
4742 const bool limit_closest_radius)
4743{
4744 Object &ob = *vc.obact;
4745
4747 StrokeCache *cache = ss.cache;
4748 const bool original = force_original || ((cache) ? !cache->accum : false);
4750
4751 if (sd) {
4752 /* TODO: This code is shared by Sculpt, Vertex, and Weight paint. Ideally, we wouldn't need
4753 * to pass in `Sculpt` and `Paint` separately, but until we have further C++ DNA types, this
4754 * is fine */
4755 stroke_modifiers_check(depsgraph, ob, brush);
4756 }
4757
4758 float3 ray_start;
4759 float3 ray_end;
4760 float3 ray_normal;
4761 const float depth = raycast_init(&vc, mval, ray_start, ray_end, ray_normal, original);
4762
4764
4765 std::optional<float3> hit_location;
4766 {
4767 RaycastData rd;
4768 rd.object = &ob;
4769 rd.is_mid_stroke = ob.runtime->sculpt_session->cache != nullptr;
4770 rd.ray_start = ray_start;
4771 rd.ray_normal = ray_normal;
4772 rd.hit = false;
4773 if (pbvh.type() == bke::pbvh::Type::Mesh) {
4774 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
4776 rd.faces = mesh.faces();
4777 rd.corner_verts = mesh.corner_verts();
4778 rd.corner_tris = mesh.corner_tris();
4779 const bke::AttributeAccessor attributes = mesh.attributes();
4780 rd.hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
4781 }
4782 else if (pbvh.type() == bke::pbvh::Type::Grids) {
4783 rd.subdiv_ccg = ss.subdiv_ccg;
4784 }
4786 rd.depth = depth;
4787 rd.use_original = original;
4789
4791 pbvh,
4792 [&](bke::pbvh::Node &node, float *tmin) { sculpt_raycast_cb(node, rd, tmin); },
4793 ray_start,
4794 ray_normal,
4795 rd.use_original);
4796 if (rd.hit) {
4797 hit_location = ray_start + ray_normal * rd.depth;
4798 }
4799 }
4800
4801 if (hit_location.has_value() || !check_closest) {
4802 return hit_location;
4803 }
4804
4805 FindNearestToRayData fntrd{};
4806 fntrd.use_original = original;
4807 fntrd.object = &ob;
4808 fntrd.is_mid_stroke = ss.cache != nullptr;
4809 fntrd.hit = false;
4810 if (pbvh.type() == bke::pbvh::Type::Mesh) {
4811 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
4812 fntrd.vert_positions = bke::pbvh::vert_positions_eval(depsgraph, ob);
4813 fntrd.faces = mesh.faces();
4814 fntrd.corner_verts = mesh.corner_verts();
4815 fntrd.corner_tris = mesh.corner_tris();
4816 const bke::AttributeAccessor attributes = mesh.attributes();
4817 fntrd.hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
4818 }
4819 else if (pbvh.type() == bke::pbvh::Type::Grids) {
4820 fntrd.subdiv_ccg = ss.subdiv_ccg;
4821 }
4822 fntrd.ray_start = ray_start;
4823 fntrd.ray_normal = ray_normal;
4824 fntrd.depth = std::numeric_limits<float>::max();
4825 fntrd.dist_sq_to_ray = std::numeric_limits<float>::max();
4826
4828 pbvh,
4829 [&](bke::pbvh::Node &node, float *tmin) {
4830 sculpt_find_nearest_to_ray_cb(node, fntrd, tmin);
4831 },
4832 ray_start,
4833 ray_normal,
4834 fntrd.use_original);
4835 if (fntrd.hit && fntrd.dist_sq_to_ray) {
4836 hit_location = ray_start + ray_normal * fntrd.depth;
4837 }
4838
4839 float closest_radius_sq = std::numeric_limits<float>::max();
4840 if (limit_closest_radius) {
4841 if (brush) {
4842 closest_radius_sq = object_space_radius_get(
4843 vc, paint, *brush, hit_location.value_or(float3(0.0f)));
4844 closest_radius_sq *= closest_radius_sq;
4845 }
4846 }
4847
4848 if (fntrd.dist_sq_to_ray < closest_radius_sq) {
4849 return hit_location;
4850 }
4851
4852 return std::nullopt;
4853}
4854
4855std::optional<float3> stroke_get_location_bvh(Depsgraph &depsgraph,
4856 ViewContext &vc,
4857 const Sculpt &sd,
4858 const Brush *brush,
4859 const float mval[2],
4860 const bool force_original)
4861{
4862 const bool check_closest = brush && brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE;
4863
4865 depsgraph, vc, sd.paint, &sd, mval, force_original, check_closest, true);
4866}
4867
4868std::optional<float3> stroke_get_location_bvh(Depsgraph &depsgraph,
4869 ViewContext &vc,
4870 const Paint &paint,
4871 const Brush *brush,
4872 const float2 mval,
4873 const bool force_original)
4874{
4875 const bool check_closest = brush && brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE;
4876
4878 depsgraph, vc, paint, nullptr, mval, force_original, check_closest, true);
4879}
4880
4881std::optional<float3> stroke_get_location_bvh(bContext *C,
4882 const float2 mval,
4883 const bool force_original)
4884{
4885 Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);
4886 ViewContext vc = ED_view3d_viewcontext_init(C, depsgraph);
4887 const Sculpt &sd = *CTX_data_tool_settings(C)->sculpt;
4889
4890 return stroke_get_location_bvh(*depsgraph, vc, sd, brush, mval, force_original);
4891}
4892
4897
4898 /* Needed to tag other viewports */
4900
4902 : PaintStroke(C, op, event, PaintMode::Sculpt)
4903 {
4905
4906 ToolSettings *tool_settings = CTX_data_tool_settings(C);
4907 sculpt_ = tool_settings->sculpt;
4909 wm_ = CTX_wm_manager(C);
4910 }
4911
4912 std::optional<float3> get_location(float2 mouse, bool force_original) override;
4913 bool test_start(wmOperator *op, float2 mouse) override;
4914 void redraw(bool final) override;
4915 bool test_cancel() override;
4916 void update_step(wmOperator *op, const StrokeStep &stroke_step) override;
4917 void done(bool is_cancel, bool stroke_started) override;
4918};
4919
4920std::optional<float3> SculptPaintStroke::get_location(const float2 mouse, bool force_original)
4921{
4923 *this->depsgraph, this->vc, *sculpt_, this->brush, mouse, force_original);
4924}
4925
4926static void brush_init_tex(const Sculpt &sd, SculptSession &ss)
4927{
4930
4931 /* Init mtex nodes. */
4932 if (mask_tex->tex && mask_tex->tex->nodetree) {
4933 /* Has internal flag to detect it only does it once. */
4935 }
4936
4937 if (ss.tex_pool == nullptr) {
4939 }
4940}
4941
4944{
4945 const BrushStrokeMode stroke_mode = BrushStrokeMode(RNA_enum_get(op.ptr, "mode"));
4946 const BrushSwitchMode brush_switch_mode = BrushSwitchMode(RNA_enum_get(op.ptr, "brush_toggle"));
4947 const bool pen_flip = RNA_boolean_get(op.ptr, "pen_flip");
4948
4949 StrokeToggleSettings toggle_settings;
4950
4951 toggle_settings.invert = stroke_mode == BrushStrokeMode::Invert || pen_flip;
4952 toggle_settings.alt_smooth = brush_switch_mode == BrushSwitchMode::Smooth;
4953 toggle_settings.alt_mask = brush_switch_mode == BrushSwitchMode::Mask;
4954
4955 /* Alt-Smooth. */
4956 if (toggle_settings.alt_smooth) {
4957 smooth_brush_toggle_on(&bmain, &paint, toggle_settings);
4958 }
4959 /* Alt-Mask. */
4960 if (toggle_settings.alt_mask) {
4961 mask_brush_toggle_on(&bmain, &paint, toggle_settings);
4962 }
4963 return toggle_settings;
4964}
4965
4966static void brush_stroke_init(bContext *C, const wmOperator *op)
4967{
4969 ToolSettings *tool_settings = CTX_data_tool_settings(C);
4970 Sculpt &sd = *tool_settings->sculpt;
4972
4973 if (!G.background) {
4975 }
4976
4977 if (!ss.cache) {
4978 ss.cache = MEM_new<StrokeCache>(__func__);
4980 }
4981
4984 brush_init_tex(sd, ss);
4985
4986 if (brush_type_is_paint(brush->sculpt_brush_type)) {
4988 }
4989
4990 /* CTX_data_ensure_evaluated_depsgraph should be used at the end to include the updates of
4991 * earlier steps modifying the data. */
4992 Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);
4993 BKE_sculptsession_update_for_edit(depsgraph, &ob, brush_type_is_paint(brush->sculpt_brush_type));
4994
4996}
4997
4998static void restore_from_undo_step_if_necessary(const Depsgraph &depsgraph,
4999 const Sculpt &sd,
5000 Object &ob)
5001{
5005
5006 /* Brushes that use original coordinates and need a "restore" step. This has to happen separately
5007 * rather than in the brush deformation calculation because that is called once for each symmetry
5008 * pass, potentially within the same BVH node.
5009 *
5010 * NOTE: Despite the Cloth and Boundary brush using original coordinates, the brushes do not
5011 * expect this restoration to happen on every stroke step. Performing this restoration causes
5012 * issues with the cloth simulation mode for those brushes.
5013 */
5014 if (ELEM(brush->sculpt_brush_type,
5019 {
5020 undo::restore_from_undo_step(depsgraph, sd, ob);
5021 return;
5022 }
5023
5024 /* For the cloth brush it makes more sense to not restore the mesh state to keep running the
5025 * simulation from the previous state. */
5026 if (brush->sculpt_brush_type == SCULPT_BRUSH_TYPE_CLOTH) {
5027 return;
5028 }
5029
5030 /* Restore the mesh before continuing with anchored stroke. */
5031 if (ELEM(brush->stroke_method, BRUSH_STROKE_ANCHORED, BRUSH_STROKE_DRAG_DOT)) {
5032
5033 undo::restore_from_undo_step(depsgraph, sd, ob);
5034
5035 if (ss.cache) {
5036 /* Temporary data within the StrokeCache that is usually cleared at the end of the stroke
5037 * needs to be invalidated here so that the brushes do not accumulate and apply extra data.
5038 * See #129069. */
5040 ss.cache->paint_brush.mix_colors = {};
5041 }
5042 }
5043}
5044
5045static void tag_mesh_positions_changed(Object &object, const bool use_pbvh_draw)
5046{
5047 Mesh &mesh = *id_cast<Mesh *>(object.data);
5048
5049 /* Various operations inside sculpt mode can cause either the #MeshRuntimeData or the entire
5050 * Mesh to be changed (e.g. Undoing the very first operation after opening a file, performing
5051 * remesh, etc).
5052 *
5053 * This isn't an ideal fix for the core issue here, but to mitigate the drastic performance
5054 * falloff, we refreeze the cache before we do any operation that would tag this runtime
5055 * cache as dirty.
5056 *
5057 * See #130636. */
5058 if (!mesh.runtime->corner_tris_cache.frozen) {
5059 mesh.runtime->corner_tris_cache.freeze();
5060 }
5061
5062 /* Updating mesh positions without marking caches dirty is generally not good, but since
5063 * sculpt mode has special requirements and is expected to have sole ownership of the mesh it
5064 * modifies, it's generally okay. */
5065 if (use_pbvh_draw) {
5066 /* When drawing from bke::pbvh::Tree is used, vertex and face normals are updated
5067 * later in #bke::pbvh::update_normals. However, we update the mesh's bounds eagerly here
5068 * since they are trivial to access from the bke::pbvh::Tree. Updating the
5069 * object's evaluated geometry bounding box is necessary because sculpt strokes don't cause
5070 * an object reevaluation. */
5071 mesh.tag_positions_changed_no_normals();
5072 /* Sculpt mode does not use or recalculate face corner normals, so they are cleared. */
5073 mesh.runtime->corner_normals_cache.tag_dirty();
5074 }
5075 else {
5076 /* Drawing happens from the modifier stack evaluation result.
5077 * Tag both coordinates and normals as modified, as both needed for proper drawing and the
5078 * modifier stack is not guaranteed to tag normals for update. */
5079 mesh.tag_positions_changed();
5080 }
5081
5082 if (const bke::pbvh::Tree *pbvh = bke::object::pbvh_get(object)) {
5083 mesh.bounds_set_eager(bke::pbvh::bounds_get(*pbvh));
5084 if (object.runtime->bounds_eval) {
5085 object.runtime->bounds_eval = mesh.bounds_min_max();
5086 }
5087 }
5088}
5089
5095
5096void flush_update_step(ViewContext &vc, Object &object, const UpdateType update_type)
5097{
5099 if (vc.rv3d) {
5100 /* Mark for faster 3D viewport redraws. */
5101 vc.rv3d->rflag |= RV3D_PAINTING;
5102 }
5103
5104 const SculptSession &ss = *object.runtime->sculpt_session;
5106 if (mmd != nullptr) {
5108 }
5109
5111
5112 const bool use_pbvh_draw = BKE_sculptsession_use_pbvh_draw(&object, vc.rv3d);
5113 /* Only current viewport matters, slower update for all viewports will
5114 * be done in sculpt_flush_update_done. */
5115 if (!use_pbvh_draw) {
5116 /* Slow update with full dependency graph update and all that comes with it.
5117 * Needed when there are modifiers or full shading in the 3D viewport. */
5119 }
5120
5122
5124 if (update_type == UpdateType::Position && !ss.shapekey_active) {
5125 if (pbvh.type() == bke::pbvh::Type::Mesh) {
5126 tag_mesh_positions_changed(object, use_pbvh_draw);
5127 }
5128 }
5129}
5130
5131void flush_update_done(bContext *C, Object &ob, const UpdateType update_type)
5132{
5135 flush_update_done(vc, wm, ob, update_type);
5136}
5137
5139 const wmWindowManager &wm,
5140 Object &ob,
5141 const UpdateType update_type)
5142{
5143 /* After we are done drawing the stroke, check if we need to do a more
5144 * expensive depsgraph tag to update geometry. */
5145 const Mesh &mesh = *id_cast<Mesh *>(ob.data);
5146
5147 /* Always needed for linked duplicates. */
5148 bool need_tag = ID_REAL_USERS(&mesh.id) > 1;
5149
5150 if (vc.rv3d) {
5151 vc.rv3d->rflag &= ~RV3D_PAINTING;
5152 }
5153
5154 /* TODO: this might be better in the `redraw` callback instead of here */
5155 for (wmWindow &win : wm.windows) {
5156 const bScreen &screen = *WM_window_get_active_screen(&win);
5157 for (ScrArea &area : screen.areabase) {
5158 const SpaceLink &sl = *area.spacedata.first();
5159 if (sl.spacetype != SPACE_VIEW3D) {
5160 continue;
5161 }
5162
5163 /* Tag all 3D viewports for redraw now that we are done. Other
5164 * viewports did not get a full redraw, and anti-aliasing for the
5165 * current viewport was deactivated. */
5166 for (ARegion &region : area.regionbase) {
5167 if (region.regiontype == RGN_TYPE_WINDOW) {
5168 const RegionView3D *other_rv3d = static_cast<RegionView3D *>(region.regiondata);
5169 if (other_rv3d != vc.rv3d) {
5170 need_tag |= !BKE_sculptsession_use_pbvh_draw(&ob, other_rv3d);
5171 }
5172
5173 ED_region_tag_redraw(&region);
5174 }
5175 }
5176 }
5177 }
5178
5180
5181 if (update_type == UpdateType::Position) {
5183
5184 /* Coordinates were modified, so fake neighbors are not longer valid. */
5186 }
5187
5188 if (update_type == UpdateType::Position) {
5189 if (pbvh.type() == bke::pbvh::Type::BMesh) {
5192 }
5193 }
5194
5195 if (need_tag) {
5197 }
5198}
5199
5200/* Replace an entire attribute using implicit sharing to avoid copies when possible. */
5201static void replace_attribute(const bke::AttributeAccessor src_attributes,
5202 const StringRef name,
5203 const bke::AttrDomain domain,
5204 const bke::AttrType data_type,
5205 bke::MutableAttributeAccessor dst_attributes)
5206{
5207 dst_attributes.remove(name);
5208 bke::GAttributeReader src = src_attributes.lookup(name, domain, data_type);
5209 if (!src) {
5210 return;
5211 }
5212 if (src.sharing_info && src.varray.is_span()) {
5214 dst_attributes.add(name, domain, data_type, init);
5215 }
5216 else {
5217 const bke::AttributeInitVArray init(*src);
5218 dst_attributes.add(name, domain, data_type, init);
5219 }
5220}
5221
5224 const StringRef name)
5225{
5226 const bke::GAttributeReader a_attr = a.lookup(name);
5227 const bke::GAttributeReader b_attr = b.lookup(name);
5228 if (!a_attr.sharing_info || !b_attr.sharing_info) {
5229 return false;
5230 }
5231 return a_attr.sharing_info == b_attr.sharing_info;
5232}
5233
5234static bool topology_matches(const Mesh &a, const Mesh &b)
5235{
5236 if (a.verts_num != b.verts_num || a.edges_num != b.edges_num || a.faces_num != b.faces_num ||
5237 a.corners_num != b.corners_num)
5238 {
5239 return false;
5240 }
5241 if (a.runtime->face_offsets_sharing_info != b.runtime->face_offsets_sharing_info) {
5242 return false;
5243 }
5244 const bke::AttributeAccessor a_attributes = a.attributes();
5245 const bke::AttributeAccessor b_attributes = b.attributes();
5246 if (!attribute_matches(a_attributes, b_attributes, ".edge_verts") ||
5247 !attribute_matches(a_attributes, b_attributes, ".corner_vert") ||
5248 !attribute_matches(a_attributes, b_attributes, ".corner_edge"))
5249 {
5250 return false;
5251 }
5252 return true;
5253}
5254
5256 const Scene &scene,
5257 Object &object,
5258 Mesh *new_mesh)
5259{
5260 Mesh &mesh = *id_cast<Mesh *>(object.data);
5261 sculpt_paint::undo::geometry_begin(scene, object, &op);
5262 BKE_mesh_nomain_to_mesh(new_mesh, &mesh, &object, false);
5265}
5266
5268{
5269 const int layer_index = CustomData_get_layer_index(&mesh.vert_data, CD_MDEFORMVERT);
5270 if (layer_index == -1) {
5271 return nullptr;
5272 }
5273 return mesh.vert_data.layers[layer_index].sharing_info;
5274}
5275
5277 const Scene &scene,
5278 const Depsgraph &depsgraph,
5279 const RegionView3D *rv3d,
5280 Object &object,
5281 Mesh *new_mesh)
5282{
5283 Mesh &mesh = *id_cast<Mesh *>(object.data);
5284 const bool changed_topology = !topology_matches(mesh, *new_mesh);
5285 const bool use_pbvh_draw = BKE_sculptsession_use_pbvh_draw(&object, rv3d);
5286 bool entire_mesh_changed = false;
5287
5288 if (changed_topology) {
5289 store_sculpt_entire_mesh(op, scene, object, new_mesh);
5290 entire_mesh_changed = true;
5291 }
5292 else {
5293 /* Detect attributes present in the new mesh which no longer match the original. */
5294 VectorSet<StringRef> vertex_group_names;
5295 for (const bDeformGroup &vertex_group : mesh.vertex_group_names) {
5296 vertex_group_names.add(vertex_group.name);
5297 }
5298
5299 VectorSet<StringRef> changed_attributes;
5300 new_mesh->attributes().foreach_attribute([&](const bke::AttributeIter &iter) {
5301 if (ELEM(iter.name, ".edge_verts", ".corner_vert", ".corner_edge")) {
5302 return;
5303 }
5304 if (vertex_group_names.contains(iter.name)) {
5305 /* Vertex group changes are handled separately. */
5306 return;
5307 }
5308 const bke::GAttributeReader attribute = iter.get();
5309 if (attribute_matches(new_mesh->attributes(), mesh.attributes(), iter.name)) {
5310 return;
5311 }
5312 changed_attributes.add(iter.name);
5313 });
5314 /* Detect attributes that were removed in the new mesh. */
5315 mesh.attributes().foreach_attribute([&](const bke::AttributeIter &iter) {
5316 if (!new_mesh->attributes().contains(iter.name)) {
5317 changed_attributes.add(iter.name);
5318 }
5319 });
5320
5321 /* Vertex groups aren't handled fully by the attribute system, we need to use CustomData. */
5322 const bool vertex_groups_changed = get_vertex_group_sharing_info(mesh) !=
5324
5325 if (vertex_groups_changed) {
5326 changed_attributes.add_multiple(vertex_group_names);
5327 }
5328
5329 /* Try to use the few specialized sculpt undo types that result in better performance, mainly
5330 * because redo avoids clearing the BVH, but also because some other updates can be skipped. */
5332 IndexMaskMemory memory;
5333 const IndexMask leaf_nodes = bke::pbvh::all_leaf_nodes(pbvh, memory);
5334 if (changed_attributes.as_span() == Span<StringRef>{"position"}) {
5335 undo::push_begin(scene, object, &op);
5336 undo::push_nodes(depsgraph, object, leaf_nodes, undo::Type::Position);
5337 undo::push_end(object);
5338 mesh.attribute_storage.wrap().remove("position");
5339 const bke::AttributeReader position = new_mesh->attributes().lookup<float3>("position");
5340 if (position.sharing_info) {
5341 /* Use lower level API to add the position attribute to avoid copying the array and to
5342 * allow using #tag_positions_changed_no_normals instead of #tag_positions_changed (which
5343 * would be called by the attribute API). */
5344 position.sharing_info->add_user();
5345
5347 data.data = const_cast<float3 *>(position.varray.get_internal_span().data());
5348 data.size = position.varray.size();
5349 data.sharing_info = ImplicitSharingPtr<>(position.sharing_info);
5350 mesh.attribute_storage.wrap().add(
5351 "position", bke::AttrDomain::Point, bke::AttrType::Float3, std::move(data));
5352 }
5353 else {
5354 mesh.vert_positions_for_write().copy_from(VArraySpan(*position));
5355 }
5356
5357 pbvh.tag_positions_changed(leaf_nodes);
5358 pbvh.update_bounds(depsgraph, object);
5359 tag_mesh_positions_changed(object, use_pbvh_draw);
5360 BKE_mesh_copy_parameters(&mesh, new_mesh);
5361 BKE_id_free(nullptr, new_mesh);
5362 }
5363 else if (changed_attributes.as_span() == Span<StringRef>{".sculpt_mask"}) {
5364 undo::push_begin(scene, object, &op);
5365 undo::push_nodes(depsgraph, object, leaf_nodes, undo::Type::Mask);
5366 undo::push_end(object);
5367 replace_attribute(new_mesh->attributes(),
5368 ".sculpt_mask",
5371 mesh.attributes_for_write());
5372 pbvh.tag_masks_changed(leaf_nodes);
5373 BKE_mesh_copy_parameters(&mesh, new_mesh);
5374 BKE_id_free(nullptr, new_mesh);
5375 }
5376 else if (changed_attributes.as_span() == Span<StringRef>{".sculpt_face_set"}) {
5377 undo::push_begin(scene, object, &op);
5378 undo::push_nodes(depsgraph, object, leaf_nodes, undo::Type::FaceSet);
5379 undo::push_end(object);
5380 replace_attribute(new_mesh->attributes(),
5381 ".sculpt_face_set",
5384 mesh.attributes_for_write());
5385 pbvh.tag_face_sets_changed(leaf_nodes);
5386 BKE_mesh_copy_parameters(&mesh, new_mesh);
5387 BKE_id_free(nullptr, new_mesh);
5388 }
5389 else {
5390 /* Non-geometry-type sculpt undo steps can only handle a single change at a time. When
5391 * multiple attributes or attributes that don't have their own undo type are changed, we're
5392 * forced to fall back to the slower geometry undo type. */
5393 store_sculpt_entire_mesh(op, scene, object, new_mesh);
5394 entire_mesh_changed = true;
5395 }
5396 }
5398 if (!use_pbvh_draw || entire_mesh_changed) {
5400 }
5401}
5402
5403/* Returns whether the mouse/stylus is over the mesh (1)
5404 * or over the background (0). */
5405static bool over_mesh(bContext *C, wmOperator * /*op*/, const float mval[2])
5406{
5407 const Sculpt &sd = *CTX_data_tool_settings(C)->sculpt;
5409 Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);
5410 ViewContext vc = ED_view3d_viewcontext_init(C, depsgraph);
5411
5412 const bool check_closest = brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE;
5413
5415 *depsgraph, vc, sd.paint, &sd, mval, false, check_closest, true)
5416 .has_value();
5417}
5418
5419static bool over_mesh(Depsgraph &depsgraph,
5420 ViewContext &vc,
5421 const Sculpt &sd,
5422 const Brush *brush,
5423 wmOperator * /*op*/,
5424 const float mval[2])
5425{
5426 const bool check_closest = brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE;
5427
5428 return stroke_get_location_bvh_ex(depsgraph, vc, sd.paint, &sd, mval, false, check_closest, true)
5429 .has_value();
5430}
5431
5432bool color_supported_check(const Scene &scene, Object &object, ReportList *reports)
5433{
5434 if (const SculptSession &ss = *object.runtime->sculpt_session; ss.bm) {
5435 BKE_report(reports, RPT_ERROR, "Not supported in dynamic topology mode");
5436 return false;
5437 }
5438 if (BKE_sculpt_multires_active(&scene, &object)) {
5439 BKE_report(reports, RPT_ERROR, "Not supported in multiresolution mode");
5440 return false;
5441 }
5442
5443 return true;
5444}
5445
5447 ViewContext &vc, const Sculpt &sd, const Brush &brush, Object &ob, const float mval[2])
5448{
5450 StrokeCache *cache = ss.cache;
5451
5452 stroke_cache_common_init(vc, sd.paint, brush, ob, mval);
5453
5454 /* Set scaling adjustment. */
5455 float max_scale = 0.0f;
5456 for (int i = 0; i < 3; i++) {
5457 max_scale = max_ff(max_scale, fabsf(ob.scale[i]));
5458 }
5459 cache->scale[0] = max_scale / ob.scale[0];
5460 cache->scale[1] = max_scale / ob.scale[1];
5461 cache->scale[2] = max_scale / ob.scale[2];
5462
5463 cache->plane_trim_squared = brush.plane_trim * brush.plane_trim;
5464
5465 cache->mirror_modifier_clip.flag = 0;
5466
5468
5469 cache->initial_direction_flipped = brush_flip(brush, *cache) < 0.0f;
5470
5472 /* Get gravity vector in world space. */
5473 if (cache->supports_gravity) {
5474 if (sd.gravity_object) {
5475 cache->gravity_direction = sd.gravity_object->object_to_world().z_axis();
5476 }
5477 else {
5478 cache->gravity_direction = {0.0f, 0.0f, 1.0f};
5479 }
5480
5481 /* Transform to sculpted object space. */
5483 math::transform_direction(ob.world_to_object(), cache->gravity_direction));
5484 }
5485
5486 cache->accum = true;
5487
5488 /* Make copies of the mesh vertex locations and normals for some brushes. */
5489 if (brush.stroke_method == BRUSH_STROKE_ANCHORED) {
5490 cache->accum = false;
5491 }
5492
5493 /* Draw sharp does not need the original coordinates to produce the accumulate effect, so it
5494 * should work the opposite way. */
5495 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_DRAW_SHARP) {
5496 cache->accum = false;
5497 }
5498
5500 if (!(brush.flag & BRUSH_ACCUMULATE)) {
5501 cache->accum = false;
5502 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_DRAW_SHARP) {
5503 cache->accum = true;
5504 }
5505 }
5506 }
5507
5510 }
5511 cache->plane_brush.first_time = true;
5512
5513 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_ROTATE) {
5514 constexpr int pixel_input_threshold = 5;
5515 cache->dial = BLI_dial_init(cache->initial_mouse, pixel_input_threshold);
5516 }
5517}
5518
5520{
5521 /* Don't start the stroke until `mouse` goes over the mesh. */
5522 if (over_mesh(*this->depsgraph, this->vc, *sculpt_, this->brush, op, mouse)) {
5523 Brush &brush = *this->brush;
5524
5525 /* NOTE: This should be removed when paint mode is available. Paint mode can force based on the
5526 * canvas it is painting on. (ref. use_3d_texture_paint). */
5528 View3D *v3d = this->vc.v3d;
5529 if (v3d->shading.type == OB_SOLID) {
5531 }
5532 }
5533
5534 stroke_cache_init(this->vc, *sculpt_, *this->brush, *this->object, mouse);
5539 }
5540
5541 cursor_geometry_info_update(*this->depsgraph, *paint, sculpt_, this->vc, base_, mouse, false);
5542
5543 undo::push_begin_ex(*this->scene, *this->object, sculpt_brush_type_name(brush));
5544
5545 return true;
5546 }
5547 return false;
5548}
5549
5552 const Depsgraph &depsgraph,
5553 Paint &paint,
5554 Brush &brush,
5555 Object &object,
5556 const PaintStroke::StrokeStep &stroke_step)
5557{
5559 bke::PaintRuntime &paint_runtime = *paint.runtime;
5560 SculptSession &ss = *object.runtime->sculpt_session;
5561 StrokeCache &cache = *ss.cache;
5562
5564 !((brush.stroke_method == BRUSH_STROKE_ANCHORED) ||
5565 (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SNAKE_HOOK) ||
5566 (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_ROTATE) ||
5568 {
5569 cache.location = stroke_step.location;
5570 }
5571
5572 cache.mouse = stroke_step.mouse;
5573 cache.mouse_event = stroke_step.mouse_event;
5574
5575 /* We don't do a raycast here for sculpt mode unlike vertex and weight paint */
5576
5577 /* XXX: Use pressure value from first brush step for brushes which don't support strokes (grab,
5578 * thumb). They depends on initial state and brush coord/pressure/etc.
5579 * It's more an events design issue, which doesn't split coordinate/pressure/angle changing
5580 * events. We should avoid this after events system re-design. */
5582 cache.pressure = stroke_step.pressure;
5583 }
5584
5585 cache.tilt = stroke_step.tilt;
5586
5587 /* Truly temporary data that isn't stored in properties. */
5590
5593 }
5594 }
5595
5596 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_SCENE_PROJECT) {
5597 init_scene_project_brush_targets(depsgraph, *vc.view_layer, *vc.v3d, object, cache);
5598 }
5599
5600 /* Clay stabilized pressure. */
5601 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_CLAY_THUMB) {
5603 ss.cache->clay_thumb_brush.pressure_stabilizer.fill(0.0f);
5604 ss.cache->clay_thumb_brush.stabilizer_index = 0;
5605 }
5606 else {
5607 cache.clay_thumb_brush.pressure_stabilizer[cache.clay_thumb_brush.stabilizer_index] =
5608 cache.pressure;
5609 cache.clay_thumb_brush.stabilizer_index += 1;
5610 if (cache.clay_thumb_brush.stabilizer_index >=
5611 ss.cache->clay_thumb_brush.pressure_stabilizer.size())
5612 {
5613 cache.clay_thumb_brush.stabilizer_index = 0;
5614 }
5615 }
5616 }
5617
5618 /* Note: This call needs to happen after the clay thumb specific code due to the interaction with
5619 * the stabilizer */
5621 {
5622 cache.radius = brush_dynamic_size_get(brush, cache, cache.initial_radius);
5624 brush, cache, paint_runtime.initial_pixel_radius);
5625 }
5626 else {
5627 cache.radius = cache.initial_radius;
5628 cache.dyntopo_pixel_radius = paint_runtime.initial_pixel_radius;
5629 }
5630 cache.radius_squared = cache.radius * cache.radius;
5631
5632 cache.hardness = brush.hardness;
5634 cache.hardness *= BKE_curvemapping_evaluateF(brush.curve_hardness, 0, cache.pressure);
5635 }
5636
5638
5639 if (brush.stroke_method == BRUSH_STROKE_ANCHORED) {
5640 /* True location has been calculated as part of the stroke system already here. */
5641 if (brush.flag & BRUSH_EDGE_TO_EDGE) {
5642 cache.location = stroke_step.location;
5643 }
5644
5646 *cache.vc, cache.location, paint_runtime.pixel_radius);
5647 cache.radius_squared = cache.radius * cache.radius;
5648 }
5649
5650 brush_delta_update(depsgraph, paint, object, brush);
5651
5652 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_ROTATE) {
5653 cache.vertex_rotation = -BLI_dial_angle(cache.dial, cache.mouse) * cache.bstrength;
5654
5655 paint_runtime.draw_anchored = true;
5656 copy_v2_v2(paint_runtime.anchored_initial_mouse, cache.initial_mouse);
5657 paint_runtime.anchored_size = paint_runtime.pixel_radius;
5658 }
5659
5660 /* TODO: For brushes that does not support rake, we should allow users to set a starting
5661 * rotation. Should be implemented after moving Rake and Rotation settings from the texture
5662 * datablock. */
5663 const float tip_rotation = paint_runtime.brush_rotation;
5664
5665 /* Calculate brush's 3D normal direction from screen-space rotation. */
5666 cache.tip_motion_normal = calc_motion_normal_from_angle(*cache.vc, cache.location, tip_rotation);
5667
5668 cache.iteration_count++;
5669}
5670
5671void SculptPaintStroke::update_step(wmOperator * /*op*/, const StrokeStep &stroke_step)
5672{
5673 const Scene &scene = *this->scene;
5674 Depsgraph &depsgraph = *this->depsgraph;
5675 Sculpt &sd = *sculpt_;
5676 Object &ob = *this->object;
5678 Brush &brush = *this->brush;
5679 StrokeCache *cache = ss.cache;
5680 cache->stroke_distance = this->stroke_distance();
5681
5683 stroke_cache_update(this->vc, depsgraph, sd.paint, brush, ob, stroke_step);
5685
5687 cache->base_brush_strength = brush_strength(sd, *cache);
5689 depsgraph, scene, sd.paint, ob, dynamic_topology_update, nullptr);
5690 }
5691
5692 cache->base_brush_strength = brush_strength(sd, *cache);
5694 depsgraph, scene, sd.paint, ob, do_brush_action, nullptr);
5695
5696 /* Hack to fix noise texture tearing mesh. */
5697 sculpt_fix_noise_tear(sd, ob);
5698
5699 ss.cache->first_time = false;
5701
5702 /* Cleanup. */
5704 flush_update_step(this->vc, *this->object, UpdateType::Mask);
5705 }
5707 flush_update_step(this->vc, *this->object, UpdateType::Color);
5708 }
5709 else {
5710 flush_update_step(this->vc, *this->object, UpdateType::Position);
5711 }
5712}
5713
5714static void brush_exit_tex(Sculpt &sd)
5715{
5718
5719 if (mask_tex->tex && mask_tex->tex->nodetree) {
5721 }
5722}
5723
5724void SculptPaintStroke::done(bool is_cancel, bool stroke_started)
5725{
5726 Object &ob = *this->object;
5728 Sculpt &sd = *this->sculpt_;
5729
5730 /* Finished. */
5731 if (!ss.cache) {
5732 brush_exit_tex(sd);
5733 return;
5734 }
5736
5738
5739 /* Alt-Smooth. */
5742 /* Refresh the brush pointer in case we switched brush in the toggle function. */
5744 }
5745 /* Toggle Mask */
5746 if (ss.cache->toggle_settings.alt_mask) {
5748 /* Refresh the brush pointer in case we switched brush in the toggle function. */
5750 }
5751
5752 MEM_delete(ss.cache);
5753 ss.cache = nullptr;
5754
5755 if (!is_cancel && stroke_started) {
5756 undo::push_end(*this->object);
5757 }
5758
5761 }
5764 }
5765 else {
5767 }
5768
5770 brush_exit_tex(sd);
5771}
5772
5773void SculptPaintStroke::redraw(bool /*final*/) {}
5774
5776{
5777 const Brush &brush = *BKE_paint_brush_for_read(this->paint);
5778
5779 /* XXX Canceling strokes that way does not work with dynamic topology,
5780 * user will have to do real undo for now. See #46456. */
5781 bool ret_val = !dyntopo::stroke_is_dyntopo(*this->object, brush);
5782 return ret_val;
5783}
5784
5786 wmOperator *op,
5787 const wmEvent *event)
5788{
5790 Scene &scene = *CTX_data_scene(C);
5791 const View3D *v3d = CTX_wm_view3d(C);
5792 const Base *base = CTX_data_active_base(C);
5793 /* Test that ob is visible; otherwise we won't be able to get evaluated data
5794 * from the depsgraph. We do this here instead of SCULPT_mode_poll
5795 * to avoid falling through to the translate operator in the
5796 * global view3d keymap. */
5797 if (!BKE_base_is_visible(v3d, base)) {
5798 return OPERATOR_CANCELLED;
5799 }
5800
5801 bool pen_flip;
5802 WM_event_tablet_data(event, &pen_flip, nullptr);
5803
5804 SculptPaintStroke *stroke = MEM_new<SculptPaintStroke>(__func__, C, op, event);
5805 brush_stroke_init(C, op);
5806
5809
5810 if (brush_type_is_paint(brush.sculpt_brush_type) &&
5811 !color_supported_check(scene, ob, op->reports))
5812 {
5813 stroke->cancel(C);
5814 MEM_delete(stroke);
5815 return OPERATOR_CANCELLED;
5816 }
5817 if (!brush_type_is_attribute_only(brush.sculpt_brush_type) && !shape_key_check(ob, op->reports))
5818 {
5819 stroke->cancel(C);
5820 MEM_delete(stroke);
5821 return OPERATOR_CANCELLED;
5822 }
5823 if (ELEM(brush.sculpt_brush_type,
5826 {
5828 if (!pbvh || pbvh->type() != bke::pbvh::Type::Grids) {
5829 BKE_report(op->reports, RPT_ERROR, "Only supported in multiresolution mode");
5830 stroke->cancel(C);
5831 MEM_delete(stroke);
5832 return OPERATOR_CANCELLED;
5833 }
5834 }
5835
5836 if (brush_type_is_mask(brush.sculpt_brush_type)) {
5839
5840 mask_overlay_check(*C, *op);
5841 }
5842 if (brush.sculpt_brush_type == SCULPT_BRUSH_TYPE_DRAW_FACE_SETS) {
5844 }
5845
5846 op->customdata = stroke;
5847
5848 /* For tablet rotation. */
5849 const bool ignore_background_click = RNA_boolean_get(op->ptr, "ignore_background_click");
5850 const float mval[2] = {float(event->mval[0]), float(event->mval[1])};
5851 if (ignore_background_click && !over_mesh(C, op, mval)) {
5852 stroke->cancel(C);
5853 MEM_delete(stroke);
5854 return OPERATOR_PASS_THROUGH;
5855 }
5856
5857 const wmOperatorStatus retval = op->type->modal(C, op, event);
5858 OPERATOR_RETVAL_CHECK(retval);
5859
5861 stroke = static_cast<SculptPaintStroke *>(op->customdata);
5862 if (stroke) {
5863 if (retval == OPERATOR_FINISHED) {
5864 stroke->finish(C);
5865 }
5866 else {
5867 stroke->cancel(C);
5868 }
5869 MEM_delete(stroke);
5870 }
5871 return retval;
5872 }
5873 /* Add modal handler. */
5875
5877
5879}
5880
5882{
5883 brush_stroke_init(C, op);
5884
5885 SculptPaintStroke *stroke = MEM_new<SculptPaintStroke>(__func__, C, op, nullptr);
5886 op->customdata = stroke;
5887
5888 stroke->exec(C, op);
5889
5890 MEM_delete(stroke);
5891
5892 return OPERATOR_FINISHED;
5893}
5894
5896{
5897 const Depsgraph &depsgraph = *CTX_data_depsgraph_pointer(C);
5901
5902 SculptPaintStroke *stroke = static_cast<SculptPaintStroke *>(op->customdata);
5903
5906
5907 undo::restore_from_undo_step(depsgraph, sd, ob);
5908 stroke->cancel(C);
5909}
5910
5912{
5913 SculptPaintStroke *stroke = static_cast<SculptPaintStroke *>(op->customdata);
5914 const wmOperatorStatus retval = stroke->modal(C, op, event);
5915
5917 MEM_delete(stroke);
5918 op->customdata = nullptr;
5919 }
5920
5921 return retval;
5922}
5923
5924static void redo_empty_ui(bContext * /*C*/, wmOperator * /*op*/) {}
5925
5927{
5928 /* Identifiers. */
5929 ot->name = "Sculpt";
5930 ot->idname = "SCULPT_OT_brush_stroke";
5931 ot->description = "Sculpt a stroke into the geometry";
5932
5933 /* API callbacks. */
5939 ot->ui = redo_empty_ui;
5940
5941 /* Flags (sculpt does its own undo? (ton)). */
5942 ot->flag = OPTYPE_BLOCKING;
5943
5944 /* Properties. */
5945
5947
5949 ot->srna,
5950 "override_location",
5951 false,
5952 "Override Location",
5953 "Override the given \"location\" array by recalculating object space positions from the "
5954 "provided \"mouse_event\" positions");
5956
5957 prop = RNA_def_boolean(ot->srna,
5958 "ignore_background_click",
5959 false,
5960 "Ignore Background Click",
5961 "Clicks on the background do not start the stroke");
5963}
5964
5965/* Fake Neighbors. */
5966
5967static void fake_neighbor_init(Object &object, const float max_dist)
5968{
5969 SculptSession &ss = *object.runtime->sculpt_session;
5970 const int totvert = vertex_count_get(object);
5973}
5974
5979
5981 int vert = -1;
5982 float distance_sq = std::numeric_limits<float>::max();
5983
5985 {
5986 NearestVertData joined = a;
5987 if (joined.vert == -1) {
5988 joined.vert = b.vert;
5989 joined.distance_sq = b.distance_sq;
5990 }
5991 else if (b.distance_sq < joined.distance_sq) {
5992 joined.vert = b.vert;
5993 joined.distance_sq = b.distance_sq;
5994 }
5995 return joined;
5996 }
5997};
5998
6000 const Span<float3> vert_positions,
6001 const Span<bool> hide_vert,
6002 const float3 &location,
6003 const float max_distance_sq,
6004 const int island_id,
6006 NearestVertData &nvtd)
6007{
6008 for (const int vert : node.verts()) {
6009 if (!hide_vert.is_empty() && hide_vert[vert]) {
6010 continue;
6011 }
6013 continue;
6014 }
6015 if (islands::vert_id_get(ss, vert) == island_id) {
6016 continue;
6017 }
6018 const float distance_sq = math::distance_squared(vert_positions[vert], location);
6019 if (distance_sq < max_distance_sq && distance_sq < nvtd.distance_sq) {
6020 nvtd.vert = vert;
6021 nvtd.distance_sq = distance_sq;
6022 }
6023 }
6024}
6025
6027 const CCGKey &key,
6028 const Span<float3> positions,
6029 const BitGroupVector<> &grid_hidden,
6030 const float3 &location,
6031 const float max_distance_sq,
6032 const int island_id,
6034 NearestVertData &nvtd)
6035{
6036 for (const int grid : node.grids()) {
6037 const IndexRange grid_range = bke::ccg::grid_range(key, grid);
6038 BKE_subdiv_ccg_foreach_visible_grid_vert(key, grid_hidden, grid, [&](const int offset) {
6039 const int vert = grid_range[offset];
6041 return;
6042 }
6043 if (islands::vert_id_get(ss, vert) == island_id) {
6044 return;
6045 }
6046 const float distance_sq = math::distance_squared(positions[vert], location);
6047 if (distance_sq < max_distance_sq && distance_sq < nvtd.distance_sq) {
6048 nvtd.vert = vert;
6049 nvtd.distance_sq = distance_sq;
6050 }
6051 });
6052 }
6053}
6054
6056 const float3 &location,
6057 const float max_distance_sq,
6058 const int island_id,
6060 NearestVertData &nvtd)
6061{
6062 for (const BMVert *bm_vert :
6064 {
6065 if (BM_elem_flag_test(bm_vert, BM_ELEM_HIDDEN)) {
6066 continue;
6067 }
6068 const int vert = BM_elem_index_get(bm_vert);
6070 continue;
6071 }
6072 if (islands::vert_id_get(ss, vert) == island_id) {
6073 continue;
6074 }
6075 const float distance_sq = math::distance_squared(float3(bm_vert->co), location);
6076 if (distance_sq < max_distance_sq && distance_sq < nvtd.distance_sq) {
6077 nvtd.vert = vert;
6078 nvtd.distance_sq = distance_sq;
6079 }
6080 }
6081}
6082
6083static void fake_neighbor_search(const Depsgraph &depsgraph,
6084 const Object &ob,
6085 const float max_distance_sq,
6086 MutableSpan<int> fake_neighbors)
6087{
6089 /* NOTE: This algorithm is extremely slow, it has O(n^2) runtime for the entire mesh. This looks
6090 * like the "closest pair of points" problem which should have far better solutions. */
6093
6094 switch (pbvh.type()) {
6095 case bke::pbvh::Type::Mesh: {
6096 const Mesh &mesh = *id_cast<const Mesh *>(ob.data);
6097 const Span<float3> vert_positions = bke::pbvh::vert_positions_eval(depsgraph, ob);
6098 const bke::AttributeAccessor attributes = mesh.attributes();
6099 const VArraySpan<bool> hide_vert = *attributes.lookup<bool>(".hide_vert",
6101 for (const int vert : vert_positions.index_range()) {
6102 if (fake_neighbors[vert] != FAKE_NEIGHBOR_NONE) {
6103 continue;
6104 }
6105 const int island_id = islands::vert_id_get(ss, vert);
6106 const float3 &location = vert_positions[vert];
6107
6108 IndexMaskMemory memory;
6109 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
6110 pbvh, memory, [&](const bke::pbvh::Node &node) {
6111 return node_in_sphere(node, location, max_distance_sq, false);
6112 });
6113 if (nodes_in_sphere.is_empty()) {
6114 continue;
6115 }
6118 nodes_in_sphere.index_range(),
6119 1,
6121 [&](const IndexRange range, NearestVertData nvtd) {
6122 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
6124 vert_positions,
6125 hide_vert,
6126 location,
6127 max_distance_sq,
6128 island_id,
6129 nodes[i],
6130 nvtd);
6131 });
6132 return nvtd;
6133 },
6135 if (nvtd.vert == -1) {
6136 continue;
6137 }
6138 fake_neighbors[vert] = nvtd.vert;
6139 fake_neighbors[nvtd.vert] = vert;
6140 }
6141 break;
6142 }
6144 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
6145 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
6146 const Span<float3> positions = subdiv_ccg.positions;
6147 const BitGroupVector<> grid_hidden = subdiv_ccg.grid_hidden;
6148 for (const int vert : positions.index_range()) {
6149 if (fake_neighbors[vert] != FAKE_NEIGHBOR_NONE) {
6150 continue;
6151 }
6152 const int island_id = islands::vert_id_get(ss, vert);
6153 const float3 &location = positions[vert];
6154 IndexMaskMemory memory;
6155 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
6156 pbvh, memory, [&](const bke::pbvh::Node &node) {
6157 return node_in_sphere(node, location, max_distance_sq, false);
6158 });
6159 if (nodes_in_sphere.is_empty()) {
6160 continue;
6161 }
6164 nodes_in_sphere.index_range(),
6165 1,
6167 [&](const IndexRange range, NearestVertData nvtd) {
6168 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
6170 key,
6171 positions,
6172 grid_hidden,
6173 location,
6174 max_distance_sq,
6175 island_id,
6176 nodes[i],
6177 nvtd);
6178 });
6179 return nvtd;
6180 },
6182 if (nvtd.vert == -1) {
6183 continue;
6184 }
6185 fake_neighbors[vert] = nvtd.vert;
6186 fake_neighbors[nvtd.vert] = vert;
6187 }
6188 break;
6189 }
6191 const BMesh &bm = *ss.bm;
6192 for (const int vert : IndexRange(bm.totvert)) {
6193 if (fake_neighbors[vert] != FAKE_NEIGHBOR_NONE) {
6194 continue;
6195 }
6196 const int island_id = islands::vert_id_get(ss, vert);
6197 const float3 location = BM_vert_at_index(&const_cast<BMesh &>(bm), vert)->co;
6198 IndexMaskMemory memory;
6199 const IndexMask nodes_in_sphere = bke::pbvh::search_nodes(
6200 pbvh, memory, [&](const bke::pbvh::Node &node) {
6201 return node_in_sphere(node, location, max_distance_sq, false);
6202 });
6203 if (nodes_in_sphere.is_empty()) {
6204 continue;
6205 }
6208 nodes_in_sphere.index_range(),
6209 1,
6211 [&](const IndexRange range, NearestVertData nvtd) {
6212 nodes_in_sphere.slice(range).foreach_index([&](const int i) {
6214 ss, location, max_distance_sq, island_id, nodes[i], nvtd);
6215 });
6216 return nvtd;
6217 },
6219 if (nvtd.vert == -1) {
6220 continue;
6221 }
6222 fake_neighbors[vert] = nvtd.vert;
6223 fake_neighbors[nvtd.vert] = vert;
6224 }
6225 break;
6226 }
6227 }
6228}
6229
6230Span<int> fake_neighbors_ensure(const Depsgraph &depsgraph, Object &ob, const float max_dist)
6231{
6233
6234 /* Fake neighbors were already initialized with the same distance, so no need to be
6235 * recalculated. */
6237 ss.fake_neighbors.current_max_distance == max_dist)
6238 {
6240 }
6241
6243 fake_neighbor_init(ob, max_dist);
6244 fake_neighbor_search(depsgraph, ob, max_dist * max_dist, ss.fake_neighbors.fake_neighbor_index);
6245
6247}
6248
6254
6255bool vertex_is_occluded(const Depsgraph &depsgraph,
6256 const Object &object,
6257 const float3 &position,
6258 bool original)
6259{
6260 SculptSession &ss = *object.runtime->sculpt_session;
6261
6262 ViewContext *vc = ss.cache ? ss.cache->vc : &ss.filter_cache->vc;
6263
6266
6267 float3 ray_start;
6268 float3 ray_end;
6269 float3 ray_normal;
6270 float depth = raycast_init(vc, mouse, ray_end, ray_start, ray_normal, original);
6271
6272 ray_normal = ray_normal * -1.0f;
6273 ray_start = position + ray_normal * 0.002f;
6274
6275 bke::pbvh::Tree &pbvh = *bke::object::pbvh_get(const_cast<Object &>(object));
6276
6277 RaycastData srd = {nullptr};
6278 srd.use_original = original;
6279 srd.object = &const_cast<Object &>(object);
6280 srd.is_mid_stroke = ss.cache != nullptr;
6281 srd.hit = false;
6282 srd.ray_start = ray_start;
6283 srd.ray_normal = ray_normal;
6284 srd.depth = depth;
6285 if (pbvh.type() == bke::pbvh::Type::Mesh) {
6286 const Mesh &mesh = *id_cast<const Mesh *>(object.data);
6287 srd.vert_positions = bke::pbvh::vert_positions_eval(depsgraph, object);
6288 srd.faces = mesh.faces();
6289 srd.corner_verts = mesh.corner_verts();
6290 srd.corner_tris = mesh.corner_tris();
6291 }
6292 else if (pbvh.type() == bke::pbvh::Type::Grids) {
6293 srd.subdiv_ccg = ss.subdiv_ccg;
6294 }
6295 vert_random_access_ensure(const_cast<Object &>(object));
6296
6299 pbvh,
6300 [&](bke::pbvh::Node &node, float *tmin) { sculpt_raycast_cb(node, srd, tmin); },
6301 ray_start,
6302 ray_normal,
6303 srd.use_original);
6304
6305 return srd.hit;
6306}
6307
6308namespace islands {
6309
6310int vert_id_get(const SculptSession &ss, const int vert)
6311{
6313 if (!ss.topology_island_cache) {
6314 /* The cache should be calculated whenever it's necessary.
6315 * Still avoid crashing in release builds though. */
6316 return 0;
6317 }
6319 if (!cache.vert_island_ids.is_empty()) {
6320 return cache.vert_island_ids[vert];
6321 }
6322 return 0;
6323}
6324
6326{
6327 ss.topology_island_cache.reset();
6328}
6329
6331 const int verts_num)
6332{
6333 Array<int> island_indices(verts_num);
6334 const int islands_num = vert_sets.calc_reduced_ids(island_indices);
6335 if (islands_num == 1) {
6336 return {};
6337 }
6338
6339 Array<uint8_t> island_ids(island_indices.size());
6340 threading::parallel_for(island_ids.index_range(), 4096, [&](const IndexRange range) {
6341 for (const int i : range) {
6342 island_ids[i] = uint8_t(island_indices[i]);
6343 }
6344 });
6345
6347 cache.vert_island_ids = std::move(island_ids);
6348 return cache;
6349}
6350
6352{
6353 const OffsetIndices<int> faces = mesh.faces();
6354 const Span<int> corner_verts = mesh.corner_verts();
6355 const bke::AttributeAccessor attributes = mesh.attributes();
6356 const VArraySpan<bool> hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
6357 IndexMaskMemory memory;
6358 const IndexMask visible_faces = hide_poly.is_empty() ?
6359 IndexMask(faces.size()) :
6361 faces.index_range(), hide_poly, memory);
6362
6363 AtomicDisjointSet disjoint_set(mesh.verts_num);
6364 visible_faces.foreach_index(
6365 [&](const int face) {
6366 const Span<int> face_verts = corner_verts.slice(faces[face]);
6367 for (const int i : face_verts.index_range().drop_front(1)) {
6368 disjoint_set.join(face_verts.first(), face_verts[i]);
6369 }
6370 },
6371 exec_mode::grain_size(1024));
6372 return vert_disjoint_set_to_islands(disjoint_set, mesh.verts_num);
6373}
6374
6379{
6380 const SculptSession &ss = *object.runtime->sculpt_session;
6381 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
6382 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
6383 AtomicDisjointSet disjoint_set(subdiv_ccg.positions.size());
6384 threading::parallel_for(IndexRange(subdiv_ccg.grids_num), 512, [&](const IndexRange range) {
6385 for (const int grid : range) {
6386 SubdivCCGNeighbors neighbors;
6387 for (const short y : IndexRange(key.grid_size)) {
6388 for (const short x : IndexRange(key.grid_size)) {
6389 const SubdivCCGCoord coord{grid, x, y};
6390 SubdivCCGNeighbors neighbors;
6391 BKE_subdiv_ccg_neighbor_coords_get(subdiv_ccg, coord, true, neighbors);
6392 for (const SubdivCCGCoord neighbor : neighbors.coords) {
6393 disjoint_set.join(coord.to_index(key), neighbor.to_index(key));
6394 }
6395 }
6396 }
6397 }
6398 });
6399
6400 return vert_disjoint_set_to_islands(disjoint_set, subdiv_ccg.positions.size());
6401}
6402
6404{
6405 const SculptSession &ss = *object.runtime->sculpt_session;
6406 const bke::pbvh::Tree &pbvh = *bke::object::pbvh_get(object);
6408 BMesh &bm = *ss.bm;
6409 vert_random_access_ensure(const_cast<Object &>(object));
6410
6411 IndexMaskMemory memory;
6412 const IndexMask node_mask = bke::pbvh::all_leaf_nodes(pbvh, memory);
6413 AtomicDisjointSet disjoint_set(bm.totvert);
6414 node_mask.foreach_index(
6415 [&](const int i) {
6416 for (const BMFace *face :
6418 {
6419 if (BM_elem_flag_test(face, BM_ELEM_HIDDEN)) {
6420 continue;
6421 }
6422 disjoint_set.join(BM_elem_index_get(face->l_first->v),
6423 BM_elem_index_get(face->l_first->next->v));
6424 disjoint_set.join(BM_elem_index_get(face->l_first->v),
6425 BM_elem_index_get(face->l_first->next->next->v));
6426 }
6427 },
6429
6430 return vert_disjoint_set_to_islands(disjoint_set, bm.totvert);
6431}
6432
6434{
6436 switch (bke::object::pbvh_get(object)->type()) {
6438 return calc_topology_islands_mesh(*id_cast<const Mesh *>(object.data));
6440 return calc_topology_islands_grids(object);
6442 return calc_topology_islands_bmesh(object);
6443 }
6445 return {};
6446}
6447
6449{
6450 SculptSession &ss = *object.runtime->sculpt_session;
6451 if (ss.topology_island_cache) {
6452 return;
6453 }
6454 ss.topology_island_cache = std::make_unique<SculptTopologyIslandCache>(calculate_cache(object));
6455}
6456
6457} // namespace islands
6458
6460{
6462 float4x4 unused;
6463 float4x4 mat;
6464
6469 ss.cache->location_symm,
6470 ss.cache->radius,
6471 unused.ptr(),
6472 mat.ptr());
6473
6474 /* NOTE: we ignore the radius scaling done inside of calc_brush_local_mat to
6475 * duplicate prior behavior.
6476 *
6477 * TODO: try disabling this and check that all edge cases work properly.
6478 */
6479 normalize_m4(mat.ptr());
6480
6482 float4x4 tmat = mat * scale;
6483 tmat.y_axis() *= brush.tip_scale_x;
6484 return math::invert(tmat);
6485}
6486
6487
6489{
6490 const bke::AttributeAccessor attributes = mesh.attributes();
6491 this->mask = *attributes.lookup<float>(".sculpt_mask", bke::AttrDomain::Point);
6492 this->hide_vert = *attributes.lookup<bool>(".hide_vert", bke::AttrDomain::Point);
6493 this->hide_poly = *attributes.lookup<bool>(".hide_poly", bke::AttrDomain::Face);
6494 this->face_sets = *attributes.lookup<int>(".sculpt_face_set", bke::AttrDomain::Face);
6495}
6496
6498{
6500 BLI_assert(verts.size() == positions.size());
6501
6502 int i = 0;
6503 for (const BMVert *vert : verts) {
6504 positions[i] = vert->co;
6505 i++;
6506 }
6507}
6508
6509void gather_grids_normals(const SubdivCCG &subdiv_ccg,
6510 const Span<int> grids,
6511 const MutableSpan<float3> normals)
6512{
6514 gather_data_grids(subdiv_ccg, subdiv_ccg.normals.as_span(), grids, normals);
6515}
6516
6518{
6520 int i = 0;
6521 for (const BMVert *vert : verts) {
6522 normals[i] = vert->no;
6523 i++;
6524 }
6525}
6526
6527template<typename T>
6528void gather_data_grids(const SubdivCCG &subdiv_ccg,
6529 const Span<T> src,
6530 const Span<int> grids,
6531 const MutableSpan<T> node_data)
6532{
6534 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
6535 BLI_assert(grids.size() * key.grid_area == node_data.size());
6536
6537 for (const int i : grids.index_range()) {
6538 const IndexRange grids_range = bke::ccg::grid_range(key, grids[i]);
6539 const IndexRange node_range = bke::ccg::grid_range(key, i);
6540 node_data.slice(node_range).copy_from(src.slice(grids_range));
6541 }
6542}
6543
6544template<typename T>
6546 const Set<BMVert *, 0> &verts,
6547 const MutableSpan<T> node_data)
6548{
6550 BLI_assert(verts.size() == node_data.size());
6551
6552 int i = 0;
6553 for (const BMVert *vert : verts) {
6554 node_data[i] = src[BM_elem_index_get(vert)];
6555 i++;
6556 }
6557}
6558
6559template<typename T>
6560void scatter_data_grids(const SubdivCCG &subdiv_ccg,
6561 const Span<T> node_data,
6562 const Span<int> grids,
6563 const MutableSpan<T> dst)
6564{
6566 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
6567 BLI_assert(grids.size() * key.grid_area == node_data.size());
6568
6569 for (const int i : grids.index_range()) {
6570 const IndexRange grids_range = bke::ccg::grid_range(key, grids[i]);
6571 const IndexRange node_range = bke::ccg::grid_range(key, i);
6572 dst.slice(grids_range).copy_from(node_data.slice(node_range));
6573 }
6574}
6575
6576template<typename T>
6577void scatter_data_bmesh(const Span<T> node_data,
6578 const Set<BMVert *, 0> &verts,
6579 const MutableSpan<T> dst)
6580{
6582 BLI_assert(verts.size() == node_data.size());
6583
6584 int i = 0;
6585 for (const BMVert *vert : verts) {
6586 dst[BM_elem_index_get(vert)] = node_data[i];
6587 i++;
6588 }
6589}
6590
6594 Span<int>,
6598 Span<int>,
6603 const Set<BMVert *, 0> &,
6605
6608 Span<int>,
6612 Span<int>,
6616 const Set<BMVert *, 0> &,
6618
6619void calc_local_positions(const Span<float3> vert_positions,
6620 const Span<int> verts,
6621 const float4x4 &mat,
6622 const float3 &plane_center,
6623 const float3 &view_normal,
6624 const eBrushFalloffShape falloff_shape,
6625 const MutableSpan<float3> local_positions)
6626{
6628 BLI_assert(local_positions.size() == verts.size());
6629 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
6630 float4 test_plane;
6631 plane_from_point_normal_v3(test_plane, plane_center, view_normal);
6632 for (const int i : verts.index_range()) {
6633 float3 projected;
6634 closest_to_plane_normalized_v3(projected, test_plane, vert_positions[verts[i]]);
6635 local_positions[i] = math::transform_point(mat, projected);
6636 }
6637 }
6638 else {
6639 for (const int i : verts.index_range()) {
6640 local_positions[i] = math::transform_point(mat, vert_positions[verts[i]]);
6641 }
6642 }
6643}
6644
6646 const float4x4 &mat,
6647 const float3 &plane_center,
6648 const float3 &view_normal,
6649 const eBrushFalloffShape falloff_shape,
6650 const MutableSpan<float3> local_positions)
6651{
6653 BLI_assert(local_positions.size() == positions.size());
6654 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
6655 float4 test_plane;
6656 plane_from_point_normal_v3(test_plane, plane_center, view_normal);
6657 for (const int i : positions.index_range()) {
6658 float3 projected;
6659 closest_to_plane_normalized_v3(projected, test_plane, positions[i]);
6660 local_positions[i] = math::transform_point(mat, projected);
6661 }
6662 }
6663 else {
6664 for (const int i : positions.index_range()) {
6665 local_positions[i] = math::transform_point(mat, positions[i]);
6666 }
6667 }
6668}
6669
6670void calc_local_positions(const Span<float3> vert_positions,
6671 const Span<int> verts,
6672 const float4x4 &mat,
6673 const float3 &plane_center,
6674 const float3 &view_normal,
6675 const eBrushFalloffShape falloff_shape,
6676 const MutableSpan<float2> xy_positions,
6677 const MutableSpan<float> z_positions)
6678{
6680 BLI_assert(xy_positions.size() == verts.size());
6681 BLI_assert(z_positions.size() == verts.size());
6682
6683 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
6684 float4 test_plane;
6685 plane_from_point_normal_v3(test_plane, plane_center, view_normal);
6686 for (const int i : verts.index_range()) {
6687 float3 projected;
6688 closest_to_plane_normalized_v3(projected, test_plane, vert_positions[verts[i]]);
6689 const float3 position = math::transform_point(mat, projected);
6690
6691 xy_positions[i] = position.xy();
6692 z_positions[i] = position.z;
6693 }
6694 }
6695 else {
6696 for (const int i : verts.index_range()) {
6697 const float3 position = math::transform_point(mat, vert_positions[verts[i]]);
6698
6699 xy_positions[i] = position.xy();
6700 z_positions[i] = position.z;
6701 }
6702 }
6703}
6704
6706 const float4x4 &mat,
6707 const float3 &plane_center,
6708 const float3 &view_normal,
6709 const eBrushFalloffShape falloff_shape,
6710 const MutableSpan<float2> xy_positions,
6711 const MutableSpan<float> z_positions)
6712{
6714 BLI_assert(xy_positions.size() == positions.size());
6715 BLI_assert(z_positions.size() == positions.size());
6716
6717 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
6718 float4 test_plane;
6719 plane_from_point_normal_v3(test_plane, plane_center, view_normal);
6720 for (const int i : positions.index_range()) {
6721 float3 projected;
6722 closest_to_plane_normalized_v3(projected, test_plane, positions[i]);
6723 const float3 position = math::transform_point(mat, projected);
6724
6725 xy_positions[i] = position.xy();
6726 z_positions[i] = position.z;
6727 }
6728 }
6729 else {
6730 for (const int i : positions.index_range()) {
6731 const float3 position = math::transform_point(mat, positions[i]);
6732
6733 xy_positions[i] = position.xy();
6734 z_positions[i] = position.z;
6735 }
6736 }
6737}
6738
6739void calc_factors_common_mesh_indexed(const Depsgraph &depsgraph,
6740 const Brush &brush,
6741 const Object &object,
6742 const MeshAttributeData &attribute_data,
6743 const Span<float3> vert_positions,
6744 const Span<float3> vert_normals,
6746 const MutableSpan<float> factors,
6747 const MutableSpan<float> distances)
6748{
6750 const SculptSession &ss = *object.runtime->sculpt_session;
6751 const StrokeCache &cache = *ss.cache;
6752
6753 const Span<int> verts = node.verts();
6754
6755 fill_factor_from_hide_and_mask(attribute_data.hide_vert, attribute_data.mask, verts, factors);
6756 filter_region_clip_factors(ss, vert_positions, verts, factors);
6757 if (brush.flag & BRUSH_FRONTFACE) {
6758 calc_front_face(cache.view_normal_symm, vert_normals, verts, factors);
6759 }
6760
6762 ss, vert_positions, verts, eBrushFalloffShape(brush.falloff_shape), distances);
6763 filter_distances_with_radius(cache.radius, distances, factors);
6764 apply_hardness_to_distances(cache, distances);
6765 calc_brush_strength_factors(cache, brush, distances, factors);
6766
6767 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
6768
6769 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, vert_positions, verts, factors);
6770}
6771
6772void calc_factors_common_mesh(const Depsgraph &depsgraph,
6773 const Brush &brush,
6774 const Object &object,
6775 const MeshAttributeData &attribute_data,
6776 const Span<float3> positions,
6777 const Span<float3> vert_normals,
6779 const MutableSpan<float> factors,
6780 const MutableSpan<float> distances)
6781{
6783 const SculptSession &ss = *object.runtime->sculpt_session;
6784 const StrokeCache &cache = *ss.cache;
6785
6786 const Span<int> verts = node.verts();
6787
6788 fill_factor_from_hide_and_mask(attribute_data.hide_vert, attribute_data.mask, verts, factors);
6789 filter_region_clip_factors(ss, positions, factors);
6790 if (brush.flag & BRUSH_FRONTFACE) {
6791 calc_front_face(cache.view_normal_symm, vert_normals, verts, factors);
6792 }
6793
6794 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
6795 filter_distances_with_radius(cache.radius, distances, factors);
6796 apply_hardness_to_distances(cache, distances);
6797 calc_brush_strength_factors(cache, brush, distances, factors);
6798
6799 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
6800
6801 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
6802}
6803
6804void calc_factors_common_grids(const Depsgraph &depsgraph,
6805 const Brush &brush,
6806 const Object &object,
6807 const Span<float3> positions,
6809 Vector<float> &r_factors,
6810 Vector<float> &r_distances)
6811{
6812 const SculptSession &ss = *object.runtime->sculpt_session;
6813 const StrokeCache &cache = *ss.cache;
6814 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
6815
6816 const Span<int> grids = node.grids();
6817
6818 r_factors.resize(positions.size());
6819 const MutableSpan<float> factors = r_factors;
6820 fill_factor_from_hide_and_mask(subdiv_ccg, grids, factors);
6821 filter_region_clip_factors(ss, positions, factors);
6822 if (brush.flag & BRUSH_FRONTFACE) {
6823 calc_front_face(cache.view_normal_symm, subdiv_ccg, grids, factors);
6824 }
6825
6826 r_distances.resize(positions.size());
6827 const MutableSpan<float> distances = r_distances;
6828 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
6829 filter_distances_with_radius(cache.radius, distances, factors);
6830 apply_hardness_to_distances(cache, distances);
6831 calc_brush_strength_factors(cache, brush, distances, factors);
6832
6833 auto_mask::calc_grids_factors(depsgraph, object, cache.automasking.get(), node, grids, factors);
6834
6835 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
6836}
6837
6838void calc_cube_tip_factors_common_grids(const Depsgraph &depsgraph,
6839 const Brush &brush,
6840 const Object &object,
6841 const float4x4 &mat,
6842 Span<float3> positions,
6844 Vector<float> &r_factors,
6845 Vector<float> &r_distances)
6846{
6847 const SculptSession &ss = *object.runtime->sculpt_session;
6848 const StrokeCache &cache = *ss.cache;
6849 const SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
6850
6851 const Span<int> grids = node.grids();
6852 /* Fill initial factors from hide and mask, and apply front face culling and region clipping.
6853 */
6854 r_factors.resize(positions.size());
6855 const MutableSpan<float> factors = r_factors;
6856 fill_factor_from_hide_and_mask(subdiv_ccg, grids, factors);
6857 filter_region_clip_factors(ss, positions, factors);
6858 if (brush.flag & BRUSH_FRONTFACE) {
6859 calc_front_face(cache.view_normal_symm, subdiv_ccg, grids, factors);
6860 }
6861
6862 /* Calculate local positions. */
6863 Vector<float3> local_positions_storage(positions.size());
6864 MutableSpan<float3> local_positions = local_positions_storage;
6865 calc_local_positions(positions,
6866 mat,
6867 cache.location_symm,
6868 cache.view_normal_symm,
6869 eBrushFalloffShape(brush.falloff_shape),
6870 local_positions);
6871
6872 /* Find the cube distance. */
6873 r_distances.resize(positions.size());
6874 const MutableSpan<float> distances = r_distances;
6875 calc_brush_cube_distances<float3>(brush, local_positions, distances);
6876 filter_distances_with_radius(1.0f, distances, factors);
6877 apply_hardness_to_distances(1.0f, cache.hardness, distances);
6878
6879 /* Apply falloff curve. */
6880 BKE_brush_calc_curve_factors(eBrushCurvePreset(brush.curve_distance_falloff_preset),
6881 brush.curve_distance_falloff,
6882 distances,
6883 1.0f,
6884 factors);
6885
6886 auto_mask::calc_grids_factors(depsgraph, object, cache.automasking.get(), node, grids, factors);
6887
6888 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
6889}
6890
6891void calc_factors_common_bmesh(const Depsgraph &depsgraph,
6892 const Brush &brush,
6893 const Object &object,
6894 const Span<float3> positions,
6896 Vector<float> &r_factors,
6897 Vector<float> &r_distances)
6898{
6899 const SculptSession &ss = *object.runtime->sculpt_session;
6900 const StrokeCache &cache = *ss.cache;
6901
6903
6904 r_factors.resize(verts.size());
6905 const MutableSpan<float> factors = r_factors;
6906 fill_factor_from_hide_and_mask(*ss.bm, verts, factors);
6907 filter_region_clip_factors(ss, positions, factors);
6908 if (brush.flag & BRUSH_FRONTFACE) {
6909 calc_front_face(cache.view_normal_symm, verts, factors);
6910 }
6911
6912 r_distances.resize(verts.size());
6913 const MutableSpan<float> distances = r_distances;
6914 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
6915 filter_distances_with_radius(cache.radius, distances, factors);
6916 apply_hardness_to_distances(cache, distances);
6917 calc_brush_strength_factors(cache, brush, distances, factors);
6918
6919 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
6920
6921 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
6922}
6923
6924void calc_cube_tip_factors_common_bmesh(const Depsgraph &depsgraph,
6925 const Brush &brush,
6926 const Object &object,
6927 const float4x4 &mat,
6928 Span<float3> positions,
6930 Vector<float> &r_factors,
6931 Vector<float> &r_distances)
6932{
6933 const SculptSession &ss = *object.runtime->sculpt_session;
6934 const StrokeCache &cache = *ss.cache;
6935
6937 /* Fill initial factors from hide and mask, and apply front face culling and region clipping.
6938 */
6939 r_factors.resize(verts.size());
6940 const MutableSpan<float> factors = r_factors;
6941 fill_factor_from_hide_and_mask(*ss.bm, verts, factors);
6942 filter_region_clip_factors(ss, positions, factors);
6943 if (brush.flag & BRUSH_FRONTFACE) {
6944 calc_front_face(cache.view_normal_symm, verts, factors);
6945 }
6946
6947 /* Calculate local positions. */
6948 Vector<float3> local_positions_storage(verts.size());
6949 MutableSpan<float3> local_positions = local_positions_storage;
6950 calc_local_positions(positions,
6951 mat,
6952 cache.location_symm,
6953 cache.view_normal_symm,
6954 eBrushFalloffShape(brush.falloff_shape),
6955 local_positions);
6956
6957 /* Find the cube distance. */
6958 r_distances.resize(verts.size());
6959 const MutableSpan<float> distances = r_distances;
6960 calc_brush_cube_distances<float3>(brush, local_positions, distances);
6961 filter_distances_with_radius(1.0f, distances, factors);
6962 apply_hardness_to_distances(1.0f, cache.hardness, distances);
6963
6964 /* Apply falloff curve. */
6965 BKE_brush_calc_curve_factors(eBrushCurvePreset(brush.curve_distance_falloff_preset),
6966 brush.curve_distance_falloff,
6967 distances,
6968 1.0f,
6969 factors);
6970
6971 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
6972
6973 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
6974}
6975
6976void calc_factors_common_from_orig_data_mesh(const Depsgraph &depsgraph,
6977 const Brush &brush,
6978 const Object &object,
6979 const MeshAttributeData &attribute_data,
6980 const Span<float3> positions,
6981 const Span<float3> normals,
6983 const MutableSpan<float> factors,
6984 const MutableSpan<float> distances)
6985{
6986 const SculptSession &ss = *object.runtime->sculpt_session;
6987 const StrokeCache &cache = *ss.cache;
6988
6989 const Span<int> verts = node.verts();
6990
6991 fill_factor_from_hide_and_mask(attribute_data.hide_vert, attribute_data.mask, verts, factors);
6992 filter_region_clip_factors(ss, positions, factors);
6993
6994 if (brush.flag & BRUSH_FRONTFACE) {
6995 calc_front_face(cache.view_normal_symm, normals, factors);
6996 }
6997
6998 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
6999 filter_distances_with_radius(cache.radius, distances, factors);
7000 apply_hardness_to_distances(cache, distances);
7001 calc_brush_strength_factors(cache, brush, distances, factors);
7002
7003 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
7004
7005 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
7006}
7007
7008void calc_factors_common_from_orig_data_grids(const Depsgraph &depsgraph,
7009 const Brush &brush,
7010 const Object &object,
7011 const Span<float3> positions,
7012 const Span<float3> normals,
7014 Vector<float> &r_factors,
7015 Vector<float> &r_distances)
7016{
7017 SculptSession &ss = *object.runtime->sculpt_session;
7018 const StrokeCache &cache = *ss.cache;
7019 SubdivCCG &subdiv_ccg = *ss.subdiv_ccg;
7020
7021 const Span<int> grids = node.grids();
7022
7023 r_factors.resize(positions.size());
7024 const MutableSpan<float> factors = r_factors;
7025 fill_factor_from_hide_and_mask(subdiv_ccg, grids, factors);
7026 filter_region_clip_factors(ss, positions, factors);
7027 if (brush.flag & BRUSH_FRONTFACE) {
7028 calc_front_face(cache.view_normal_symm, normals, factors);
7029 }
7030
7031 r_distances.resize(positions.size());
7032 const MutableSpan<float> distances = r_distances;
7033 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
7034 filter_distances_with_radius(cache.radius, distances, factors);
7035 apply_hardness_to_distances(cache, distances);
7036 calc_brush_strength_factors(cache, brush, distances, factors);
7037
7038 auto_mask::calc_grids_factors(depsgraph, object, cache.automasking.get(), node, grids, factors);
7039
7040 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
7041}
7042
7043void calc_factors_common_from_orig_data_bmesh(const Depsgraph &depsgraph,
7044 const Brush &brush,
7045 const Object &object,
7046 const Span<float3> positions,
7047 const Span<float3> normals,
7049 Vector<float> &r_factors,
7050 Vector<float> &r_distances)
7051{
7052 SculptSession &ss = *object.runtime->sculpt_session;
7053 const StrokeCache &cache = *ss.cache;
7054
7056
7057 r_factors.resize(verts.size());
7058 const MutableSpan<float> factors = r_factors;
7059 fill_factor_from_hide_and_mask(*ss.bm, verts, factors);
7060 filter_region_clip_factors(ss, positions, factors);
7061 if (brush.flag & BRUSH_FRONTFACE) {
7062 calc_front_face(cache.view_normal_symm, normals, factors);
7063 }
7064
7065 r_distances.resize(verts.size());
7066 const MutableSpan<float> distances = r_distances;
7067 calc_brush_distances(ss, positions, eBrushFalloffShape(brush.falloff_shape), distances);
7068 filter_distances_with_radius(cache.radius, distances, factors);
7069 apply_hardness_to_distances(cache, distances);
7070 calc_brush_strength_factors(cache, brush, distances, factors);
7071
7072 auto_mask::calc_vert_factors(depsgraph, object, cache.automasking.get(), node, verts, factors);
7073
7074 calc_brush_texture_factors(PaintMode::Sculpt, ss, brush, positions, factors);
7075}
7076
7078 const Span<int> verts,
7079 const MutableSpan<float> r_factors)
7080{
7082 BLI_assert(verts.size() == r_factors.size());
7083
7084 if (!hide_vert.is_empty()) {
7085 for (const int i : verts.index_range()) {
7086 r_factors[i] = hide_vert[verts[i]] ? 0.0f : 1.0f;
7087 }
7088 }
7089 else {
7090 r_factors.fill(1.0f);
7091 }
7092}
7093
7094void fill_factor_from_hide(const SubdivCCG &subdiv_ccg,
7095 const Span<int> grids,
7096 const MutableSpan<float> r_factors)
7097{
7099 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
7100 BLI_assert(grids.size() * key.grid_area == r_factors.size());
7101
7102 const BitGroupVector<> &grid_hidden = subdiv_ccg.grid_hidden;
7103 if (grid_hidden.is_empty()) {
7104 r_factors.fill(1.0f);
7105 return;
7106 }
7107 for (const int i : grids.index_range()) {
7108 const BitSpan hidden = grid_hidden[grids[i]];
7109 const int start = i * key.grid_area;
7110 for (const int offset : IndexRange(key.grid_area)) {
7111 r_factors[start + offset] = hidden[offset] ? 0.0f : 1.0f;
7112 }
7113 }
7114}
7115
7117{
7119 BLI_assert(verts.size() == r_factors.size());
7120
7121 int i = 0;
7122 for (const BMVert *vert : verts) {
7123 r_factors[i] = BM_elem_flag_test_bool(vert, BM_ELEM_HIDDEN) ? 0.0f : 1.0f;
7124 i++;
7125 }
7126}
7127
7129 const Span<float> mask,
7130 const Span<int> verts,
7131 const MutableSpan<float> r_factors)
7132{
7134 BLI_assert(verts.size() == r_factors.size());
7135
7136 if (!mask.is_empty()) {
7137 for (const int i : verts.index_range()) {
7138 r_factors[i] = 1.0f - mask[verts[i]];
7139 }
7140 }
7141 else {
7142 r_factors.fill(1.0f);
7143 }
7144
7145 if (!hide_vert.is_empty()) {
7146 for (const int i : verts.index_range()) {
7147 if (hide_vert[verts[i]]) {
7148 r_factors[i] = 0.0f;
7149 }
7150 }
7151 }
7152}
7153
7155 const Set<BMVert *, 0> &verts,
7156 const MutableSpan<float> r_factors)
7157{
7159 BLI_assert(verts.size() == r_factors.size());
7160
7161 /* TODO: Avoid overhead of accessing attributes for every bke::pbvh::Tree node. */
7162 const int mask_offset = CustomData_get_offset_named(&bm.vdata, CD_PROP_FLOAT, ".sculpt_mask");
7163 int i = 0;
7164 for (const BMVert *vert : verts) {
7165 r_factors[i] = (mask_offset == -1) ? 1.0f : 1.0f - BM_ELEM_CD_GET_FLOAT(vert, mask_offset);
7166 if (BM_elem_flag_test(vert, BM_ELEM_HIDDEN)) {
7167 r_factors[i] = 0.0f;
7168 }
7169 i++;
7170 }
7171}
7172
7174 const Span<int> grids,
7175 const MutableSpan<float> r_factors)
7176{
7178 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
7179 BLI_assert(grids.size() * key.grid_area == r_factors.size());
7180
7181 if (!subdiv_ccg.masks.is_empty()) {
7182 const Span<float> masks = subdiv_ccg.masks;
7183 for (const int i : grids.index_range()) {
7184 const Span src = masks.slice(bke::ccg::grid_range(key, grids[i]));
7185 MutableSpan dst = r_factors.slice(bke::ccg::grid_range(key, i));
7186 for (const int offset : dst.index_range()) {
7187 dst[offset] = 1.0f - src[offset];
7188 }
7189 }
7190 }
7191 else {
7192 r_factors.fill(1.0f);
7193 }
7194
7195 const BitGroupVector<> &grid_hidden = subdiv_ccg.grid_hidden;
7196 if (!grid_hidden.is_empty()) {
7197 for (const int i : grids.index_range()) {
7198 const BitSpan hidden = grid_hidden[grids[i]];
7199 const int start = i * key.grid_area;
7200 for (const int offset : IndexRange(key.grid_area)) {
7201 if (hidden[offset]) {
7202 r_factors[start + offset] = 0.0f;
7203 }
7204 }
7205 }
7206 }
7207}
7208
7209void calc_front_face(const float3 &view_normal,
7210 const Span<float3> vert_normals,
7211 const Span<int> verts,
7212 const MutableSpan<float> factors)
7213{
7215 BLI_assert(verts.size() == factors.size());
7216
7217 for (const int i : verts.index_range()) {
7218 const float dot = math::dot(view_normal, vert_normals[verts[i]]);
7219 factors[i] *= std::max(dot, 0.0f);
7220 }
7221}
7222
7223void calc_front_face(const float3 &view_normal,
7224 const Span<float3> normals,
7225 const MutableSpan<float> factors)
7226{
7228 BLI_assert(normals.size() == factors.size());
7229
7230 for (const int i : normals.index_range()) {
7231 const float dot = math::dot(view_normal, normals[i]);
7232 factors[i] *= std::max(dot, 0.0f);
7233 }
7234}
7235void calc_front_face(const float3 &view_normal,
7236 const SubdivCCG &subdiv_ccg,
7237 const Span<int> grids,
7238 const MutableSpan<float> factors)
7239{
7241 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
7242 const Span<float3> normals = subdiv_ccg.normals;
7243 BLI_assert(grids.size() * key.grid_area == factors.size());
7244
7245 for (const int i : grids.index_range()) {
7246 const Span<float3> grid_normals = normals.slice(bke::ccg::grid_range(key, grids[i]));
7247 MutableSpan<float> grid_factors = factors.slice(bke::ccg::grid_range(key, i));
7248 for (const int offset : grid_factors.index_range()) {
7249 const float dot = math::dot(view_normal, grid_normals[offset]);
7250 grid_factors[offset] *= std::max(dot, 0.0f);
7251 }
7252 }
7253}
7254
7255void calc_front_face(const float3 &view_normal,
7256 const Set<BMVert *, 0> &verts,
7257 const MutableSpan<float> factors)
7258{
7260 BLI_assert(verts.size() == factors.size());
7261
7262 int i = 0;
7263 for (const BMVert *vert : verts) {
7264 const float dot = math::dot(view_normal, float3(vert->no));
7265 factors[i] *= std::max(dot, 0.0f);
7266 i++;
7267 }
7268}
7269
7270void calc_front_face(const float3 &view_normal,
7271 const Set<BMFace *, 0> &faces,
7272 const MutableSpan<float> factors)
7273{
7275 BLI_assert(faces.size() == factors.size());
7276
7277 int i = 0;
7278 for (const BMFace *face : faces) {
7279 const float dot = math::dot(view_normal, float3(face->no));
7280 factors[i] *= std::max(dot, 0.0f);
7281 i++;
7282 }
7283}
7284
7286 const Span<float3> positions,
7287 const Span<int> verts,
7288 const MutableSpan<float> factors)
7289{
7291 BLI_assert(verts.size() == factors.size());
7292
7293 const RegionView3D *rv3d = ss.cache ? ss.cache->vc->rv3d : ss.rv3d;
7294 const View3D *v3d = ss.cache ? ss.cache->vc->v3d : ss.v3d;
7295 if (!RV3D_CLIPPING_ENABLED(v3d, rv3d)) {
7296 return;
7297 }
7298
7299 const ePaintSymmetryFlags mirror_symmetry_pass = ss.cache ? ss.cache->mirror_symmetry_pass :
7301 const int radial_symmetry_pass = ss.cache ? ss.cache->radial_symmetry_pass : 0;
7302 const float4x4 symm_rot_mat_inv = ss.cache ? ss.cache->symm_rot_mat_inv : float4x4::identity();
7303 for (const int i : verts.index_range()) {
7304 float3 symm_co = symmetry_flip(positions[verts[i]], mirror_symmetry_pass);
7305 if (radial_symmetry_pass) {
7306 symm_co = math::transform_point(symm_rot_mat_inv, symm_co);
7307 }
7308 if (ED_view3d_clipping_test(rv3d, symm_co, true)) {
7309 factors[i] = 0.0f;
7310 }
7311 }
7312}
7313
7315 const Span<float3> positions,
7316 const MutableSpan<float> factors)
7317{
7319 BLI_assert(positions.size() == factors.size());
7320
7321 const RegionView3D *rv3d = ss.cache ? ss.cache->vc->rv3d : ss.rv3d;
7322 const View3D *v3d = ss.cache ? ss.cache->vc->v3d : ss.v3d;
7323 if (!RV3D_CLIPPING_ENABLED(v3d, rv3d)) {
7324 return;
7325 }
7326
7327 const ePaintSymmetryFlags mirror_symmetry_pass = ss.cache ? ss.cache->mirror_symmetry_pass :
7329 const int radial_symmetry_pass = ss.cache ? ss.cache->radial_symmetry_pass : 0;
7330 const float4x4 symm_rot_mat_inv = ss.cache ? ss.cache->symm_rot_mat_inv : float4x4::identity();
7331 for (const int i : positions.index_range()) {
7332 float3 symm_co = symmetry_flip(positions[i], mirror_symmetry_pass);
7333 if (radial_symmetry_pass) {
7334 symm_co = math::transform_point(symm_rot_mat_inv, symm_co);
7335 }
7336 if (ED_view3d_clipping_test(rv3d, symm_co, true)) {
7337 factors[i] = 0.0f;
7338 }
7339 }
7340}
7341
7343 const Span<float3> positions,
7344 const Span<int> verts,
7345 const eBrushFalloffShape falloff_shape,
7346 const MutableSpan<float> r_distances)
7347{
7348 BLI_assert(verts.size() == r_distances.size());
7349
7350 const float3 &test_location = ss.cache ? ss.cache->location_symm : ss.cursor_location;
7351 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE && (ss.cache || ss.filter_cache)) {
7352 /* The tube falloff shape requires the cached view normal. */
7353 const float3 &view_normal = ss.cache ? ss.cache->view_normal_symm :
7355 float4 test_plane;
7356 plane_from_point_normal_v3(test_plane, test_location, view_normal);
7357 for (const int i : verts.index_range()) {
7358 float3 projected;
7359 closest_to_plane_normalized_v3(projected, test_plane, positions[verts[i]]);
7360 r_distances[i] = math::distance_squared(projected, test_location);
7361 }
7362 }
7363 else {
7364 for (const int i : verts.index_range()) {
7365 r_distances[i] = math::distance_squared(test_location, positions[verts[i]]);
7366 }
7367 }
7368}
7369
7371 const Span<float3> positions,
7372 const Span<int> verts,
7373 const eBrushFalloffShape falloff_shape,
7374 const MutableSpan<float> r_distances)
7375{
7377 calc_brush_distances_squared(ss, positions, verts, falloff_shape, r_distances);
7378 for (float &value : r_distances) {
7379 value = std::sqrt(value);
7380 }
7381}
7382
7384 const Span<float3> positions,
7385 const eBrushFalloffShape falloff_shape,
7386 const MutableSpan<float> r_distances)
7387{
7388 BLI_assert(positions.size() == r_distances.size());
7389
7390 const float3 &test_location = ss.cache ? ss.cache->location_symm : ss.cursor_location;
7391 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE && (ss.cache || ss.filter_cache)) {
7392 /* The tube falloff shape requires the cached view normal. */
7393 const float3 &view_normal = ss.cache ? ss.cache->view_normal_symm :
7395 float4 test_plane;
7396 plane_from_point_normal_v3(test_plane, test_location, view_normal);
7397 for (const int i : positions.index_range()) {
7398 float3 projected;
7399 closest_to_plane_normalized_v3(projected, test_plane, positions[i]);
7400 r_distances[i] = math::distance_squared(projected, test_location);
7401 }
7402 }
7403 else {
7404 for (const int i : positions.index_range()) {
7405 r_distances[i] = math::distance_squared(test_location, positions[i]);
7406 }
7407 }
7408}
7409
7411 const Span<float3> positions,
7412 const eBrushFalloffShape falloff_shape,
7413 const MutableSpan<float> r_distances)
7414{
7416 calc_brush_distances_squared(ss, positions, falloff_shape, r_distances);
7417 for (float &value : r_distances) {
7418 value = std::sqrt(value);
7419 }
7420}
7421
7422void filter_distances_with_radius(const float radius,
7423 const Span<float> distances,
7424 const MutableSpan<float> factors)
7425{
7427 for (const int i : distances.index_range()) {
7428 if (distances[i] >= radius) {
7429 factors[i] = 0.0f;
7430 }
7431 }
7432}
7433
7434template<typename T>
7436 const Span<T> positions,
7437 const MutableSpan<float> r_distances)
7438{
7440 BLI_assert(r_distances.size() == positions.size());
7441
7442 const float roundness = brush.tip_roundness;
7443 const float roundness_rcp = math::safe_rcp(roundness);
7444 const float hardness = 1.0f - roundness;
7445 const T hardness_vec(hardness);
7446 const T zero(0.0f);
7447
7448 for (const int i : positions.index_range()) {
7449 const T local = math::abs(positions[i]);
7450
7451 if (math::reduce_max(local) > 1.0f) {
7452 r_distances[i] = 1.0f;
7453 continue;
7454 }
7455
7456 const T excess = math::max(local - hardness_vec, zero);
7457 if (math::reduce_max(excess) == 0.0f) {
7458 r_distances[i] = 0.0f;
7459 continue;
7460 }
7461
7462 const float distance = math::min(math::length(excess) * roundness_rcp, 1.0f);
7463 r_distances[i] = distance;
7464 }
7465}
7467 const Span<float2> positions,
7468 MutableSpan<float> r_distances);
7470 const Span<float3> positions,
7471 MutableSpan<float> r_distances);
7472
7473void apply_hardness_to_distances(const float radius,
7474 const float hardness,
7475 const MutableSpan<float> distances)
7476{
7478 if (hardness == 0.0f) {
7479 return;
7480 }
7481 const float threshold = hardness * radius;
7482 if (hardness == 1.0f) {
7483 for (const int i : distances.index_range()) {
7484 distances[i] = distances[i] < threshold ? 0.0f : radius;
7485 }
7486 return;
7487 }
7488 const float radius_inv = math::rcp(radius);
7489 const float hardness_inv_rcp = math::rcp(1.0f - hardness);
7490 for (const int i : distances.index_range()) {
7491 if (distances[i] < threshold) {
7492 distances[i] = 0.0f;
7493 }
7494 else {
7495 const float radius_factor = (distances[i] * radius_inv - hardness) * hardness_inv_rcp;
7496 distances[i] = radius_factor * radius;
7497 }
7498 }
7499}
7500
7502 const Brush &brush,
7503 const Span<float> distances,
7504 const MutableSpan<float> factors)
7505{
7506 BKE_brush_calc_curve_factors(eBrushCurvePreset(brush.curve_distance_falloff_preset),
7507 brush.curve_distance_falloff,
7508 distances,
7509 cache.radius,
7510 factors);
7511}
7512
7514 const SculptSession &ss,
7515 const Brush &brush,
7516 const Span<float3> vert_positions,
7517 const Span<int> verts,
7518 const MutableSpan<float> factors)
7519{
7521 BLI_assert(verts.size() == factors.size());
7522
7523 const MTex *mtex = BKE_brush_mask_texture_get(&brush, paint_mode);
7524 if (!mtex->tex) {
7525 return;
7526 }
7527 const int thread_id = BLI_task_parallel_thread_id(nullptr);
7528
7529 for (const int i : verts.index_range()) {
7530 if (factors[i] == 0.0f) {
7531 continue;
7532 }
7533 float texture_value;
7534 float4 texture_rgba;
7535 /* NOTE: This is not a thread-safe call. */
7537 paint_mode, ss, brush, vert_positions[verts[i]], thread_id, &texture_value, texture_rgba);
7538
7539 factors[i] *= texture_value;
7540 }
7541}
7542
7544 const SculptSession &ss,
7545 const Brush &brush,
7546 const Span<float3> positions,
7547 const MutableSpan<float> factors)
7548{
7550 BLI_assert(positions.size() == factors.size());
7551
7552 const MTex *mtex = BKE_brush_mask_texture_get(&brush, paint_mode);
7553 if (!mtex->tex) {
7554 return;
7555 }
7556 const int thread_id = BLI_task_parallel_thread_id(nullptr);
7557
7558 for (const int i : positions.index_range()) {
7559 if (factors[i] == 0.0f) {
7560 continue;
7561 }
7562 float texture_value;
7563 float4 texture_rgba;
7564 /* NOTE: This is not a thread-safe call. */
7566 paint_mode, ss, brush, positions[i], thread_id, &texture_value, texture_rgba);
7567
7568 factors[i] *= texture_value;
7569 }
7570}
7571
7573 const Span<float3> positions,
7574 const Span<float3> orig_positions)
7575{
7577 BLI_assert(translations.size() == orig_positions.size());
7578 BLI_assert(translations.size() == positions.size());
7579 for (const int i : translations.index_range()) {
7580 const float3 prev_translation = positions[i] - orig_positions[i];
7581 translations[i] -= prev_translation;
7582 }
7583}
7584
7585#ifndef NDEBUG
7586static bool contains_nan(const Span<float> values)
7587{
7588 return std::any_of(values.begin(), values.end(), [&](const float v) { return std::isnan(v); });
7589}
7590#endif
7591
7592void apply_translations(const Span<float3> translations,
7593 const Span<int> verts,
7594 const MutableSpan<float3> positions)
7595{
7597 BLI_assert(verts.size() == translations.size());
7598 BLI_assert(!contains_nan(translations.cast<float>()));
7599
7600 for (const int i : verts.index_range()) {
7601 const int vert = verts[i];
7602 positions[vert] += translations[i];
7603 }
7604}
7605
7606void apply_translations(const Span<float3> translations,
7607 const Span<int> grids,
7608 SubdivCCG &subdiv_ccg)
7609{
7611 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
7612 MutableSpan<float3> positions = subdiv_ccg.positions;
7613 BLI_assert(grids.size() * key.grid_area == translations.size());
7614 BLI_assert(!contains_nan(translations.cast<float>()));
7615
7616 for (const int i : grids.index_range()) {
7617 const Span<float3> grid_translations = translations.slice(bke::ccg::grid_range(key, i));
7618 MutableSpan<float3> grid_positions = positions.slice(bke::ccg::grid_range(key, grids[i]));
7619 for (const int offset : grid_positions.index_range()) {
7620 grid_positions[offset] += grid_translations[offset];
7621 }
7622 }
7623}
7624
7625void apply_translations(const Span<float3> translations, const Set<BMVert *, 0> &verts)
7626{
7628 BLI_assert(verts.size() == translations.size());
7629 BLI_assert(!contains_nan(translations.cast<float>()));
7630
7631 int i = 0;
7632 for (BMVert *vert : verts) {
7633 add_v3_v3(vert->co, translations[i]);
7634 i++;
7635 }
7636}
7637
7638void project_translations(const MutableSpan<float3> translations, const float3 &plane)
7639{
7641 /* Equivalent to #project_plane_v3_v3v3. */
7642 const float len_sq = math::length_squared(plane);
7643 if (len_sq < std::numeric_limits<float>::epsilon()) {
7644 return;
7645 }
7646 const float dot_factor = -math::rcp(len_sq);
7647 for (const int i : translations.index_range()) {
7648 translations[i] += plane * math::dot(translations[i], plane) * dot_factor;
7649 }
7650}
7651
7653 const Span<int> verts,
7654 const MutableSpan<float3> translations)
7655{
7657 BLI_assert(verts.size() == translations.size());
7658
7659 for (const int i : verts.index_range()) {
7660 translations[i] = math::transform_point(deform_imats[verts[i]], translations[i]);
7661 }
7662}
7663
7665 const SculptSession &ss,
7666 const Span<float3> positions,
7667 const Span<int> verts,
7668 const MutableSpan<float3> translations)
7669{
7671 BLI_assert(verts.size() == translations.size());
7672
7673 const StrokeCache *cache = ss.cache;
7674 if (!cache) {
7675 return;
7676 }
7677 for (const int axis : IndexRange(3)) {
7678 if (sd.flags & (SCULPT_LOCK_X << axis)) {
7679 for (float3 &translation : translations) {
7680 translation[axis] = 0.0f;
7681 }
7682 continue;
7683 }
7684
7685 if (!(cache->mirror_modifier_clip.flag & (uint8_t(StrokeFlags::ClipX) << axis))) {
7686 continue;
7687 }
7688
7689 const float4x4 mirror(cache->mirror_modifier_clip.mat);
7690 const float4x4 mirror_inverse(cache->mirror_modifier_clip.mat_inv);
7691 for (const int i : verts.index_range()) {
7692 const int vert = verts[i];
7693
7694 /* Transform into the space of the mirror plane, check translations, then transform back. */
7695 float3 co_mirror = math::transform_point(mirror, positions[vert]);
7696 if (math::abs(co_mirror[axis]) > cache->mirror_modifier_clip.tolerance[axis]) {
7697 continue;
7698 }
7699 /* Clear the translation in the local space of the mirror object. */
7700 co_mirror[axis] = 0.0f;
7701 const float3 co_local = math::transform_point(mirror_inverse, co_mirror);
7702 translations[i][axis] = co_local[axis] - positions[vert][axis];
7703 }
7704 }
7705}
7706
7708 const SculptSession &ss,
7709 const Span<float3> positions,
7710 const MutableSpan<float3> translations)
7711{
7713 BLI_assert(positions.size() == translations.size());
7714
7715 const StrokeCache *cache = ss.cache;
7716 if (!cache) {
7717 return;
7718 }
7719 for (const int axis : IndexRange(3)) {
7720 if (sd.flags & (SCULPT_LOCK_X << axis)) {
7721 for (float3 &translation : translations) {
7722 translation[axis] = 0.0f;
7723 }
7724 continue;
7725 }
7726
7727 if (!(cache->mirror_modifier_clip.flag & (uint8_t(StrokeFlags::ClipX) << axis))) {
7728 continue;
7729 }
7730
7731 const float4x4 mirror(cache->mirror_modifier_clip.mat);
7732 const float4x4 mirror_inverse(cache->mirror_modifier_clip.mat_inv);
7733 for (const int i : positions.index_range()) {
7734 /* Transform into the space of the mirror plane, check translations, then transform back. */
7735 float3 co_mirror = math::transform_point(mirror, positions[i]);
7736 if (math::abs(co_mirror[axis]) > cache->mirror_modifier_clip.tolerance[axis]) {
7737 continue;
7738 }
7739 /* Clear the translation in the local space of the mirror object. */
7740 co_mirror[axis] = 0.0f;
7741 const float3 co_local = math::transform_point(mirror_inverse, co_mirror);
7742 translations[i][axis] = co_local[axis] - positions[i][axis];
7743 }
7744 }
7745}
7746
7747std::optional<ShapeKeyData> ShapeKeyData::from_object(Object &object)
7748{
7749 Mesh &mesh = *id_cast<Mesh *>(object.data);
7750 Key *keys = mesh.key;
7751 if (!keys) {
7752 return std::nullopt;
7753 }
7754 const int active_index = object.shapenr - 1;
7755 const KeyBlock *active_key = BKE_keyblock_find_by_index(keys, active_index);
7756 if (!active_key) {
7757 return std::nullopt;
7758 }
7760 data.active_key_data = {static_cast<float3 *>(active_key->data), active_key->totelem};
7761 data.basis_key_active = active_key == keys->refkey;
7762 if (const std::optional<Array<bool>> dependent = BKE_keyblock_get_dependent_keys(keys,
7763 active_index))
7764 {
7765
7766 for (const auto [i, other_key] : keys->block.enumerate()) {
7767 if ((&other_key != active_key) && (*dependent)[i]) {
7768 data.dependent_keys.append({static_cast<float3 *>(other_key.data), other_key.totelem});
7769 }
7770 }
7771 }
7772 return data;
7773}
7774
7775PositionDeformData::PositionDeformData(const Depsgraph &depsgraph, Object &object_orig)
7776{
7777 Mesh &mesh = *id_cast<Mesh *>(object_orig.data);
7778 this->eval = bke::pbvh::vert_positions_eval(depsgraph, object_orig);
7779
7780 if (!object_orig.runtime->sculpt_session->deform_imats.is_empty()) {
7781 deform_imats_ = object_orig.runtime->sculpt_session->deform_imats;
7782 }
7783 orig_ = mesh.vert_positions_for_write();
7784
7785 MutableSpan eval_mut = bke::pbvh::vert_positions_eval_for_write(depsgraph, object_orig);
7786 if (eval_mut.data() != orig_.data()) {
7787 eval_mut_ = eval_mut;
7788 }
7789
7790 shape_key_data_ = ShapeKeyData::from_object(object_orig);
7791}
7792
7793void PositionDeformData::deform(MutableSpan<float3> translations, const Span<int> verts) const
7794{
7796 if (eval_mut_) {
7797 /* Apply translations to the evaluated mesh. This is necessary because multiple brush
7798 * evaluations can happen in between object reevaluations (otherwise just deforming the
7799 * original positions would be enough). */
7800 apply_translations(translations, verts, *eval_mut_);
7801 }
7802
7803 if (deform_imats_) {
7804 /* Apply the reverse procedural deformation, since subsequent translation happens to the state
7805 * from "before" deforming modifiers. */
7806 apply_crazyspace_to_translations(*deform_imats_, verts, translations);
7807 }
7808
7809 if (shape_key_data_) {
7810 if (!shape_key_data_->dependent_keys.is_empty()) {
7811 for (MutableSpan<float3> data : shape_key_data_->dependent_keys) {
7812 apply_translations(translations, verts, data);
7813 }
7814 }
7815
7816 if (shape_key_data_->basis_key_active) {
7817 /* The basis key positions and the mesh positions are always kept in sync. */
7818 apply_translations(translations, verts, orig_);
7819 }
7820 apply_translations(translations, verts, shape_key_data_->active_key_data);
7821 }
7822 else {
7823 apply_translations(translations, verts, orig_);
7824 }
7825}
7826
7827void filter_translations(const MutableSpan<float3> translations, const Span<float> factors)
7828{
7830 for (const int i : translations.index_range()) {
7831 if (factors[i] == 0.0f) {
7832 translations[i] = float3(0.0f);
7833 }
7834 }
7835}
7836
7837void scale_translations(const MutableSpan<float3> translations, const Span<float> factors)
7838{
7840 for (const int i : translations.index_range()) {
7841 translations[i] *= factors[i];
7842 }
7843}
7844
7845void scale_translations(const MutableSpan<float3> translations, const float factor)
7846{
7848 if (factor == 1.0f) {
7849 return;
7850 }
7851 for (const int i : translations.index_range()) {
7852 translations[i] *= factor;
7853 }
7854}
7855
7856void scale_factors(const MutableSpan<float> factors, const float strength)
7857{
7859 if (strength == 1.0f) {
7860 return;
7861 }
7862 for (float &factor : factors) {
7863 factor *= strength;
7864 }
7865}
7866
7867void scale_factors(const MutableSpan<float> factors, const Span<float> strengths)
7868{
7870 BLI_assert(factors.size() == strengths.size());
7871
7872 for (const int i : factors.index_range()) {
7873 factors[i] *= strengths[i];
7874 }
7875}
7876
7878 const Span<float> factors,
7879 const MutableSpan<float3> r_translations)
7880{
7882 BLI_assert(r_translations.size() == factors.size());
7883
7884 for (const int i : factors.index_range()) {
7885 r_translations[i] = offset * factors[i];
7886 }
7887}
7888
7890 const Span<int> verts,
7891 const Span<float3> old_positions,
7892 const MutableSpan<float3> translations)
7893{
7895 BLI_assert(new_positions.size() == verts.size());
7896 for (const int i : verts.index_range()) {
7897 translations[i] = new_positions[i] - old_positions[verts[i]];
7898 }
7899}
7900
7902 const Span<float3> old_positions,
7903 const MutableSpan<float3> translations)
7904{
7906 BLI_assert(new_positions.size() == old_positions.size());
7907 for (const int i : new_positions.index_range()) {
7908 translations[i] = new_positions[i] - old_positions[i];
7909 }
7910}
7911
7913 const IndexMask &node_mask,
7914 Array<int> &node_data)
7915{
7917 node_data.reinitialize(node_mask.size() + 1);
7918 node_mask.foreach_index_optimized<int>(
7919 [&](const int i, const int pos) { node_data[pos] = nodes[i].verts().size(); });
7921}
7922
7925 const IndexMask &node_mask,
7926 Array<int> &node_data)
7927{
7929 node_data.reinitialize(node_mask.size() + 1);
7930 node_mask.foreach_index_optimized<int>([&](const int i, const int pos) {
7931 node_data[pos] = nodes[i].grids().size() * key.grid_area;
7932 });
7934}
7935
7937 const IndexMask &node_mask,
7938 Array<int> &node_data)
7939{
7941 node_data.reinitialize(node_mask.size() + 1);
7942 node_mask.foreach_index([&](const int i, const int pos) {
7943 node_data[pos] =
7945 });
7947}
7948
7950 const Span<int> corner_verts,
7951 const GroupedSpan<int> vert_to_face,
7952 const Span<bool> hide_poly,
7953 const Span<int> verts,
7954 Vector<int> &r_offset_data,
7955 Vector<int> &r_data)
7956{
7958 BLI_assert(corner_verts.size() == faces.total_size());
7959 r_offset_data.resize(verts.size() + 1);
7960 r_data.clear();
7961 for (const int i : verts.index_range()) {
7962 r_offset_data[i] = r_data.size();
7963 append_neighbors_to_vector(faces, corner_verts, vert_to_face, hide_poly, verts[i], r_data);
7964 }
7965 r_offset_data.last() = r_data.size();
7966 return GroupedSpan<int>(r_offset_data.as_span(), r_data.as_span());
7967}
7968
7970 const Span<int> grids,
7971 Vector<int> &r_offset_data,
7972 Vector<int> &r_data)
7973{
7975 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
7976 SubdivCCGNeighbors neighbors;
7977
7978 r_offset_data.resize(key.grid_area * grids.size() + 1);
7979 r_data.clear();
7980
7981 for (const int i : grids.index_range()) {
7982 const int grid = grids[i];
7983 const int node_verts_start = i * key.grid_area;
7984
7985 for (const short y : IndexRange(key.grid_size)) {
7986 for (const short x : IndexRange(key.grid_size)) {
7987 const int offset = CCG_grid_xy_to_index(key.grid_size, x, y);
7988 r_offset_data[node_verts_start + offset] = r_data.size();
7989
7990 SubdivCCGCoord coord{};
7991 coord.grid_index = grid;
7992 coord.x = x;
7993 coord.y = y;
7994 BKE_subdiv_ccg_neighbor_coords_get(subdiv_ccg, coord, false, neighbors);
7995 for (const SubdivCCGCoord neighbor : neighbors.coords) {
7996 r_data.append(neighbor.to_index(key));
7997 }
7998 }
7999 }
8000 }
8001 r_offset_data.last() = r_data.size();
8002 return GroupedSpan<int>(r_offset_data.as_span(), r_data.as_span());
8003}
8004
8006 Vector<int> &r_offset_data,
8007 Vector<BMVert *> &r_data)
8008{
8010 r_offset_data.resize(verts.size() + 1);
8011 r_data.clear();
8012
8013 BMeshNeighborVerts neighbor_data;
8014 int i = 0;
8015 for (BMVert *vert : verts) {
8016 r_offset_data[i] = r_data.size();
8017 r_data.extend(vert_neighbors_get_bmesh(*vert, neighbor_data));
8018 i++;
8019 }
8020 r_offset_data.last() = r_data.size();
8021 return GroupedSpan<BMVert *>(r_offset_data.as_span(), r_data.as_span());
8022}
8023
8024template<bool use_factors>
8026 const Span<int> corner_verts,
8027 const GroupedSpan<int> vert_to_face,
8028 const BitSpan boundary_verts,
8029 const Set<OrderedEdge> &boundary_edges,
8030 const Span<bool> hide_poly,
8031 const Span<int> verts,
8032 const Span<float> factors,
8033 Vector<int> &r_offset_data,
8034 Vector<int> &r_data)
8035{
8037 BLI_assert(corner_verts.size() == faces.total_size());
8038 if constexpr (use_factors) {
8039 BLI_assert(verts.size() == factors.size());
8040 }
8041
8042 r_offset_data.resize(verts.size() + 1);
8043 r_data.clear();
8044
8045 for (const int i : verts.index_range()) {
8046 const int vert = verts[i];
8047 const int vert_start = r_data.size();
8048 r_offset_data[i] = vert_start;
8049 if constexpr (use_factors) {
8050 if (factors[i] == 0.0f) {
8051 continue;
8052 }
8053 }
8054 append_neighbors_to_vector(faces, corner_verts, vert_to_face, hide_poly, vert, r_data);
8055
8056 if (boundary_verts[vert]) {
8057 /* Do not include neighbors of corner vertices. */
8058 if (r_data.size() == vert_start + 2) {
8059 r_data.resize(vert_start);
8060 }
8061 else {
8062 /* Only include other boundary vertices as neighbors of boundary vertices. */
8063 for (int neighbor_i = r_data.size() - 1; neighbor_i >= vert_start; neighbor_i--) {
8064 OrderedEdge edge(r_data[neighbor_i], vert);
8065 if (!boundary_edges.contains(OrderedEdge(r_data[neighbor_i], vert))) {
8066 r_data.remove_and_reorder(neighbor_i);
8067 }
8068 }
8069 }
8070 }
8071 }
8072 r_offset_data.last() = r_data.size();
8073 return GroupedSpan<int>(r_offset_data.as_span(), r_data.as_span());
8074}
8075
8077 const Span<int> corner_verts,
8078 const GroupedSpan<int> vert_to_face,
8079 const BitSpan boundary_verts,
8080 const Set<OrderedEdge> &boundary_edges,
8081 const Span<bool> hide_poly,
8082 const Span<int> verts,
8083 const Span<float> factors,
8084 Vector<int> &r_offset_data,
8085 Vector<int> &r_data)
8086{
8088 corner_verts,
8089 vert_to_face,
8090 boundary_verts,
8091 boundary_edges,
8092 hide_poly,
8093 verts,
8094 factors,
8095 r_offset_data,
8096 r_data);
8097}
8098
8100 const Span<int> corner_verts,
8101 const GroupedSpan<int> vert_to_face,
8102 const BitSpan boundary_verts,
8103 const Set<OrderedEdge> &boundary_edges,
8104 const Span<bool> hide_poly,
8105 const Span<int> verts,
8106 Vector<int> &r_offset_data,
8107 Vector<int> &r_data)
8108{
8110 corner_verts,
8111 vert_to_face,
8112 boundary_verts,
8113 boundary_edges,
8114 hide_poly,
8115 verts,
8116 {},
8117 r_offset_data,
8118 r_data);
8119}
8120
8122 const Span<int> corner_verts,
8123 const BitSpan boundary_verts,
8124 const Set<OrderedEdge> &boundary_edges,
8125 const SubdivCCG &subdiv_ccg,
8126 const Span<int> grids,
8128{
8130 const CCGKey key = BKE_subdiv_ccg_key_top_level(subdiv_ccg);
8131
8132 BLI_assert(grids.size() * key.grid_area == result.size());
8133
8134 for (const int i : grids.index_range()) {
8135 const int grid = grids[i];
8136 const int node_verts_start = i * key.grid_area;
8137
8138 /* TODO: This loop could be optimized in the future by skipping unnecessary logic for
8139 * non-boundary grid vertices. */
8140 for (const int y : IndexRange(key.grid_size)) {
8141 for (const int x : IndexRange(key.grid_size)) {
8142 const int offset = CCG_grid_xy_to_index(key.grid_size, x, y);
8143 const int node_vert_index = node_verts_start + offset;
8144
8145 SubdivCCGCoord coord{};
8146 coord.grid_index = grid;
8147 coord.x = x;
8148 coord.y = y;
8149
8150 SubdivCCGNeighbors neighbors;
8151 BKE_subdiv_ccg_neighbor_coords_get(subdiv_ccg, coord, false, neighbors);
8152
8154 faces, corner_verts, boundary_verts, boundary_edges, subdiv_ccg, coord))
8155 {
8156 if (neighbors.coords.size() == 2) {
8157 /* Do not include neighbors of corner vertices. */
8158 neighbors.coords.clear();
8159 }
8160 else {
8161 /* Only include other boundary vertices as neighbors of boundary vertices. */
8162 neighbors.coords.remove_if([&](const SubdivCCGCoord coord) {
8164 faces, corner_verts, boundary_verts, boundary_edges, subdiv_ccg, coord);
8165 });
8166 }
8167 }
8168 result[node_vert_index] = neighbors.coords;
8169 }
8170 }
8171 }
8172}
8173
8176{
8178 BLI_assert(verts.size() == result.size());
8179 BMeshNeighborVerts neighbor_data;
8180
8181 int i = 0;
8182 for (BMVert *vert : verts) {
8183 vert_neighbors_get_interior_bmesh(*vert, neighbor_data);
8184 result[i] = neighbor_data;
8185 i++;
8186 }
8187}
8188
8190 const Span<int> verts,
8191 const float4 &plane,
8192 const MutableSpan<float3> translations)
8193{
8195 for (const int i : verts.index_range()) {
8196 const float3 &position = vert_positions[verts[i]];
8199 translations[i] = closest - position;
8200 }
8201}
8202
8204 const float4 &plane,
8205 const MutableSpan<float3> translations)
8206{
8208 for (const int i : positions.index_range()) {
8209 const float3 &position = positions[i];
8212 translations[i] = closest - position;
8213 }
8214}
8215
8217 const float3 &pivot,
8218 const ePaintSymmetryFlags symm,
8219 const MutableSpan<float> factors)
8220{
8222 BLI_assert(positions.size() == factors.size());
8223
8224 for (const int i : positions.index_range()) {
8225 if (!check_vertex_pivot_symmetry(positions[i], pivot, symm)) {
8226 factors[i] = 0.0f;
8227 }
8228 }
8229}
8230
8232 const StrokeCache &cache,
8233 const Span<float3> translations,
8234 const MutableSpan<float> factors)
8235{
8237 if (!(brush.flag & BRUSH_PLANE_TRIM)) {
8238 return;
8239 }
8240 const float threshold = cache.radius_squared * cache.plane_trim_squared;
8241 for (const int i : translations.index_range()) {
8242 if (math::length_squared(translations[i]) > threshold) {
8243 factors[i] = 0.0f;
8244 }
8245 }
8246}
8247
8249 const Span<int> verts,
8250 const float4 &plane,
8251 const MutableSpan<float> factors)
8252{
8254 for (const int i : verts.index_range()) {
8255 if (plane_point_side_v3(plane, vert_positions[verts[i]]) <= 0.0f) {
8256 factors[i] = 0.0f;
8257 }
8258 }
8259}
8260
8262 const float4 &plane,
8263 const MutableSpan<float> factors)
8264{
8266 for (const int i : positions.index_range()) {
8267 if (plane_point_side_v3(plane, positions[i]) <= 0.0f) {
8268 factors[i] = 0.0f;
8269 }
8270 }
8271}
8272
8274 const Span<int> verts,
8275 const float4 &plane,
8276 const MutableSpan<float> factors)
8277{
8279 for (const int i : verts.index_range()) {
8280 if (plane_point_side_v3(plane, vert_positions[verts[i]]) > 0.0f) {
8281 factors[i] = 0.0f;
8282 }
8283 }
8284}
8285
8287 const float4 &plane,
8288 const MutableSpan<float> factors)
8289{
8291 for (const int i : positions.index_range()) {
8292 if (plane_point_side_v3(plane, positions[i]) > 0.0f) {
8293 factors[i] = 0.0f;
8294 }
8295 }
8296}
8297
8299{
8300 View3D *v3d = CTX_wm_view3d(&C);
8301 if (!v3d) {
8302 return;
8303 }
8304
8305 if (v3d->flag2 & V3D_HIDE_OVERLAYS) {
8306 BKE_report(op.reports, RPT_WARNING, RPT_("Viewport overlays are disabled"));
8307 }
8308 else {
8312 }
8313
8314 if (v3d->overlay.sculpt_mode_mask_opacity == 0.0f) {
8315 BKE_report(op.reports, RPT_WARNING, RPT_("Mask overlay opacity is currently set to 0"));
8316 }
8317 }
8318}
8319
8321{
8322 View3D *v3d = CTX_wm_view3d(&C);
8323 if (!v3d) {
8324 return;
8325 }
8326
8327 if (v3d->flag2 & V3D_HIDE_OVERLAYS) {
8328 BKE_report(op.reports, RPT_WARNING, RPT_("Viewport overlays are disabled"));
8329 }
8330 else {
8334 }
8335
8336 if (v3d->overlay.sculpt_mode_face_sets_opacity == 0.0f) {
8337 BKE_report(op.reports, RPT_WARNING, RPT_("Face Sets overlay opacity is currently set to 0"));
8338 }
8339 }
8340}
8341
8342} // namespace ed::sculpt_paint
8343
8344} // namespace blender
CustomData interface, see also DNA_customdata_types.h.
General operations, lookup, etc. for blender objects.
#define PAINT_SYMM_AREA_DEFAULT
Definition BKE_paint.hh:100
A BVH for high poly meshes.
#define final(a, b, c)
Definition BLI_hash_c.hh:21
#define M_PI_2
#define RPT_(msgid)
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define ID_REAL_USERS(id)
Definition DNA_ID.h:679
Object is a sort of wrapper for general info.
#define RV3D_CLIPPING_ENABLED(v3d, rv3d)
#define OPERATOR_RETVAL_CHECK(ret)
Read Blender memory allocation and freeing.
#define PRF_scope(category)
#define PRF_scope_set_dynamic_name(fmt,...)
#define C
Definition RandGen.cpp:29
#define ND_DRAW
Definition WM_types.hh:502
#define ND_SPACE_VIEW3D
Definition WM_types.hh:571
#define NC_OBJECT
Definition WM_types.hh:392
#define NC_SPACE
Definition WM_types.hh:405
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define UNPACK3(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define BM_ELEM_CD_SET_FLOAT(ele, offset, f)
#define BM_ELEM_CD_GET_FLOAT(ele, offset)
#define BM_ELEM_CD_GET_INT(ele, offset)
#define BM_elem_index_get(ele)
#define BM_elem_flag_test(ele, hflag)
#define BM_elem_flag_test_bool(ele, hflag)
#define BM_ITER_ELEM(ele, iter, data, itype)
SIMD_FORCE_INLINE btScalar angle(const btVector3 &v) const
Return the angle between this and another vector.
Definition btVector3.h:356
bool closest(btVector3 &v)
int64_t size() const
Definition BLI_array.hh:267
Span< T > as_span() const
Definition BLI_array.hh:254
IndexRange index_range() const
Definition BLI_array.hh:371
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
bool is_empty() const
Definition BLI_array.hh:275
int calc_reduced_ids(MutableSpan< int > result) const
const void * data() const
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
static IndexMask from_bools_inverse(Span< bool > bools, LinearAllocator<> &memory)
constexpr IndexRange()=default
constexpr IndexRange drop_front(int64_t n) const
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr T * data() const
Definition BLI_span.hh:545
constexpr void fill(const T &value) const
Definition BLI_span.hh:523
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:745
int64_t size() const
Definition BLI_set.hh:606
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
bool is_empty() const
Definition BLI_set.hh:614
Span< NewT > constexpr cast() const
Definition BLI_span.hh:422
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T * end() const
Definition BLI_span.hh:228
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const T * begin() const
Definition BLI_span.hh:224
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr bool contains(const T &value) const
Definition BLI_span.hh:281
bool add(const Key &key)
void add_multiple(Span< Key > keys)
bool contains(const Key &key) const
Span< Key > as_span() const
int64_t size() const
void remove_and_reorder(const int64_t index)
int64_t remove_if(Predicate &&predicate)
void append(const T &value)
const T & last(const int64_t n=0) const
void resize(const int64_t new_size)
void extend(Span< T > array)
void append_non_duplicates(const T &value)
Span< T > as_span() const
void resize(const int64_t new_size_in_bits, const bool value=false)
GAttributeReader lookup(const StringRef name) const
GAttributeReader get() const
bool add(const StringRef name, const AttrDomain domain, const AttrType data_type, const AttributeInit &initializer)
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
constexpr bool is_empty() const
void deform(MutableSpan< float3 > translations, Span< int > verts) const
Definition sculpt.cc:7793
PositionDeformData(const Depsgraph &depsgraph, Object &object_orig)
Definition sculpt.cc:7775
void foreach_index_optimized(Fn &&fn, Mode mode=exec_mode::serial) const
IndexMask slice(IndexRange range) const
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
CCL_NAMESPACE_BEGIN ccl_device_inline float frac(const float x, ccl_private int *ix)
#define powf(x, y)
#define FLT_EPSILON
#define position
#define attribute(slot)
#define vertex
float dot(VecOp< float, D >, VecOp< float, D >) RET
float distance(float, float) RET
float2x2 invert(float2x2 mat)
float3x3 scale(float3x3 mat, float2 scale)
ccl_device_inline void copy_v3_v3(ccl_private float *r, const float3 val)
#define T
#define SCULPT_RAKE_BRUSH_FACTOR
#define FAKE_NEIGHBOR_NONE
void count_indices(Span< int > indices, MutableSpan< int > counts)
bool supports_auto_smooth_pressure(const Brush &brush)
Definition brush.cc:2065
bool supports_rake_factor(const Brush &brush)
Definition brush.cc:1987
bool supports_accumulate(const Brush &brush)
Definition brush.cc:1916
bool supports_gravity(const Brush &brush)
Definition brush.cc:2091
bool supports_hardness_pressure(const Brush &brush)
Definition brush.cc:2069
float normal_weight_get(const Brush &brush, bool invert)
Definition brush.cc:1841
void common_pressure_curves_init(Brush &brush)
Definition brush.cc:1549
bool supports_dyntopo(const Brush &brush)
Definition brush.cc:1893
bool supports_topology_rake(const Brush &brush)
Definition brush.cc:1932
bool supports_normal_weight(const Brush &brush)
Definition brush.cc:1980
IndexRange grid_range(const int grid_area, const int grid)
int2 face_find_adjacent_verts(const IndexRange face, const Span< int > corner_verts, const int vert)
Definition BKE_mesh.hh:338
pbvh::Tree * pbvh_get(Object &object)
void stroke_track_location(Paint &paint, float3 location)
void raycast(Tree &pbvh, FunctionRef< void(Node &node, float *tmin)> hit_fn, const float3 &ray_start, const float3 &ray_normal, bool original)
IndexMask search_nodes(const Tree &pbvh, IndexMaskMemory &memory, FunctionRef< bool(const Node &)> filter_fn)
Definition pbvh.cc:2556
void update_normals(const Depsgraph &depsgraph, Object &object_orig, Tree &pbvh)
Definition pbvh.cc:1179
IndexMask all_leaf_nodes(const Tree &pbvh, IndexMaskMemory &memory)
Definition pbvh.cc:2522
void clip_ray_ortho(Tree &pbvh, bool original, float ray_start[3], float ray_end[3], float ray_normal[3])
Definition pbvh.cc:2084
bool node_raycast_mesh(const MeshNode &node, Span< float3 > node_positions, Span< float3 > vert_positions, OffsetIndices< int > faces, Span< int > corner_verts, Span< int3 > corner_tris, Span< bool > hide_poly, const float3 &ray_start, const float3 &ray_normal, IsectRayPrecalc *isect_precalc, float *depth, int &r_active_vertex, int &r_active_face_index, float3 &r_face_normal)
Definition pbvh.cc:1878
void node_update_mask_bmesh(int mask_offset, BMeshNode &node)
Definition pbvh.cc:1404
void node_update_mask_mesh(Span< float > mask, MeshNode &node)
Definition pbvh.cc:1345
bool node_raycast_bmesh(BMeshNode &node, const float3 &ray_start, const float3 &ray_normal, const IsectRayPrecalc *isect_precalc, float *depth, bool use_original, BMVert **r_active_vertex, float3 &r_face_normal)
void node_update_mask_grids(const CCGKey &key, Span< float > masks, GridsNode &node)
Definition pbvh.cc:1373
bool node_raycast_grids(const SubdivCCG &subdiv_ccg, GridsNode &node, Span< float3 > node_positions, const float3 &ray_start, const float3 &ray_normal, const IsectRayPrecalc *isect_precalc, float *depth, SubdivCCGCoord &r_active_vertex, int &r_active_grid_index, float3 &r_face_normal)
Definition pbvh.cc:1994
Bounds< float3 > bounds_get(const Tree &pbvh)
Definition pbvh.cc:1590
Span< float3 > vert_normals_eval(const Depsgraph &depsgraph, const Object &object_orig)
Definition pbvh.cc:952
MutableSpan< float3 > vert_positions_eval_for_write(const Depsgraph &depsgraph, Object &object_orig)
Definition pbvh.cc:946
bool bmesh_update_topology(BMesh &bm, Tree &pbvh, BMLog &bm_log, PBVHTopologyUpdateMode mode, float min_edge_len, float max_edge_len, const float3 &center, const std::optional< float3 > &view_normal, float radius, bool use_frontface, bool use_projected)
bool find_nearest_to_ray_node(Tree &pbvh, Node &node, Span< float3 > node_positions, bool use_origco, Span< float3 > vert_positions, const OffsetIndices< int > faces, Span< int > corner_verts, Span< int3 > corner_tris, Span< bool > hide_poly, const SubdivCCG *subdiv_ccg, const float ray_start[3], const float ray_normal[3], float *depth, float *dist_sq)
Definition pbvh.cc:2328
void store_bounds_orig(Tree &pbvh)
Definition pbvh.cc:1332
Span< int > node_face_indices_calc_grids(const SubdivCCG &subdiv_ccg, const GridsNode &node, Vector< int > &faces)
Definition pbvh.cc:1666
Span< float3 > vert_positions_eval(const Depsgraph &depsgraph, const Object &object_orig)
Definition pbvh.cc:933
void find_nearest_to_ray(Tree &pbvh, const FunctionRef< void(Node &node, float *tmin)> fn, const float3 &ray_start, const float3 &ray_normal, bool original)
Cache & stroke_cache_ensure(const Depsgraph &depsgraph, const Paint &paint, const Brush *brush, Object &ob)
bool is_enabled(const Paint &paint, const Object &object, const Brush *br)
void calc_vert_factors(const Depsgraph &depsgraph, const Object &object, const Cache &automasking, const bke::pbvh::MeshNode &node, Span< int > verts, MutableSpan< float > factors)
void calc_grids_factors(const Depsgraph &depsgraph, const Object &object, const Cache &automasking, const bke::pbvh::GridsNode &node, Span< int > grids, MutableSpan< float > factors)
SculptBoundaryInfoCache create_boundary_info(const Mesh &mesh)
Definition sculpt.cc:599
void do_boundary_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void ensure_boundary_info(Object &object)
Definition sculpt.cc:588
bool vert_is_boundary(const GroupedSpan< int > vert_to_face_map, const Span< bool > hide_poly, const BitSpan boundary_verts, const int vert)
Definition sculpt.cc:620
CursorSampleResult calc_node_mask(const Depsgraph &depsgraph, Object &ob, const Brush &brush, IndexMaskMemory &memory)
CursorSampleResult calc_node_mask(const Depsgraph &depsgraph, Object &ob, const Brush &brush, IndexMaskMemory &memory)
Definition plane.cc:483
void do_snake_hook_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_smooth_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask, float brush_strength)
Definition smooth.cc:243
void do_mask_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_draw_face_sets_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_blob_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition crease.cc:288
void do_draw_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition draw.cc:187
void do_displacement_eraser_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void do_elastic_deform_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_draw_vector_displacement_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_crease_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition crease.cc:279
void do_topology_relax_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition relax.cc:840
void do_thumb_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition thumb.cc:138
void do_clay_thumb_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void do_rotate_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_topology_slide_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_displacement_smear_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void do_clay_strips_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask, const float3 &plane_normal, const float3 &plane_center)
void do_surface_smooth_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_plane_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask, const float3 &plane_normal, const float3 &plane_center)
Definition plane.cc:366
void do_enhance_details_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_bmesh_topology_rake_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask, const float input_strength)
void do_layer_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_nudge_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition draw.cc:204
void do_inflate_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition inflate.cc:138
void do_relax_face_sets_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition relax.cc:805
void do_draw_sharp_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_multiplane_scrape_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_pinch_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
Definition pinch.cc:172
void do_smooth_mask_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask, float brush_strength)
void do_gravity_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition draw.cc:219
float clay_thumb_get_stabilized_pressure(const StrokeCache &cache)
void do_clay_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition clay.cc:159
void do_scene_project_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, const IndexMask &node_mask)
void do_grab_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition grab.cc:172
bool is_cloth_deform_brush(const Brush &brush)
void brush_store_simulation_state(const Depsgraph &depsgraph, const Object &object, SimulationData &cloth_sim)
void ensure_nodes_constraints(const Sculpt &sd, Object &object, const IndexMask &node_mask, SimulationData &cloth_sim, const float3 &initial_location, const float radius)
void sim_activate_nodes(Object &object, SimulationData &cloth_sim, const IndexMask &node_mask)
IndexMask brush_affected_nodes_gather(const Object &object, const Brush &brush, IndexMaskMemory &memory)
void do_simulation_step(const Depsgraph &depsgraph, const Sculpt &sd, Object &object, SimulationData &cloth_sim, const IndexMask &node_mask)
std::unique_ptr< SimulationData > brush_simulation_create(const Depsgraph &depsgraph, Object &ob, const float cloth_mass, const float cloth_damping, const float cloth_softbody_strength, const bool use_collisions, const bool needs_deform_coords)
void do_cloth_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
bke::GSpanAttributeWriter active_color_attribute_for_write(Mesh &mesh)
void do_smear_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void color_vert_set(OffsetIndices< int > faces, Span< int > corner_verts, GroupedSpan< int > vert_to_face_map, bke::AttrDomain color_domain, int vert, const float4 &color, GMutableSpan color_attribute)
void do_paint_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void do_blur_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
float relative_to_detail_size(const float relative_detail, const float brush_radius, const float pixel_radius, const float pixel_size)
float constant_to_detail_size(const float constant_detail, const Object &ob)
float brush_to_detail_size(const float brush_percent, const float brush_radius)
bool stroke_is_dyntopo(const Object &object, const Brush &brush)
Definition sculpt.cc:986
bool vert_has_unique_face_set(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, int vert)
Definition sculpt.cc:324
bool coord_has_face_set(const OffsetIndices< int > faces, const Span< int > corner_verts, const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const SubdivCCG &subdiv_ccg, const SubdivCCGCoord coord, const int face_set)
Definition sculpt.cc:410
bool vert_has_any_face_set(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, int vert, const Set< int > &allowed_face_sets)
Definition sculpt.cc:308
bool vert_has_face_set(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const int vert, const int face_set)
Definition sculpt.cc:268
int vert_face_set_max_get(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const int vert)
Definition sculpt.cc:232
bke::SpanAttributeWriter< int > ensure_face_sets_mesh(Mesh &mesh)
bool coord_has_any_face_set(const OffsetIndices< int > faces, const Span< int > corner_verts, const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const SubdivCCG &subdiv_ccg, const SubdivCCGCoord coord, const Set< int > &allowed_face_sets)
Definition sculpt.cc:432
Set< int > vert_face_sets_get(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const int vert)
Definition sculpt.cc:254
int vert_face_set_get(const SubdivCCG &subdiv_ccg, const Span< int > face_sets, const int grid)
Definition sculpt.cc:243
int active_face_set_get(const Object &object)
Definition sculpt.cc:202
static bool sculpt_check_unique_face_set_for_edge_in_base_mesh(const GroupedSpan< int > vert_to_face_map, const Span< int > face_sets, const Span< int > corner_verts, const OffsetIndices< int > faces, int v1, int v2)
Definition sculpt.cc:350
bool vert_all_faces_visible_get(const Span< bool > hide_poly, const GroupedSpan< int > vert_to_face_map, const int vert)
void ensure_cache(Object &object)
Definition sculpt.cc:6448
static SculptTopologyIslandCache calc_topology_islands_grids(const Object &object)
Definition sculpt.cc:6378
static SculptTopologyIslandCache vert_disjoint_set_to_islands(const AtomicDisjointSet &vert_sets, const int verts_num)
Definition sculpt.cc:6330
static SculptTopologyIslandCache calc_topology_islands_mesh(const Mesh &mesh)
Definition sculpt.cc:6351
static SculptTopologyIslandCache calculate_cache(const Object &object)
Definition sculpt.cc:6433
static SculptTopologyIslandCache calc_topology_islands_bmesh(const Object &object)
Definition sculpt.cc:6403
int vert_id_get(const SculptSession &ss, const int vert)
Definition sculpt.cc:6310
void invalidate(SculptSession &ss)
Definition sculpt.cc:6325
void do_pose_brush(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
void push_nodes(const Depsgraph &depsgraph, Object &object, const IndexMask &node_mask, const Type type)
static void restore_from_undo_step(const Depsgraph &depsgraph, const Sculpt &sd, Object &object)
Definition sculpt.cc:1309
static void restore_color_from_undo_step(Object &object)
Definition sculpt.cc:1089
static void restore_face_set_from_undo_step(Object &object)
Definition sculpt.cc:1125
void push_begin_ex(const Scene &, Object &ob, const char *name)
void restore_position_from_undo_step(const Depsgraph &depsgraph, Object &object)
Definition sculpt.cc:1181
void geometry_begin(const Scene &scene, Object &ob, const wmOperator *op)
static void restore_mask_from_undo_step(Object &object)
Definition sculpt.cc:1008
void push_begin(const Scene &scene, Object &ob, const wmOperator *op)
static void restore_from_undo_step_if_necessary(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob)
Definition sculpt.cc:4998
static void calc_area_normal_and_center_node_mesh(const Object &object, const Span< float3 > vert_positions, const Span< float3 > vert_normals, const Span< bool > hide_vert, const Brush &brush, const AverageDataFlags flag, const bke::pbvh::MeshNode &node, AreaNormalCenterData &anctd)
Definition sculpt.cc:1459
bool shape_key_check(const Object &ob, ReportList *reports)
Definition sculpt.cc:134
void fill_factor_from_hide_and_mask(Span< bool > hide_vert, Span< float > mask, Span< int > verts, MutableSpan< float > r_factors)
Definition sculpt.cc:7128
static void calc_local_from_screen(const ViewContext &vc, const float center[3], const float screen_dir[2], float r_local_dir[3])
Definition sculpt.cc:2794
std::optional< Span< float > > orig_mask_data_lookup_grids(const Object &object, const bke::pbvh::GridsNode &node)
static bool brush_needs_rake_rotation(const Brush &brush)
Definition sculpt.cc:965
MutableSpan< float3 > gather_grids_positions(const SubdivCCG &subdiv_ccg, const Span< int > grids, Vector< float3 > &positions)
void face_set_overlay_check(bContext &C, wmOperator &op)
Definition sculpt.cc:8320
static void sculpt_raycast_cb(bke::pbvh::Node &node, RaycastData &rd, float *distance)
Definition sculpt.cc:4320
static float brush_dynamic_size_get(const Brush &brush, const StrokeCache &cache, float initial_size)
Definition sculpt.cc:4059
static void fake_neighbor_search_mesh(const SculptSession &ss, const Span< float3 > vert_positions, const Span< bool > hide_vert, const float3 &location, const float max_distance_sq, const int island_id, const bke::pbvh::MeshNode &node, NearestVertData &nvtd)
Definition sculpt.cc:5999
static bool attribute_matches(const bke::AttributeAccessor a, const bke::AttributeAccessor b, const StringRef name)
Definition sculpt.cc:5222
bool node_in_sphere(const bke::pbvh::Node &node, const float3 &location, const float radius_sq, const bool original)
Definition sculpt.cc:2511
void scatter_data_bmesh(Span< T > node_data, const Set< BMVert *, 0 > &verts, MutableSpan< T > dst)
Definition sculpt.cc:6577
bool node_in_cylinder(const DistRayAABB_Precalc &ray_dist_precalc, const bke::pbvh::Node &node, const float radius_sq, const bool original)
Definition sculpt.cc:2521
float4x4 cube_tip_init(const Object &ob, const Brush &brush)
Definition sculpt.cc:6459
static void brush_stroke_init(bContext *C, const wmOperator *op)
Definition sculpt.cc:4966
void calc_factors_common_from_orig_data_grids(const Depsgraph &depsgraph, const Brush &brush, const Object &object, Span< float3 > positions, Span< float3 > normals, const bke::pbvh::GridsNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:7008
void gather_bmesh_positions(const Set< BMVert *, 0 > &verts, MutableSpan< float3 > positions)
Definition sculpt.cc:6497
static void smooth_brush_toggle_off(Paint *paint, StrokeCache *cache)
Definition sculpt.cc:3955
bool brush_cursor_poll(bContext *C)
Definition sculpt.cc:3855
static GroupedSpan< int > calc_vert_neighbors_interior_impl(const OffsetIndices< int > faces, const Span< int > corner_verts, const GroupedSpan< int > vert_to_face, const BitSpan boundary_verts, const Set< OrderedEdge > &boundary_edges, const Span< bool > hide_poly, const Span< int > verts, const Span< float > factors, Vector< int > &r_offset_data, Vector< int > &r_data)
Definition sculpt.cc:8025
bool check_vertex_pivot_symmetry(const float vco[3], const float pco[3], const char symm)
Definition sculpt.cc:672
static void tag_mesh_positions_changed(Object &object, const bool use_pbvh_draw)
Definition sculpt.cc:5045
void calc_brush_strength_factors(const StrokeCache &cache, const Brush &brush, Span< float > distances, MutableSpan< float > factors)
Definition sculpt.cc:7501
std::optional< Span< int > > orig_face_set_data_lookup_mesh(const Object &object, const bke::pbvh::MeshNode &node)
void gather_data_grids(const SubdivCCG &subdiv_ccg, Span< T > src, Span< int > grids, MutableSpan< T > node_data)
Definition sculpt.cc:6528
static void redo_empty_ui(bContext *, wmOperator *)
Definition sculpt.cc:5924
void vert_random_access_ensure(Object &object)
Definition sculpt.cc:154
static void flip_qt_qt(float out[4], const float in[4], const ePaintSymmetryFlags symm)
Definition sculpt.cc:2994
std::optional< int > nearest_vert_calc_mesh(const bke::pbvh::Tree &pbvh, const Span< float3 > vert_positions, const Span< bool > hide_vert, const float3 &location, const float max_distance, const bool use_original)
Definition sculpt.cc:730
void filter_below_plane_factors(Span< float3 > vert_positions, Span< int > verts, const float4 &plane, MutableSpan< float > factors)
Definition sculpt.cc:8248
void apply_hardness_to_distances(float radius, float hardness, MutableSpan< float > distances)
Definition sculpt.cc:7473
void calc_factors_common_grids(const Depsgraph &depsgraph, const Brush &brush, const Object &object, Span< float3 > positions, const bke::pbvh::GridsNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:6804
GroupedSpan< int > calc_vert_neighbors(OffsetIndices< int > faces, Span< int > corner_verts, GroupedSpan< int > vert_to_face, Span< bool > hide_poly, Span< int > verts, Vector< int > &r_offset_data, Vector< int > &r_data)
Definition sculpt.cc:7949
void gather_bmesh_normals(const Set< BMVert *, 0 > &verts, MutableSpan< float3 > normals)
Definition sculpt.cc:6517
static void pose_fake_neighbors_free(SculptSession &ss)
Definition sculpt.cc:5975
bool node_fully_masked_or_hidden(const bke::pbvh::Node &node)
Definition sculpt.cc:2500
float3 tilt_effective_normal_get(const SculptSession &ss, const Brush &brush)
Definition sculpt.cc:2904
void filter_translations(MutableSpan< float3 > translations, Span< float > factors)
Definition sculpt.cc:7827
static void stroke_cache_init(ViewContext &vc, const Sculpt &sd, const Brush &brush, Object &ob, const float mval[2])
Definition sculpt.cc:5446
Vector< BMVert *, 64 > BMeshNeighborVerts
void calc_factors_common_from_orig_data_mesh(const Depsgraph &depsgraph, const Brush &brush, const Object &object, const MeshAttributeData &attribute_data, Span< float3 > positions, Span< float3 > normals, const bke::pbvh::MeshNode &node, MutableSpan< float > r_factors, MutableSpan< float > r_distances)
Definition sculpt.cc:6976
ENUM_OPERATORS(AverageDataFlags)
void filter_distances_with_radius(float radius, Span< float > distances, MutableSpan< float > factors)
Definition sculpt.cc:7422
static const char * sculpt_brush_type_name(const Brush &brush)
Definition sculpt.cc:3395
int vertex_count_get(const Object &object)
Definition sculpt.cc:163
std::optional< OrigPositionData > orig_position_data_lookup_grids(const Object &object, const bke::pbvh::GridsNode &node)
ePaintSymmetryAreas get_vertex_symm_area(const float co[3])
Definition sculpt.cc:2979
void stroke_modifiers_check(Depsgraph &depsgraph, Object &ob, const Brush *brush)
Definition sculpt.cc:4309
static bool over_mesh(bContext *C, wmOperator *, const float mval[2])
Definition sculpt.cc:5405
static const ImplicitSharingInfo * get_vertex_group_sharing_info(const Mesh &mesh)
Definition sculpt.cc:5267
static void cache_paint_brush_variants_update(StrokeCache &cache, const Brush &brush)
Definition sculpt.cc:4272
bool node_in_box_positive_z(const float4x4 &mat, const Bounds< float3 > &bounds)
Definition sculpt.cc:2606
void filter_region_clip_factors(const SculptSession &ss, Span< float3 > vert_positions, Span< int > verts, MutableSpan< float > factors)
Definition sculpt.cc:7285
void gather_data_bmesh(Span< T > src, const Set< BMVert *, 0 > &verts, MutableSpan< T > node_data)
Definition sculpt.cc:6545
static void fake_neighbor_init(Object &object, const float max_dist)
Definition sculpt.cc:5967
void reset_translations_to_original(MutableSpan< float3 > translations, Span< float3 > positions, Span< float3 > orig_positions)
Definition sculpt.cc:7572
bool stroke_is_first_brush_step_of_symmetry_pass(const StrokeCache &cache)
Definition sculpt.cc:667
float3 symmetry_flip(const float3 &src, const ePaintSymmetryFlags symm)
static int sculpt_brush_needs_normal(const SculptSession &ss, const Brush &brush)
Definition sculpt.cc:943
void orig_position_data_gather_bmesh(const BMLog &bm_log, const Set< BMVert *, 0 > &verts, MutableSpan< float3 > positions, MutableSpan< float3 > normals)
bool stroke_is_first_brush_step(const StrokeCache &cache)
Definition sculpt.cc:661
static float area_normal_calc_weight(const float distance, const float radius_inv)
Definition sculpt.cc:1404
static void flip_qt(float quat[4], const ePaintSymmetryFlags symm)
Definition sculpt.cc:3017
void scale_translations(MutableSpan< float3 > translations, Span< float > factors)
Definition sculpt.cc:7837
GroupedSpan< int > calc_vert_neighbors_interior(OffsetIndices< int > faces, Span< int > corner_verts, GroupedSpan< int > vert_to_face, BitSpan boundary_verts, const Set< OrderedEdge > &boundary_edges, Span< bool > hide_poly, Span< int > verts, Vector< int > &r_offset_data, Vector< int > &r_data)
Definition sculpt.cc:8099
void calc_factors_common_mesh_indexed(const Depsgraph &depsgraph, const Brush &brush, const Object &object, const MeshAttributeData &attribute_data, Span< float3 > vert_positions, Span< float3 > vert_normals, const bke::pbvh::MeshNode &node, MutableSpan< float > factors, MutableSpan< float > distances)
Definition sculpt.cc:6739
static void brush_init_tex(const Sculpt &sd, SculptSession &ss)
Definition sculpt.cc:4926
static bool brush_type_needs_original(const char sculpt_brush_type)
Definition sculpt.cc:920
bool paint_supports_dynamic_size(const Brush &br, PaintMode mode)
ePaintSymmetryFlags mesh_symmetry_xyz_get(const Object &object)
Definition sculpt.cc:192
static void dynamic_topology_update(const Depsgraph &depsgraph, const Scene &scene, const Brush &brush, Object &ob, PaintModeData *)
Definition sculpt.cc:3157
bool sculpt_mode_poll(bContext *C)
Definition sculpt.cc:3800
static void sculpt_init_mirror_clipping(const Object &ob, const SculptSession &ss)
Definition sculpt.cc:3880
void calc_vertex_displacement(const SculptSession &ss, const Brush &brush, float translation[3])
Definition sculpt.cc:2476
void fake_neighbors_free(Object &ob)
Definition sculpt.cc:6249
float3 calc_motion_normal_from_angle(const ViewContext &vc, const float3 &tip_location, const float angle)
Definition sculpt.cc:2812
static void mask_brush_toggle_on(Main *bmain, Paint *paint, StrokeToggleSettings &toggle_settings)
Definition sculpt.cc:3981
static void brush_exit_tex(Sculpt &sd)
Definition sculpt.cc:5714
void calc_cube_tip_factors_common_bmesh(const Depsgraph &depsgraph, const Brush &brush, const Object &object, const float4x4 &mat, Span< float3 > positions, bke::pbvh::BMeshNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:6924
bool color_supported_check(const Scene &scene, Object &object, ReportList *reports)
Definition sculpt.cc:5432
static bool need_delta_from_anchored_origin(const Brush &brush)
Definition sculpt.cc:4081
static void calc_area_normal_and_center_node_grids(const Object &object, const Brush &brush, const AverageDataFlags flag, const bke::pbvh::GridsNode &node, SampleLocalData &tls, AreaNormalCenterData &anctd)
Definition sculpt.cc:1548
static wmOperatorStatus brush_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
Definition sculpt.cc:5911
static void store_sculpt_entire_mesh(const wmOperator &op, const Scene &scene, Object &object, Mesh *new_mesh)
Definition sculpt.cc:5255
float raycast_init(ViewContext *vc, const float2 &mval, float3 &r_ray_start, float3 &r_ray_end, float3 &r_ray_normal, bool original)
Definition sculpt.cc:4471
static bool brush_type_needs_all_pbvh_nodes(const Brush &brush)
Definition sculpt.cc:3237
static float brush_flip(const Brush &brush, const StrokeCache &cache)
Definition sculpt.cc:2249
void filter_verts_outside_symmetry_area(Span< float3 > positions, const float3 &pivot, ePaintSymmetryFlags symm, MutableSpan< float > factors)
Definition sculpt.cc:8216
static void accumulate_area_center(const float3 &test_location, const float3 &position, const float distance, const float radius_inv, const int flip_index, AreaNormalCenterData &anctd)
Definition sculpt.cc:1424
static void rake_data_update(SculptRakeData *srd, const float co[3])
Definition sculpt.cc:972
void calc_translations_to_plane(Span< float3 > vert_positions, Span< int > verts, const float4 &plane, MutableSpan< float3 > translations)
Definition sculpt.cc:8189
void scale_factors(MutableSpan< float > factors, float strength)
Definition sculpt.cc:7856
static void init_scene_project_brush_targets(const Depsgraph &depsgraph, ViewLayer &view_layer, const View3D &v3d, const Object &active_object, StrokeCache &cache)
Definition sculpt.cc:4029
float3 flip_v3_by_symm_area(const float3 &vector, const ePaintSymmetryFlags symm, const ePaintSymmetryAreas symmarea, const float3 &pivot)
Definition sculpt.cc:3022
static void brush_delta_update(const Depsgraph &depsgraph, Paint &paint, const Object &ob, const Brush &brush)
Definition sculpt.cc:4122
void do_symmetrical_brush_actions_with_tiling_and_feathering(const Depsgraph &depsgraph, const Scene &scene, const Paint &paint, Object &object, const BrushActionFn action_fn, PaintModeData *paint_mode_data)
static float3 calc_sculpt_normal(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const IndexMask &node_mask)
Definition sculpt.cc:2732
bool brush_type_is_paint(const int tool)
void translations_from_new_positions(Span< float3 > new_positions, Span< int > verts, Span< float3 > old_positions, MutableSpan< float3 > translations)
Definition sculpt.cc:7889
static bool need_delta_for_tip_orientation(const Brush &brush)
Definition sculpt.cc:4108
void clip_and_lock_translations(const Sculpt &sd, const SculptSession &ss, Span< float3 > positions, Span< int > verts, MutableSpan< float3 > translations)
Definition sculpt.cc:7664
static void sculpt_brush_stroke_cancel(bContext *C, wmOperator *op)
Definition sculpt.cc:5895
IndexMask gather_nodes(const bke::pbvh::Tree &pbvh, const eBrushFalloffShape falloff_shape, const bool use_original, const float3 &location, const float radius_sq, const std::optional< float3 > &ray_direction, IndexMaskMemory &memory)
Definition sculpt.cc:2696
std::optional< float3 > stroke_get_location_bvh(Depsgraph &depsgraph, ViewContext &vc, const Sculpt &sd, const Brush *brush, const float mval[2], const bool force_original)
Definition sculpt.cc:4855
static void push_undo_nodes(const Depsgraph &depsgraph, Object &ob, const Brush &brush, const IndexMask &node_mask)
Definition sculpt.cc:3362
void calc_factors_common_mesh(const Depsgraph &depsgraph, const Brush &brush, const Object &object, const MeshAttributeData &attribute_data, Span< float3 > positions, Span< float3 > vert_normals, const bke::pbvh::MeshNode &node, MutableSpan< float > factors, MutableSpan< float > distances)
Definition sculpt.cc:6772
std::optional< Span< float4 > > orig_color_data_lookup_mesh(const Object &object, const bke::pbvh::MeshNode &node)
void scatter_data_mesh(Span< T > src, Span< int > indices, MutableSpan< T > dst)
static bool contains_nan(const Span< float > values)
Definition sculpt.cc:7586
bool sculpt_mode_poll_view3d(bContext *C)
Definition sculpt.cc:3806
void calc_brush_distances(const SculptSession &ss, Span< float3 > vert_positions, Span< int > vert, eBrushFalloffShape falloff_shape, MutableSpan< float > r_distances)
Definition sculpt.cc:7370
void SCULPT_OT_brush_stroke(wmOperatorType *ot)
Definition sculpt.cc:5926
void project_translations(MutableSpan< float3 > translations, const float3 &plane)
Definition sculpt.cc:7638
std::optional< ActiveElementInfo > active_element_info_get(ViewContext &vc, const float2 &mval)
Definition sculpt.cc:4512
void calc_brush_plane(const Depsgraph &depsgraph, const Brush &brush, Object &ob, const IndexMask &node_mask, float3 &r_area_no, float3 &r_area_co)
Definition sculpt.cc:3062
Span< BMVert * > vert_neighbors_get_interior_bmesh(BMVert &vert, BMeshNeighborVerts &r_neighbors)
Definition sculpt.cc:505
static IndexMask pbvh_gather_generic_cube(Object &ob, const Brush &brush, const float4x4 &brush_local_mat, const bool use_original, IndexMaskMemory &memory)
Definition sculpt.cc:2659
void stroke_cache_common_init(ViewContext &vc, const Paint &paint, const Brush &brush, Object &object, const float2 mval)
std::optional< float3 > calc_area_normal(const Depsgraph &depsgraph, const Brush &brush, const Object &ob, const IndexMask &node_mask)
Definition sculpt.cc:1926
void filter_plane_trim_limit_factors(const Brush &brush, const StrokeCache &cache, Span< float3 > translations, MutableSpan< float > factors)
Definition sculpt.cc:8231
OffsetIndices< int > create_node_vert_offsets(Span< bke::pbvh::MeshNode > nodes, const IndexMask &node_mask, Array< int > &node_data)
Definition sculpt.cc:7912
Span< BMVert * > vert_neighbors_get_bmesh(BMVert &vert, BMeshNeighborVerts &r_neighbors)
Definition sculpt.cc:490
void apply_translations(Span< float3 > translations, Span< int > verts, MutableSpan< float3 > positions)
Definition sculpt.cc:7592
bool node_in_box(const float4x4 &mat, const Bounds< float3 > &bounds, const float3 &brush_center, const float3 &brush_half_lengths, const bool test_z_axis)
Definition sculpt.cc:2536
const float * brush_frontface_normal_from_falloff_shape(const SculptSession &ss, char falloff_shape)
Definition sculpt.cc:1341
bool vertex_is_occluded(const Depsgraph &depsgraph, const Object &object, const float3 &position, bool original)
Definition sculpt.cc:6255
static void stroke_cache_update(ViewContext &vc, const Depsgraph &depsgraph, Paint &paint, Brush &brush, Object &object, const PaintStroke::StrokeStep &stroke_step)
Definition sculpt.cc:5551
void flush_update_step(bContext *C, const UpdateType update_type)
Definition sculpt.cc:5090
void calc_cube_tip_factors_common_grids(const Depsgraph &depsgraph, const Brush &brush, const Object &object, const float4x4 &mat, Span< float3 > positions, const bke::pbvh::GridsNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:6838
void flush_update_done(bContext *C, Object &ob, const UpdateType update_type)
Definition sculpt.cc:5131
static void fake_neighbor_search_bmesh(const SculptSession &ss, const float3 &location, const float max_distance_sq, const int island_id, const bke::pbvh::BMeshNode &node, NearestVertData &nvtd)
Definition sculpt.cc:6055
bool paint_brush_cursor_poll(bContext *C)
static bool is_brush_related_tool(bContext *C)
Definition sculpt.cc:3823
static void sculpt_fix_noise_tear(const Sculpt &sd, Object &ob)
Definition sculpt.cc:3789
static AreaNormalCenterData calc_area_normal_and_center_reduce(const AreaNormalCenterData &a, const AreaNormalCenterData &b)
Definition sculpt.cc:1807
void filter_above_plane_factors(Span< float3 > vert_positions, Span< int > verts, const float4 &plane, MutableSpan< float > factors)
Definition sculpt.cc:8273
void calc_area_center(const Depsgraph &depsgraph, const Brush &brush, const Object &ob, const IndexMask &node_mask, float r_area_co[3])
Definition sculpt.cc:1825
float object_space_radius_get(const ViewContext &vc, const Paint &paint, const Brush &brush, const float3 &location, const float scale_factor)
Definition sculpt.cc:121
BLI_INLINE bool brush_type_is_attribute_only(const int tool)
static constexpr int plane_brush_max_rolling_average_num
float brush_plane_offset_get(const Brush &brush, const SculptSession &ss)
Definition sculpt.cc:3145
bool stroke_is_main_symmetry_pass(const StrokeCache &cache)
Definition sculpt.cc:655
static void update_brush_local_mat(const Sculpt &sd, Object &ob)
Definition sculpt.cc:2909
static wmOperatorStatus sculpt_brush_stroke_exec(bContext *C, wmOperator *op)
Definition sculpt.cc:5881
static void calc_stabilized_plane(const Brush &brush, StrokeCache &cache, const float3 &plane_normal, const float3 &plane_center, float3 &r_stabilized_normal, float3 &r_stabilized_center)
Definition sculpt.cc:2036
float3 grab_delta_get(const Brush &brush, const StrokeCache &cache)
Definition sculpt.cc:718
bool is_vertex_inside_brush_radius_symm(const float vertex[3], const float br_co[3], float radius, char symm)
Definition sculpt.cc:878
void apply_crazyspace_to_translations(Span< float3x3 > deform_imats, Span< int > verts, MutableSpan< float3 > translations)
Definition sculpt.cc:7652
static void do_brush_action(const Depsgraph &depsgraph, const Scene &scene, const Brush &brush, Object &ob, PaintModeData *)
Definition sculpt.cc:3467
static void sculpt_find_nearest_to_ray_cb(bke::pbvh::Node &node, FindNearestToRayData &fntrd, float *tmin)
Definition sculpt.cc:4418
static bool topology_matches(const Mesh &a, const Mesh &b)
Definition sculpt.cc:5234
std::optional< BMVert * > nearest_vert_calc_bmesh(const bke::pbvh::Tree &pbvh, const float3 &location, const float max_distance, const bool use_original)
Definition sculpt.cc:831
bool sculpt_mode_and_brush_poll(bContext *C)
Definition sculpt.cc:3811
Span< int > fake_neighbors_ensure(const Depsgraph &depsgraph, Object &ob, const float max_dist)
Definition sculpt.cc:6230
std::optional< CursorGeometryInfo > cursor_geometry_info_update(bContext *C, const float2 &mval, const bool use_sampled_normal)
Definition sculpt.cc:4584
static void fake_neighbor_search(const Depsgraph &depsgraph, const Object &ob, const float max_distance_sq, MutableSpan< int > fake_neighbors)
Definition sculpt.cc:6083
static float brush_strength(const Sculpt &sd, const StrokeCache &cache)
Definition sculpt.cc:2262
static wmOperatorStatus sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, const wmEvent *event)
Definition sculpt.cc:5785
void calc_front_face(const float3 &view_normal, Span< float3 > normals, MutableSpan< float > factors)
Definition sculpt.cc:7223
void flip_quat_by_symm_area(float quat[4], const ePaintSymmetryFlags symm, const ePaintSymmetryAreas symmarea, const float pivot[3])
Definition sculpt.cc:3043
static void replace_attribute(const bke::AttributeAccessor src_attributes, const StringRef name, const bke::AttrDomain domain, const bke::AttrType data_type, bke::MutableAttributeAccessor dst_attributes)
Definition sculpt.cc:5201
static float3 area_center_calc_weighted(const float3 &test_location, const float distance, const float radius_inv, const float3 &co)
Definition sculpt.cc:1411
static void fake_neighbor_search_grids(const SculptSession &ss, const CCGKey &key, const Span< float3 > positions, const BitGroupVector<> &grid_hidden, const float3 &location, const float max_distance_sq, const int island_id, const bke::pbvh::GridsNode &node, NearestVertData &nvtd)
Definition sculpt.cc:6026
std::optional< Span< float > > orig_mask_data_lookup_mesh(const Object &object, const bke::pbvh::MeshNode &node)
static void calc_area_normal_and_center_node_bmesh(const Object &object, const Brush &brush, const AverageDataFlags flag, const bool has_bm_orco, const bke::pbvh::BMeshNode &node, SampleLocalData &tls, AreaNormalCenterData &anctd)
Definition sculpt.cc:1658
std::optional< SubdivCCGCoord > nearest_vert_calc_grids(const bke::pbvh::Tree &pbvh, const SubdivCCG &subdiv_ccg, const float3 &location, const float max_distance, const bool use_original)
Definition sculpt.cc:777
std::optional< OrigPositionData > orig_position_data_lookup_mesh_all_verts(const Object &object, const bke::pbvh::MeshNode &node)
static IndexMask pbvh_gather_cursor_update(Object &ob, bool use_original, IndexMaskMemory &memory)
Definition sculpt.cc:2611
static bool brush_uses_topology_rake(const SculptSession &ss, const Brush &brush)
Definition sculpt.cc:934
void calc_brush_distances_squared(const SculptSession &ss, Span< float3 > positions, Span< int > verts, eBrushFalloffShape falloff_shape, MutableSpan< float > r_distances)
Definition sculpt.cc:7342
void gather_grids_normals(const SubdivCCG &subdiv_ccg, Span< int > grids, MutableSpan< float3 > normals)
Definition sculpt.cc:6509
void calc_area_normal_and_center(const Depsgraph &depsgraph, const Brush &brush, const Object &ob, const IndexMask &node_mask, float r_area_no[3], float r_area_co[3])
Definition sculpt.cc:2120
void apply_brush_texture(const PaintMode paint_mode, const SculptSession &ss, const Brush &brush, const float brush_point[3], const int thread_id, float *r_value, float4 &r_rgba)
Definition sculpt.cc:2410
void calc_brush_local_mat(const float3 &tip_normal, const float3 &motion_normal_local, const float3 &tip_location, const float radius, float local_mat[4][4], float local_mat_inv[4][4])
Definition sculpt.cc:2830
void translations_from_offset_and_factors(const float3 &offset, Span< float > factors, MutableSpan< float3 > r_translations)
Definition sculpt.cc:7877
static StrokeToggleSettings create_toggle_settings(const wmOperator &op, Main &bmain, Paint &paint)
Definition sculpt.cc:4943
void calc_brush_cube_distances(const Brush &brush, const Span< T > positions, const MutableSpan< float > r_distances)
Definition sculpt.cc:7435
static float area_normal_and_center_get_normal_radius(const SculptSession &ss, const Brush &brush)
Definition sculpt.cc:1375
std::optional< OrigPositionData > orig_position_data_lookup_mesh(const Object &object, const bke::pbvh::MeshNode &node)
void store_mesh_from_eval(const wmOperator &op, const Scene &scene, const Depsgraph &depsgraph, const RegionView3D *rv3d, Object &object, Mesh *new_mesh)
Definition sculpt.cc:5276
void calc_local_positions(Span< float3 > vert_positions, Span< int > verts, const float4x4 &mat, const float3 &plane_center, const float3 &view_normal, eBrushFalloffShape falloff_shape, MutableSpan< float3 > local_positions)
Definition sculpt.cc:6619
void append_neighbors_to_vector(const OffsetIndices< int > faces, const Span< int > corner_verts, const GroupedSpan< int > vert_to_face, const Span< bool > hide_poly, const int vert, Vector< int > &r_data)
Definition sculpt.cc:555
void calc_brush_texture_factors(PaintMode paint_mode, const SculptSession &ss, const Brush &brush, Span< float3 > vert_positions, Span< int > vert, MutableSpan< float > factors)
Definition sculpt.cc:7513
std::optional< Span< int > > orig_face_set_data_lookup_grids(const Object &object, const bke::pbvh::GridsNode &node)
static std::optional< float3 > stroke_get_location_bvh_ex(Depsgraph &depsgraph, ViewContext &vc, const Paint &paint, const Sculpt *sd, const float2 &mval, const bool force_original, const bool check_closest, const bool limit_closest_radius)
Definition sculpt.cc:4735
Span< int > vert_neighbors_get_mesh(const OffsetIndices< int > faces, const Span< int > corner_verts, const GroupedSpan< int > vert_to_face, const Span< bool > hide_poly, const int vert, Vector< int > &r_neighbors)
Definition sculpt.cc:534
void fill_factor_from_hide(Span< bool > hide_vert, Span< int > verts, MutableSpan< float > r_factors)
Definition sculpt.cc:7077
static brushes::CursorSampleResult calc_brush_node_mask(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const Brush &brush, IndexMaskMemory &memory)
Definition sculpt.cc:3271
void mask_overlay_check(bContext &C, wmOperator &op)
Definition sculpt.cc:8298
void scatter_data_grids(const SubdivCCG &subdiv_ccg, Span< T > node_data, Span< int > grids, MutableSpan< T > dst)
Definition sculpt.cc:6560
bool brush_uses_vector_displacement(const Brush &brush)
static void smooth_brush_toggle_on(Main *bmain, Paint *paint, StrokeToggleSettings &toggle_settings)
Definition sculpt.cc:3917
OffsetIndices< int > create_node_vert_offsets_bmesh(Span< bke::pbvh::BMeshNode > nodes, const IndexMask &node_mask, Array< int > &node_data)
Definition sculpt.cc:7936
void calc_factors_common_bmesh(const Depsgraph &depsgraph, const Brush &brush, const Object &object, Span< float3 > positions, bke::pbvh::BMeshNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:6891
static void update_sculpt_normal(const Depsgraph &depsgraph, const Sculpt &sd, Object &ob, const brushes::CursorSampleResult &cursor_sample_result)
Definition sculpt.cc:2755
void cache_calc_brushdata_symm(StrokeCache &cache, const ePaintSymmetryFlags symm, const char axis, const float angle)
Definition sculpt.cc:3725
bool brush_type_is_mask(const int tool)
static void accumulate_area_normal(const float3 &normal, const float distance, const float radius_inv, const int flip_index, AreaNormalCenterData &anctd)
Definition sculpt.cc:1436
bool paint_brush_tool_poll(bContext *C)
void tag_update_overlays(bContext *C)
Definition sculpt.cc:895
void calc_factors_common_from_orig_data_bmesh(const Depsgraph &depsgraph, const Brush &brush, const Object &object, Span< float3 > positions, Span< float3 > normals, bke::pbvh::BMeshNode &node, Vector< float > &r_factors, Vector< float > &r_distances)
Definition sculpt.cc:7043
Span< float3 > vert_positions_for_grab_active_get(const Depsgraph &depsgraph, const Object &object)
Definition sculpt.cc:179
static void mask_brush_toggle_off(Paint *paint, StrokeCache *cache)
Definition sculpt.cc:4011
float3 tilt_apply_to_normal(const Object &object, const float4x4 &view_inverse, const float3 &normal, const float2 &tilt, const float tilt_strength)
Definition sculpt.cc:2876
static float area_normal_and_center_get_position_radius(const SculptSession &ss, const Brush &brush)
Definition sculpt.cc:1384
static IndexMask pbvh_gather_generic(Object &ob, const Brush &brush, const bool use_original, const float radius_scale, IndexMaskMemory &memory)
Definition sculpt.cc:2622
static void sculpt_project_v3_normal_align(const StrokeCache &cache, const float normal_weight, float grab_delta[3])
Definition sculpt.cc:696
bool is_symmetry_iteration_valid(const char i, const char symm)
constexpr ParallelGrainSize grain_size(int grain_size)
QuaternionBase< float > Quaternion
T length_squared(const VecBase< T, Size > &a)
VecBase< T, 3 > normal_tri(const VecBase< T, 3 > &v1, const VecBase< T, 3 > &v2, const VecBase< T, 3 > &v3)
T clamp(const T &a, const T &min, const T &max)
T safe_rcp(const T &a)
QuaternionBase< T > to_quaternion(const AxisAngleBase< T, AngleT > &axis_angle)
T safe_divide(const T &a, const T &b)
T reduce_max(const VecBase< T, Size > &a)
T distance(const T &a, const T &b)
T length(const VecBase< T, Size > &a)
AxisAngleBase< float, AngleRadianBase< float > > AxisAngle
QuaternionBase< T > normalize_and_get_length(const QuaternionBase< T > &q, T &out_length)
T dot(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
T min(const T &a, const T &b)
bool is_zero(const T &a)
CartesianBasis invert(const CartesianBasis &basis)
float3 rotate_direction_around_axis(const float3 &direction, const float3 &axis, float angle)
AxisSigned cross(const AxisSigned a, const AxisSigned b)
VectorT project_point(const MatT &mat, const VectorT &point)
MatT from_scale(const VecBase< typename MatT::base_type, ScaleDim > &scale)
T interpolate(const T &a, const T &b, const FactorT &t)
T rcp(const T &a)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
T square(const T &a)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
T max(const T &a, const T &b)
T abs(const T &a)
VecBase< T, 3 > transform_direction(const MatBase< T, 3, 3 > &mat, const VecBase< T, 3 > &direction)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
auto isolate_task(const Function &function)
Definition BLI_task.hh:224
Value parallel_reduce(IndexRange range, int64_t grain_size, const Value &identity, const Function &function, const Reduction &reduction)
Definition BLI_task.hh:127
BMesh Iterators.
@ V3D_OVERLAY_SCULPT_SHOW_MASK
@ V3D_OVERLAY_SCULPT_SHOW_FACE_SETS
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
MINLINE float len_squared_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
float WM_event_tablet_data(const wmEvent *event, bool *r_pen_flip, float r_tilt[2])
struct bNodeTreeExec * ntreeTexBeginExecTree(struct bNodeTree *ntree)
void BKE_mesh_copy_parameters(Mesh *me_dst, const Mesh *me_src)
void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
ScrArea * CTX_wm_area(const bContext *C)
int RNA_enum_get(PointerRNA *ptr, const char *name)
void multires_mark_as_modified(Depsgraph *depsgraph, Object *object, MultiresModifiedFlags flags)
Definition multires.cc:254
@ RPT_WARNING
Definition BKE_report.hh:40
const Set< BMFace *, 0 > & BKE_pbvh_bmesh_node_faces(bke::pbvh::BMeshNode *node)
std::variant< std::monostate, int, BMVert * > ActiveVert
Definition BKE_paint.hh:357
ViewContext ED_view3d_viewcontext_init(bContext *C, Depsgraph *depsgraph)
MultiresModifierData * BKE_sculpt_multires_active(const Scene *scene, Object *ob)
MINLINE void copy_v3_v3(float r[3], const float a[3])
@ BRUSH_STROKE_DRAG_DOT
@ BRUSH_STROKE_ANCHORED
float BKE_brush_sample_tex_3d(const Paint *paint, const Brush *br, const MTex *mtex, const float3 &point, float4 &rgba, int thread, ImagePool *pool)
Definition brush.cc:985
void ED_view3d_win_to_origin(const ARegion *region, const float mval[2], float r_out[3])
ATTR_WARN_UNUSED_RESULT const BMLoop * l
void axis_angle_normalized_to_quat(float r[4], const float axis[3], float angle)
void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
ePaintSymmetryAreas
Definition BKE_paint.hh:102
@ PAINT_SYMM_AREA_X
Definition BKE_paint.hh:103
@ PAINT_SYMM_AREA_Z
Definition BKE_paint.hh:105
@ PAINT_SYMM_AREA_Y
Definition BKE_paint.hh:104
bool BKE_base_is_visible(const View3D *v3d, const Base *base)
@ BRUSH_SNAKE_HOOK_DEFORM_ELASTIC
Depsgraph * CTX_data_depsgraph_pointer(const bContext *C)
void mul_v3_m4v3(float r[3], const float mat[4][4], const float vec[3])
MINLINE void copy_v2_v2(float r[2], const float a[2])
float BKE_brush_radius_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1366
@ PAINT_FALLOFF_SHAPE_SPHERE
@ PAINT_FALLOFF_SHAPE_TUBE
void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, Mesh *mesh_dst, Object *ob, bool process_shape_keys=true)
bool invert_m4_m4(float inverse[4][4], const float mat[4][4])
struct DistRayAABB_Precalc dist_squared_ray_to_aabb_v3_precalc(const float ray_origin[3], const float ray_direction[3])
Definition math_geom.cc:703
void ED_paint_brush_type_update_sticky_shading_color(bContext *C, Object *ob)
float2 ED_view3d_project_float_v2_m4(const ARegion *region, const float co[3], const float4x4 &mat)
MINLINE void add_v3_fl(float r[3], float f)
MINLINE void copy_v4_fl(float r[4], float f)
void mul_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4])
void view3d_operator_needs_gpu(const bContext *C)
@ BRUSH_PLANE_SWAP_HEIGHT_AND_DEPTH
@ BRUSH_AREA_RADIUS_PRESSURE
@ BRUSH_SMOOTH_DEFORM_LAPLACIAN
@ BRUSH_SMOOTH_DEFORM_SURFACE
int CustomData_get_layer_index(const CustomData *data, eCustomDataType type)
ATTR_WARN_UNUSED_RESULT const BMVert * v
void BKE_brush_calc_curve_factors(eBrushCurvePreset preset, const CurveMapping *cumap, Span< float > distances, float brush_radius, MutableSpan< float > factors)
Definition brush.cc:1561
MatBase< float, 4, 4 > float4x4
void ED_region_tag_redraw(ARegion *region)
Definition area.cc:681
bool BKE_subdiv_ccg_coord_is_mesh_boundary(OffsetIndices< int > faces, Span< int > corner_verts, BitSpan boundary_verts, const Set< OrderedEdge > &boundary_edges, const SubdivCCG &subdiv_ccg, SubdivCCGCoord coord)
void closest_to_plane_normalized_v3(float r_close[3], const float plane[4], const float pt[3])
Definition math_geom.cc:458
Base * CTX_data_active_base(const bContext *C)
void plane_from_point_normal_v3(float r_plane[4], const float plane_co[3], const float plane_no[3])
Definition math_geom.cc:225
@ BRUSH_CLOTH_DEFORM_EXPAND
@ BRUSH_CLOTH_DEFORM_SNAKE_HOOK
@ BRUSH_CLOTH_DEFORM_GRAB
MINLINE float pow3f(float x)
bool BM_vert_is_boundary(const BMVert *v)
void BKE_sculptsession_free_pbvh(Object &object)
bool BKE_brush_use_alpha_pressure(const Brush *brush)
Definition brush.cc:1385
MINLINE float pow4f(float x)
void BKE_sculpt_mask_layers_ensure(Depsgraph *depsgraph, Main *bmain, Object *ob, MultiresModifierData *mmd)
std::optional< Array< bool > > BKE_keyblock_get_dependent_keys(const Key *key, int index)
Definition key.cc:1875
MINLINE void mul_v3_fl(float r[3], float f)
MINLINE float pow2f(float x)
CCGKey BKE_subdiv_ccg_key_top_level(const SubdivCCG &subdiv_ccg)
void normalize_m4(float R[4][4]) ATTR_NONNULL()
@ SCULPT_BRUSH_TYPE_INFLATE
@ SCULPT_BRUSH_TYPE_SMEAR
@ SCULPT_BRUSH_TYPE_CLOTH
@ SCULPT_BRUSH_TYPE_SIMPLIFY
@ SCULPT_BRUSH_TYPE_SMOOTH
@ SCULPT_BRUSH_TYPE_CLAY_STRIPS
@ SCULPT_BRUSH_TYPE_CREASE
@ SCULPT_BRUSH_TYPE_DRAW_FACE_SETS
@ SCULPT_BRUSH_TYPE_GRAB
@ SCULPT_BRUSH_TYPE_BLUR
@ SCULPT_BRUSH_TYPE_PAINT
@ SCULPT_BRUSH_TYPE_BLOB
@ SCULPT_BRUSH_TYPE_PLANE
@ SCULPT_BRUSH_TYPE_SLIDE_RELAX
@ SCULPT_BRUSH_TYPE_PINCH
@ SCULPT_BRUSH_TYPE_POSE
@ SCULPT_BRUSH_TYPE_ROTATE
@ SCULPT_BRUSH_TYPE_LAYER
@ SCULPT_BRUSH_TYPE_DISPLACEMENT_ERASER
@ SCULPT_BRUSH_TYPE_BOUNDARY
@ SCULPT_BRUSH_TYPE_MASK
@ SCULPT_BRUSH_TYPE_DISPLACEMENT_SMEAR
@ SCULPT_BRUSH_TYPE_DRAW_SHARP
@ SCULPT_BRUSH_TYPE_SNAKE_HOOK
@ SCULPT_BRUSH_TYPE_CLAY
@ SCULPT_BRUSH_TYPE_CLAY_THUMB
@ SCULPT_BRUSH_TYPE_MULTIPLANE_SCRAPE
@ SCULPT_BRUSH_TYPE_SCENE_PROJECT
@ SCULPT_BRUSH_TYPE_THUMB
@ SCULPT_BRUSH_TYPE_NUDGE
@ SCULPT_BRUSH_TYPE_ELASTIC_DEFORM
@ SCULPT_BRUSH_TYPE_DRAW
float BKE_brush_unprojected_radius_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1412
Global G
Definition blender.cc:57
MINLINE void sub_v3_v3(float r[3], const float a[3])
void BKE_brush_unprojected_size_set(Paint *paint, Brush *brush, float unprojected_size)
Definition brush.cc:1390
VecBase< float, 4 > float4
void mul_m4_v3(const float M[4][4], float r[3])
void BKE_subdiv_ccg_neighbor_coords_get(const SubdivCCG &subdiv_ccg, const SubdivCCGCoord &coord, bool include_duplicates, SubdivCCGNeighbors &r_neighbors)
MINLINE void madd_v3_v3fl(float r[3], const float a[3], float f)
void BKE_curvemapping_init(CurveMapping *cumap)
KeyBlock * BKE_keyblock_find_by_index(Key *key, int index)
Definition key.cc:1425
void BKE_pbvh_bmesh_node_save_orig(BMesh *bm, BMLog *log, bke::pbvh::BMeshNode *node, bool use_original)
@ BRUSH_PAINT_WET_MIX_PRESSURE_INVERT
@ BRUSH_PAINT_WET_PERSISTENCE_PRESSURE
@ BRUSH_PAINT_FLOW_PRESSURE_INVERT
@ BRUSH_PAINT_DENSITY_PRESSURE
@ BRUSH_PAINT_WET_MIX_PRESSURE
@ BRUSH_PAINT_DENSITY_PRESSURE_INVERT
@ BRUSH_PAINT_WET_PERSISTENCE_PRESSURE_INVERT
@ BRUSH_PAINT_FLOW_PRESSURE
VecBase< int32_t, 2 > int2
VecBase< float, 2 > float2
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
Mesh * BKE_mesh_from_object(Object *ob)
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
@ MULTIRES_COORDS_MODIFIED
wmWindowManager * CTX_wm_manager(const bContext *C)
Depsgraph * CTX_data_ensure_evaluated_depsgraph(const bContext *C, bool rna_write_check=false)
int CustomData_get_offset_named(const CustomData *data, eCustomDataType type, StringRef name)
float3 BKE_paint_seed_hsv_jitter()
void multires_stitch_grids(Object *)
Definition multires.cc:551
unsigned char uint8_t
Definition BKE_text.h:79
int BM_mesh_elem_count(BMesh *bm, const char htype)
void BKE_pbvh_bmesh_after_stroke(BMesh &bm, bke::pbvh::Tree &pbvh)
int BKE_sculpt_get_grid_num_verts(const Object &object)
void quat_to_axis_angle(float axis[3], float *angle, const float q[4])
bool BKE_view_layer_synced_ensure(const Main &bmain, const Scene *scene, ViewLayer *view_layer)
void ntreeTexEndExecTree(struct bNodeTreeExec *exec)
MINLINE float plane_point_side_v3(const float plane[4], const float co[3])
int BKE_brush_size_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1356
@ SCULPT_DYNTOPO_DETAIL_CONSTANT
@ SCULPT_DYNTOPO_COLLAPSE
@ SCULPT_DYNTOPO_SUBDIVIDE
@ SCULPT_DYNTOPO_DETAIL_MANUAL
@ SCULPT_DYNTOPO_DETAIL_BRUSH
BLI_INLINE bool BM_edge_is_boundary(const BMEdge *e) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
void interp_v3_v3v3(float r[3], const float a[3], const float b[3], float t)
float ED_view3d_calc_zfac(const RegionView3D *rv3d, const float co[3])
void isect_ray_tri_watertight_v3_precalc(struct IsectRayPrecalc *isect_precalc, const float ray_direction[3])
RegionView3D * CTX_wm_region_view3d(const bContext *C)
ToolSettings * CTX_data_tool_settings(const bContext *C)
bool BKE_paint_brush_set(Paint *paint, Brush *brush)
bool BKE_brush_use_locked_size(const Paint *paint, const Brush *brush)
Definition brush.cc:1371
bool paint_get_tex_pixel(const MTex *mtex, float u, float v, ImagePool *pool, int thread, float *r_intensity, float r_rgba[4])
int BLI_task_parallel_thread_id(const TaskParallelTLS *tls)
bool RNA_boolean_get(PointerRNA *ptr, const char *name)
void BKE_brush_size_set(Paint *paint, Brush *brush, int size)
Definition brush.cc:1340
const float * BM_log_find_original_vert_mask(BMLog *log, BMVert *v)
Definition bmesh_log.cc:799
@ V3D_SHADING_VERTEX_COLOR
MINLINE void zero_v3(float r[3])
void BKE_id_free(Main *bmain, void *idv)
BLI_INLINE BMVert * BM_vert_at_index(BMesh *bm, const int index)
const MTex * BKE_brush_mask_texture_get(const Brush *brush, PaintMode paint_mode)
Definition brush.cc:969
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
void BKE_sculpt_color_layer_create_if_needed(Object *object)
int BKE_subdiv_ccg_grid_to_face_index(const SubdivCCG &subdiv_ccg, const int grid_index)
int CCG_grid_xy_to_index(const int grid_size, const int x, const int y)
Definition BKE_ccg.hh:75
void project_plane_v3_v3v3(float out[3], const float p[3], const float v_plane[3])
void mul_mat3_m4_v3(const float mat[4][4], float r[3])
MINLINE float normalize_v3_v3(float r[3], const float a[3])
@ BRUSH_AUTOMASKING_CAVITY_ALL
void paint_stroke_operator_properties(wmOperatorType *ot)
bool BKE_brush_use_size_pressure(const Brush *brush)
Definition brush.cc:1380
@ KEYBLOCK_LOCKED_SHAPE
MINLINE void mul_v3_v3fl(float r[3], const float a[3], float f)
BMEdge * BM_edge_exists(BMVert *v_a, BMVert *v_b)
const Brush * BKE_paint_brush_for_read(const Paint *paint)
MINLINE float normalize_v3(float n[3])
wmOperatorType * WM_operatortype_find(const char *idname, bool quiet)
MINLINE void add_v3_v3(float r[3], const float a[3])
wmEventHandler_Op * WM_event_add_modal_handler(bContext *C, wmOperator *op)
void RNA_def_property_flag(PropertyRNA *prop, PropertyFlag flag)
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
bool ED_view3d_clipping_test(const RegionView3D *rv3d, const float co[3], bool is_local)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
bool BKE_sculptsession_use_pbvh_draw(const Object *ob, const RegionView3D *rv3d)
void rotate_m4(float mat[4][4], char axis, float angle)
bool BKE_pbvh_node_fully_masked_get(const bke::pbvh::Node &node)
Definition pbvh.cc:1642
Main * CTX_data_main(const bContext *C)
void BLI_dial_free(Dial *dial)
ATTR_WARN_UNUSED_RESULT const BMVert * v2
Paint * BKE_paint_get_active_from_context(const bContext *C)
bool ED_view3d_win_to_segment_clipped(const Depsgraph *depsgraph, const ARegion *region, const View3D *v3d, const float mval[2], float r_ray_start[3], float r_ray_end[3], bool do_clip_planes)
bool BKE_brush_has_cube_tip(const Brush *brush, PaintMode paint_mode)
Definition brush.cc:1816
MINLINE float max_ff(float a, float b)
float paint_calc_object_space_radius(const ViewContext &vc, const float3 &center, float pixel_radius)
void closest_on_tri_to_point_v3(float r[3], const float p[3], const float v1[3], const float v2[3], const float v3[3])
@ ID_RECALC_SHADING
Definition DNA_ID.h:1094
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
@ PROP_SKIP_SAVE
Definition RNA_types.hh:414
@ PROP_HIDDEN
Definition RNA_types.hh:408
@ BRUSH_DEFORM_TARGET_CLOTH_SIM
bool BKE_pbvh_node_fully_hidden_get(const bke::pbvh::Node &node)
Definition pbvh.cc:1625
Base * BKE_view_layer_base_find(ViewLayer *view_layer, Object *ob)
Dial * BLI_dial_init(const float start_position[2], float threshold)
MINLINE float square_f(float a)
void BKE_sculptsession_update_for_edit(Depsgraph *depsgraph, Object *ob_orig, bool is_paint_tool)
std::optional< BrushColorJitterSettings > BKE_brush_color_jitter_get_settings(const Paint *paint, const Brush *brush)
Definition brush.cc:1262
static CLG_LogRef LOG
Definition logging.cpp:12
void BKE_subdiv_ccg_foreach_visible_grid_vert(const CCGKey &key, const BitGroupVector<> &grid_hidden, const int grid, const Fn &fn)
@ BRUSH_PROJECT_RAY_DIRECTION_PLANE_NORMAL
Brush * BKE_paint_brush(Paint *paint)
SubdivCCGAdjacencyType BKE_subdiv_ccg_coarse_mesh_adjacency_info_get(const SubdivCCG &subdiv_ccg, const SubdivCCGCoord &coord, Span< int > corner_verts, OffsetIndices< int > faces, int &r_v1, int &r_v2)
@ BRUSH_ORIGINAL_NORMAL
@ BRUSH_GRAB_ACTIVE_VERTEX
@ BRUSH_HARDNESS_PRESSURE
@ BRUSH_OFFSET_PRESSURE
@ BRUSH_SMOOTH_PRESSURE
Scene * CTX_data_scene(const bContext *C)
float BLI_dial_angle(Dial *dial, const float current_position[2])
@ OPTYPE_BLOCKING
Definition WM_types.hh:192
void copy_m4_m4(float m1[4][4], const float m2[4][4])
VecBase< float, 3 > float3
void BKE_pbvh_node_get_bm_orco_data(const bke::pbvh::BMeshNode &node, Span< float3 > &r_orig_positions, Span< int3 > &r_orig_tris)
Definition pbvh.cc:1685
void scale_m4_fl(float R[4][4], float scale)
PropertyRNA * RNA_def_boolean(StructOrFunctionRNA *cont_, const char *identifier, const bool default_value, const char *ui_name, const char *ui_description)
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
bool BKE_paint_brush_set_essentials(Main *bmain, Paint *paint, const char *name)
void ED_view3d_win_to_3d(const View3D *v3d, const ARegion *region, const float depth_pt[3], const float mval[2], float r_out[3])
void BKE_pbvh_node_mark_topology_update(bke::pbvh::Node &node)
bScreen * WM_window_get_active_screen(const wmWindow *win)
@ PAINT_SYMMETRY_FEATHER
Object * CTX_data_active_object(const bContext *C)
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
const float * BM_log_find_original_vert_co(BMLog *log, BMVert *v)
Definition bmesh_log.cc:788
const Set< BMVert *, 0 > & BKE_pbvh_bmesh_node_unique_verts(bke::pbvh::BMeshNode *node)
ARegion * CTX_wm_region(const bContext *C)
float BKE_curvemapping_evaluateF(const CurveMapping *cumap, int cur, float value)
ListBaseT< Base > * BKE_view_layer_object_bases_get(ViewLayer *view_layer)
float dist_squared_ray_to_aabb_v3(const struct DistRayAABB_Precalc *data, const float bb_min[3], const float bb_max[3], float r_point[3], float *r_depth)
MINLINE bool is_zero_v3(const float v[3]) ATTR_WARN_UNUSED_RESULT
void ED_view3d_win_to_delta(const ARegion *region, const float xy_delta[2], float zfac, float r_out[3], bool precise=false)
View3D * CTX_wm_view3d(const bContext *C)
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
float BKE_brush_alpha_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1454
Mesh * BKE_object_get_evaluated_mesh(const Object *object_eval)
Definition object.cc:4436
const btScalar eps
Definition poly34.cpp:11
#define fabsf
#define sqrtf
#define sinf
#define cosf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
eRegion_Type regiontype
struct BMLoop * next
struct BMLoop * prev
struct BMVert * v
CustomData vdata
struct CurveMapping * curve_rand_value
struct CurveMapping * curve_rand_saturation
eBrushSculptType sculpt_brush_type
struct CurveMapping * curve_rand_hue
BrushMaskTool mask_tool
char name[258]
Definition DNA_ID.h:433
KeyBlockFlag flag
KeyBlock * refkey
ListBaseT< KeyBlock > block
eMTex_BrushMapMode brush_map_mode
const c_style_mat & ptr() const
bke::MeshRuntime * runtime
ListBaseT< ModifierData > modifiers
bke::ObjectRuntime * runtime
bke::PaintRuntime * runtime
eRegionView3D_Flag rflag
struct ViewRender * view_render
struct ToolSettings * toolsettings
ListBaseT< ARegion > regionbase
ScrArea_Runtime runtime
ListBaseT< SpaceLink > spacedata
std::unique_ptr< SculptBoundaryInfoCache > boundary_info_cache
Definition BKE_paint.hh:458
ed::sculpt_paint::StrokeCache * cache
Definition BKE_paint.hh:409
std::optional< int > active_face_index
Definition BKE_paint.hh:414
KeyBlock * shapekey_active
Definition BKE_paint.hh:368
void clear_active_elements(bool persist_last_active)
std::optional< float3 > cursor_sampled_normal
Definition BKE_paint.hh:424
std::unique_ptr< SculptTopologyIslandCache > topology_island_cache
Definition BKE_paint.hh:497
void set_active_vert(ActiveVert vert)
SculptFakeNeighbors fake_neighbors
Definition BKE_paint.hh:459
float3 active_vert_position(const Depsgraph &depsgraph, const Object &object) const
std::optional< int > active_grid_index
Definition BKE_paint.hh:415
ed::sculpt_paint::filter::Cache * filter_cache
Definition BKE_paint.hh:410
Array< float3x3, 0 > deform_imats
Definition BKE_paint.hh:397
MultiresModifierData * multires_modifier
Definition BKE_paint.hh:385
std::unique_ptr< bke::pbvh::Tree > pbvh
Definition BKE_paint.hh:390
RegionView3D * rv3d
Definition BKE_paint.hh:428
struct Object * gravity_object
int to_index(const CCGKey &key) const
SubdivCCGNeighborCoords coords
Array< float3 > positions
Array< float3 > normals
BitGroupVector grid_hidden
Array< float > masks
struct bNodeTree * nodetree
eView3DOverlay_Flag flag
eV3DShadingColorType color_type
View3DOverlay overlay
eView3D_Flag2 flag2
View3DShading shading
ViewLayer * view_layer
Definition ED_view3d.hh:80
RegionView3D * rv3d
Definition ED_view3d.hh:86
Depsgraph * depsgraph
Definition ED_view3d.hh:78
bke::bNodeTreeRuntime * runtime
ListBaseT< struct ScrArea > areabase
bToolRef_Runtime * runtime
const ImplicitSharingInfo * sharing_info
const ImplicitSharingInfo * face_offsets_sharing_info
static NearestVertData join(const NearestVertData &a, const NearestVertData &b)
Definition sculpt.cc:5984
wmOperatorStatus modal(bContext *C, wmOperator *op, const wmEvent *event)
wmOperatorStatus exec(bContext *C, wmOperator *op)
std::optional< float3 > get_location(float2 mouse, bool force_original) override
Definition sculpt.cc:4920
SculptPaintStroke(bContext *C, wmOperator *op, const wmEvent *event)
Definition sculpt.cc:4901
bool test_start(wmOperator *op, float2 mouse) override
Definition sculpt.cc:5519
void update_step(wmOperator *op, const StrokeStep &stroke_step) override
Definition sculpt.cc:5671
void done(bool is_cancel, bool stroke_started) override
Definition sculpt.cc:5724
static std::optional< ShapeKeyData > from_object(Object &object)
Definition sculpt.cc:7747
std::optional< math::Quaternion > rake_rotation
struct blender::ed::sculpt_paint::StrokeCache::@152245166116023055361007250031254315334135310141 mirror_modifier_clip
Vector< ProjectBrushTarget > project_targets
struct blender::ed::sculpt_paint::StrokeCache::@225223164012065274011166026353012314236244015262 plane_brush
std::unique_ptr< auto_mask::Cache > automasking
struct blender::ed::sculpt_paint::StrokeCache::@211256062006232337057366306324060315203271114371 clay_thumb_brush
struct blender::ed::sculpt_paint::StrokeCache::@346250254335162214324031351310170235363204044376 paint_brush
std::optional< math::Quaternion > rake_rotation_symm
std::unique_ptr< cloth::SimulationData > cloth_sim
void calc_cavity_factor(const Depsgraph &depsgraph, const Object &object, const IndexMask &node_mask)
wmOperatorStatus(*) exec(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1125
const char * description
Definition WM_types.hh:1115
void(*) cancel(bContext *C, wmOperator *op)
Definition WM_types.hh:1149
void(*) ui(bContext *C, wmOperator *op)
Definition WM_types.hh:1176
bool(*) poll(bContext *C) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1165
wmOperatorStatus(*) invoke(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1141
wmOperatorStatus(*) modal(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1157
struct ReportList * reports
struct wmOperatorType * type