Blender V5.3
sculpt_density.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include <numeric>
6
7#include "BKE_brush.hh"
8#include "BKE_bvhutils.hh"
9#include "BKE_context.hh"
10#include "BKE_geometry_set.hh"
11#include "BKE_mesh.hh"
12#include "BKE_mesh_runtime.hh"
13#include "BKE_mesh_sample.hh"
14#include "BKE_modifier.hh"
15#include "BKE_object.hh"
16#include "BKE_paint.hh"
17#include "BLI_bounds.hh"
18
19#include "ED_screen.hh"
20#include "ED_view3d.hh"
21
22#include "DEG_depsgraph.hh"
24
25#include "BLI_array_utils.hh"
27#include "BLI_kdtree_new.hh"
28#include "BLI_rand.hh"
29#include "BLI_task.hh"
30
32
33#include "DNA_brush_types.h"
34#include "DNA_mesh_types.h"
35
36#include "WM_api.hh"
37
38#include "sculpt_intern.hh"
39
41
43 private:
45 std::unique_ptr<KDTreeNew<float3>> original_curve_roots_kdtree_;
47 std::unique_ptr<KDTreeNew<float3>> deformed_curve_roots_kdtree_;
49 Array<float3> original_curve_root_positions_;
50 Array<float3> deformed_curve_root_positions_;
52 Vector<float3> new_deformed_root_positions_;
53 int original_curve_num_ = 0;
54
56
57 public:
59
60 void on_stroke_extended(const PaintStroke &stroke,
61 const StrokeExtension &stroke_extension) override;
62};
63
67
71
73 const Mesh *surface_orig_ = nullptr;
74
76 Mesh *surface_eval_ = nullptr;
80
82 const Brush *brush_ = nullptr;
84
88
90
91 DensityAddOperationExecutor(const PaintStroke &stroke) : ctx_(stroke) {}
92
93 void execute(DensityAddOperation &self, const StrokeExtension &stroke_extension)
94 {
95 self_ = &self;
97 curves_id_orig_ = id_cast<Curves *>(curves_ob_orig_->data);
98 curves_orig_ = &curves_id_orig_->geometry.wrap();
99
100 if (stroke_extension.is_first) {
101 self_->original_curve_num_ = curves_orig_->curves_num();
102 }
103
104 if (curves_id_orig_->surface == nullptr || curves_id_orig_->surface->type != OB_MESH) {
105 report_missing_surface(stroke_extension.reports);
106 return;
107 }
108
110 surface_orig_ = id_cast<const Mesh *>(surface_ob_orig_->data);
111 if (surface_orig_->faces_num == 0) {
112 report_empty_original_surface(stroke_extension.reports);
113 return;
114 }
115
117 if (surface_ob_eval_ == nullptr) {
118 return;
119 }
121 if (surface_eval_->faces_num == 0) {
122 report_empty_evaluated_surface(stroke_extension.reports);
123 return;
124 }
125
126 surface_bvh_eval_ = &surface_eval_->bvh_tris();
128 /* Find UV map. */
129 VArraySpan<float2> surface_uv_map;
130 if (curves_id_orig_->surface_uv_map != nullptr) {
131 surface_uv_map = *surface_orig_->attributes().lookup<float2>(curves_id_orig_->surface_uv_map,
133 surface_uv_map_eval_ = *surface_eval_->attributes().lookup<float2>(
135 }
136 if (surface_uv_map.is_empty()) {
138 return;
139 }
142 return;
143 }
144
146
152 brush_pos_re_ = stroke_extension.mouse_position;
153
155
156 Vector<float3> new_positions_cu;
157 Vector<float2> new_uvs;
159
160 /* Find potential new curve root points. */
161 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
162 this->sample_projected_with_symmetry(rng, new_uvs, new_positions_cu);
163 }
164 else if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
165 this->sample_spherical_with_symmetry(rng, new_uvs, new_positions_cu);
166 }
167 else {
169 }
171
172 if (stroke_extension.is_first) {
174 }
175
176 /* Used to tag all curves that are too close to existing curves or too close to other new
177 * curves. */
178 Array<bool> new_curve_skipped(new_positions_cu.size(), false);
179
180 const KDTreeNew<float3> added_this_stroke_kdtree(self_->new_deformed_root_positions_);
181
182 /* Check which new root points are close to roots that existed before the current stroke
183 * started, or to roots added earlier in the current stroke. */
184 const float minimum_distance_sq = pow2f(brush_settings_->minimum_distance);
185 threading::parallel_for(new_positions_cu.index_range(), 128, [&](const IndexRange range) {
186 for (const int new_i : range) {
187 const float3 &new_root_pos_cu = new_positions_cu[new_i];
188 float distance_to_old_sq = FLT_MAX;
189 self_->deformed_curve_roots_kdtree_->find_nearest(new_root_pos_cu, &distance_to_old_sq);
190 if (distance_to_old_sq < minimum_distance_sq) {
191 new_curve_skipped[new_i] = true;
192 continue;
193 }
194 float distance_to_added_sq = FLT_MAX;
195 added_this_stroke_kdtree.find_nearest(new_root_pos_cu, &distance_to_added_sq);
196 if (distance_to_added_sq < minimum_distance_sq) {
197 new_curve_skipped[new_i] = true;
198 }
199 }
200 });
201
202 /* Find new points that are too close to other new points. */
203 const KDTreeNew<float3> new_positions_kdtree(new_positions_cu);
204 Array<int> duplicates(new_positions_cu.size(), -1);
205 kdtree::calc_duplicates(new_positions_kdtree,
207 IndexMask(new_positions_cu.size()),
208 duplicates);
209 for (const int new_i : new_positions_cu.index_range()) {
210 /* A point that other points were merged into uses its own index; only an actual merge
211 * target (a different index) means this point should be removed. */
212 if (duplicates[new_i] != -1 && duplicates[new_i] != new_i) {
213 new_curve_skipped[new_i] = true;
214 }
215 }
216
217 /* Remove points that are too close to others. */
218 for (int64_t i = new_positions_cu.size() - 1; i >= 0; i--) {
219 if (new_curve_skipped[i]) {
220 new_positions_cu.remove_and_reorder(i);
221 new_uvs.remove_and_reorder(i);
222 }
223 }
224 self_->new_deformed_root_positions_.extend(new_positions_cu);
225
226 const Span<float3> corner_normals_su = surface_orig_->corner_normals();
227 const Span<int3> surface_corner_tris_orig = surface_orig_->corner_tris();
228 const geometry::ReverseUVSampler reverse_uv_sampler{surface_uv_map, surface_corner_tris_orig};
229
230 geometry::AddCurvesOnMeshInputs add_inputs;
231 add_inputs.uvs = new_uvs;
232 add_inputs.interpolate_length = brush_settings_->flag &
234 add_inputs.interpolate_radius = brush_settings_->flag &
236 add_inputs.interpolate_shape = brush_settings_->flag &
238 add_inputs.interpolate_point_count = brush_settings_->flag &
240 add_inputs.interpolate_resolution = curves_orig_->attributes().contains("resolution");
241 add_inputs.fallback_curve_length = brush_settings_->curve_length;
242 add_inputs.fallback_curve_radius = brush_settings_->curve_radius;
243 add_inputs.fallback_point_count = std::max(2, brush_settings_->points_per_curve);
244 add_inputs.transforms = &transforms_;
245 add_inputs.surface = surface_orig_;
246 add_inputs.corner_normals_su = corner_normals_su;
247 add_inputs.surface_corner_tris = surface_corner_tris_orig;
248 add_inputs.reverse_uv_sampler = &reverse_uv_sampler;
249 add_inputs.old_roots_kdtree = self_->original_curve_roots_kdtree_.get();
250
251 const geometry::AddCurvesOnMeshOutputs add_outputs = geometry::add_curves_on_mesh(
252 *curves_orig_, add_inputs);
253 bke::MutableAttributeAccessor attributes = curves_orig_->attributes_for_write();
254 if (bke::GSpanAttributeWriter selection = attributes.lookup_for_write_span(".selection")) {
255 curves::fill_selection_true(selection.span.slice(selection.domain == bke::AttrDomain::Point ?
256 add_outputs.new_points_range :
257 add_outputs.new_curves_range));
258 selection.finish();
259 }
261 if (const std::optional<Bounds<float3>> center_cu = bounds::min_max(
262 curves_orig_->positions().slice(add_outputs.new_points_range)))
263 {
267 }
268 }
269
270 if (add_outputs.uv_error) {
271 report_invalid_uv_map(stroke_extension.reports);
272 }
273
277 }
278
280 {
281 const bke::crazyspace::GeometryDeformation deformation =
283 const Span<int> curve_offsets = curves_orig_->offsets();
284 const Span<float3> original_positions = curves_orig_->positions();
285 const Span<float3> deformed_positions = deformation.positions;
286 BLI_assert(original_positions.size() == deformed_positions.size());
287
288 auto gather_root_positions = [&](const Span<float3> positions) {
290 array_utils::gather(positions,
291 curve_offsets.take_front(curves_orig_->curves_num()),
292 roots.as_mutable_span());
293 return roots;
294 };
295
297 1024 < original_positions.size() + deformed_positions.size(),
298 [&]() {
299 self_->original_curve_root_positions_ = gather_root_positions(original_positions);
300 self_->original_curve_roots_kdtree_ = std::make_unique<KDTreeNew<float3>>(
301 self_->original_curve_root_positions_.as_span());
302 },
303 [&]() {
304 self_->deformed_curve_root_positions_ = gather_root_positions(deformed_positions);
305 self_->deformed_curve_roots_kdtree_ = std::make_unique<KDTreeNew<float3>>(
306 self_->deformed_curve_root_positions_.as_span());
307 });
308 }
309
311 Vector<float2> &r_uvs,
312 Vector<float3> &r_positions_su)
313 {
315
316 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
318 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
319 const float4x4 brush_transform_inv = math::invert(brush_transform);
320 const float4x4 transform = transforms_.curves_to_surface * brush_transform *
322 Vector<float3> positions_su;
323 Vector<float3> bary_coords;
324 Vector<int> tri_indices;
326 rng,
331 [&](const float2 &pos_re, float3 &r_start_su, float3 &r_end_su) {
332 float3 start_wo, end_wo;
334 ctx_.depsgraph, ctx_.region, ctx_.v3d, pos_re, start_wo, end_wo, true);
335 r_start_su = math::transform_point(transform, start_wo);
336 r_end_su = math::transform_point(transform, end_wo);
337 },
338 true,
341 bary_coords,
342 tri_indices,
343 positions_su);
344
345 /* Remove some sampled points randomly based on the brush falloff and strength. */
346 for (int i = new_points - 1; i >= 0; i--) {
347 const float3 pos_su = positions_su[i];
348 const float3 pos_cu = math::transform_point(
349 brush_transform_inv, math::transform_point(transforms_.surface_to_curves, pos_su));
350 const float2 pos_re = ED_view3d_project_float_v2_m4(ctx_.region, pos_cu, projection);
351 const float dist_to_brush_re = math::distance(brush_pos_re_, pos_re);
352 const float radius_falloff = BKE_brush_curve_strength(
353 brush_, dist_to_brush_re, brush_radius_re_);
354 const float weight = brush_strength_ * radius_falloff;
355 if (rng.get_float() > weight) {
356 bary_coords.remove_and_reorder(i);
357 tri_indices.remove_and_reorder(i);
358 positions_su.remove_and_reorder(i);
359 }
360 }
361
362 for (const int i : bary_coords.index_range()) {
364 bary_coords[i], surface_corner_tris_eval_[tri_indices[i]], surface_uv_map_eval_);
365 r_uvs.append(uv);
366 }
367 r_positions_su.extend(positions_su);
368 }
369 }
370
372 Vector<float2> &r_uvs,
373 Vector<float3> &r_positions_su)
374 {
375 const std::optional<CurvesBrush3D> brush_3d = sample_curves_surface_3d_brush(
377 *ctx_.region,
378 *ctx_.v3d,
383 if (!brush_3d.has_value()) {
384 return;
385 }
386
387 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
389 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
390 const float3 brush_pos_cu = math::transform_point(brush_transform, brush_3d->position_cu);
392 brush_pos_cu);
393 const float brush_radius_su = transform_brush_radius(
394 transforms_.curves_to_surface, brush_pos_cu, brush_3d->radius_cu);
395 const float brush_radius_sq_su = pow2f(brush_radius_su);
396
397 Vector<int> selected_corner_tri_indices;
398 surface_bvh_eval_->range_query(brush_pos_su, brush_radius_su, [&](const int index) {
399 selected_corner_tri_indices.append(index);
400 return true;
401 });
402
403 const float brush_plane_area_su = M_PI * brush_radius_sq_su;
404 const float approximate_density_su = brush_settings_->density_add_attempts /
405 brush_plane_area_su;
406
407 Vector<float3> positions_su;
408 Vector<float3> bary_coords;
409 Vector<int> tri_indices;
411 rng,
413 selected_corner_tri_indices,
414 brush_pos_su,
415 brush_radius_su,
416 approximate_density_su,
417 bary_coords,
418 tri_indices,
419 positions_su);
420
421 /* Remove some sampled points randomly based on the brush falloff and strength. */
422 for (int i = new_points - 1; i >= 0; i--) {
423 const float3 pos_su = positions_su[i];
425 const float dist_to_brush_cu = math::distance(pos_cu, brush_pos_cu);
426 const float radius_falloff = BKE_brush_curve_strength(
427 brush_, dist_to_brush_cu, brush_3d->radius_cu);
428 const float weight = brush_strength_ * radius_falloff;
429 if (rng.get_float() > weight) {
430 bary_coords.remove_and_reorder(i);
431 tri_indices.remove_and_reorder(i);
432 positions_su.remove_and_reorder(i);
433 }
434 }
435
436 for (const int i : bary_coords.index_range()) {
438 bary_coords[i], surface_corner_tris_eval_[tri_indices[i]], surface_uv_map_eval_);
439 r_uvs.append(uv);
440 }
441 r_positions_su.extend(positions_su);
442 }
443 }
444};
445
447 const StrokeExtension &stroke_extension)
448{
449 DensityAddOperationExecutor executor{stroke};
450 executor.execute(*this, stroke_extension);
451}
452
454 private:
456
462 Vector<float3> deformed_root_positions_;
463
464 public:
465 void on_stroke_extended(const PaintStroke &stroke,
466 const StrokeExtension &stroke_extension) override;
467};
468
476
477 Object *object_ = nullptr;
478 Curves *curves_id_ = nullptr;
480
483
485 Mesh *surface_orig_ = nullptr;
486
488 Mesh *surface_eval_ = nullptr;
490
491 const CurvesSculpt *curves_sculpt_ = nullptr;
492 const Brush *brush_ = nullptr;
497
499
501
502 std::unique_ptr<KDTreeNew<float3>> root_points_kdtree_;
503
505
506 void execute(DensitySubtractOperation &self, const StrokeExtension &stroke_extension)
507 {
508 self_ = &self;
509
511
512 curves_id_ = id_cast<Curves *>(object_->data);
513 curves_ = &curves_id_->geometry.wrap();
514 if (curves_->is_empty()) {
515 return;
516 }
517
518 surface_ob_orig_ = curves_id_->surface;
519 if (surface_ob_orig_ == nullptr) {
520 return;
521 }
522 surface_orig_ = id_cast<Mesh *>(surface_ob_orig_->data);
523
525 if (surface_ob_eval_ == nullptr) {
526 return;
527 }
529
530 surface_bvh_eval_ = &surface_eval_->bvh_tris();
531
535 brush_radius_factor_ = brush_radius_factor(*brush_, stroke_extension);
537 brush_pos_re_ = stroke_extension.mouse_position;
538
540
542
545
546 if (stroke_extension.is_first) {
547 const bke::crazyspace::GeometryDeformation deformation =
549 for (const int curve_i : curves_->curves_range()) {
550 const int first_point_i = curves_->offsets()[curve_i];
551 self_->deformed_root_positions_.append(deformation.positions[first_point_i]);
552 }
553 }
554
555 root_points_kdtree_ = std::make_unique<KDTreeNew<float3>>(
556 self_->deformed_root_positions_.as_span(), curve_selection_);
557
558 /* Find all curves that should be deleted. */
559 Array<bool> curves_to_keep(curves_->curves_num(), true);
560 if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
561 this->reduce_density_projected_with_symmetry(curves_to_keep);
562 }
563 else if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
564 this->reduce_density_spherical_with_symmetry(curves_to_keep);
565 }
566 else {
568 }
569
570 IndexMaskMemory mask_memory;
571 const IndexMask mask_to_keep = IndexMask::from_bools(curves_to_keep, mask_memory);
572
573 /* Remove deleted curves from the stored deformed root positions. */
574 BLI_assert(curves_->curves_num() == self_->deformed_root_positions_.size());
575 Vector<float3> new_deformed_positions(mask_to_keep.size());
576 array_utils::gather(self_->deformed_root_positions_.as_span(),
577 mask_to_keep,
578 new_deformed_positions.as_mutable_span());
579 self_->deformed_root_positions_ = std::move(new_deformed_positions);
580
581 *curves_ = bke::curves_copy_curve_selection(*curves_, mask_to_keep, {});
582 BLI_assert(curves_->curves_num() == self_->deformed_root_positions_.size());
583
587 }
588
590 {
591 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
593 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
594 this->reduce_density_projected(brush_transform, curves_to_keep);
595 }
596 }
597
598 void reduce_density_projected(const float4x4 &brush_transform, MutableSpan<bool> curves_to_keep)
599 {
600 const float brush_radius_re = brush_radius_base_re_ * brush_radius_factor_;
601 const float brush_radius_sq_re = pow2f(brush_radius_re);
602
604
605 /* Randomly select the curves that are allowed to be removed, based on the brush radius and
606 * strength. */
607 Array<bool> allow_remove_curve(curves_->curves_num(), false);
608 threading::parallel_for(curves_->curves_range(), 512, [&](const IndexRange range) {
609 RandomNumberGenerator rng = RandomNumberGenerator::from_random_seed();
610
611 for (const int curve_i : range) {
612 if (!curves_to_keep[curve_i]) {
613 allow_remove_curve[curve_i] = true;
614 continue;
615 }
616 const float3 pos_cu = math::transform_point(brush_transform,
617 self_->deformed_root_positions_[curve_i]);
618
619 const float2 pos_re = ED_view3d_project_float_v2_m4(ctx_.region, pos_cu, projection);
620 const float dist_to_brush_sq_re = math::distance_squared(brush_pos_re_, pos_re);
621 if (dist_to_brush_sq_re > brush_radius_sq_re) {
622 continue;
623 }
624 const float dist_to_brush_re = std::sqrt(dist_to_brush_sq_re);
625 const float radius_falloff = BKE_brush_curve_strength(
626 brush_, dist_to_brush_re, brush_radius_re);
627 const float weight = brush_strength_ * radius_falloff;
628 if (rng.get_float() < weight) {
629 allow_remove_curve[curve_i] = true;
630 }
631 }
632 });
633
634 /* Detect curves that are too close to other existing curves. */
635 curve_selection_.foreach_segment([&](const IndexMaskSegment segment) {
636 for (const int curve_i : segment) {
637 if (!curves_to_keep[curve_i]) {
638 continue;
639 }
640 if (!allow_remove_curve[curve_i]) {
641 continue;
642 }
643 const float3 orig_pos_cu = self_->deformed_root_positions_[curve_i];
644 const float3 pos_cu = math::transform_point(brush_transform, orig_pos_cu);
645 const float2 pos_re = ED_view3d_project_float_v2_m4(ctx_.region, pos_cu, projection);
646 const float dist_to_brush_sq_re = math::distance_squared(brush_pos_re_, pos_re);
647 if (dist_to_brush_sq_re > brush_radius_sq_re) {
648 continue;
649 }
650 root_points_kdtree_->foreach_in_radius(
651 orig_pos_cu,
652 minimum_distance_,
653 [&](const int other_curve_i, const float /*distance_sq*/) {
654 if (other_curve_i == curve_i) {
655 return;
656 }
657 if (allow_remove_curve[other_curve_i]) {
658 curves_to_keep[other_curve_i] = false;
659 }
660 });
661 }
662 });
663 }
664
666 {
667 const float brush_radius_re = brush_radius_base_re_ * brush_radius_factor_;
668 const std::optional<CurvesBrush3D> brush_3d = sample_curves_surface_3d_brush(
670 *ctx_.region,
671 *ctx_.v3d,
675 brush_radius_re);
676 if (!brush_3d.has_value()) {
677 return;
678 }
679
680 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
682 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
683 const float3 brush_pos_cu = math::transform_point(brush_transform, brush_3d->position_cu);
684 this->reduce_density_spherical(brush_pos_cu, brush_3d->radius_cu, curves_to_keep);
685 }
686 }
687
688 void reduce_density_spherical(const float3 &brush_pos_cu,
689 const float brush_radius_cu,
690 MutableSpan<bool> curves_to_keep)
691 {
692 const float brush_radius_sq_cu = pow2f(brush_radius_cu);
693
694 /* Randomly select the curves that are allowed to be removed, based on the brush radius and
695 * strength. */
696 Array<bool> allow_remove_curve(curves_->curves_num(), false);
697 threading::parallel_for(curves_->curves_range(), 512, [&](const IndexRange range) {
698 RandomNumberGenerator rng = RandomNumberGenerator::from_random_seed();
699
700 for (const int curve_i : range) {
701 if (!curves_to_keep[curve_i]) {
702 allow_remove_curve[curve_i] = true;
703 continue;
704 }
705 const float3 pos_cu = self_->deformed_root_positions_[curve_i];
706
707 const float dist_to_brush_sq_cu = math::distance_squared(brush_pos_cu, pos_cu);
708 if (dist_to_brush_sq_cu > brush_radius_sq_cu) {
709 continue;
710 }
711 const float dist_to_brush_cu = std::sqrt(dist_to_brush_sq_cu);
712 const float radius_falloff = BKE_brush_curve_strength(
713 brush_, dist_to_brush_cu, brush_radius_cu);
714 const float weight = brush_strength_ * radius_falloff;
715 if (rng.get_float() < weight) {
716 allow_remove_curve[curve_i] = true;
717 }
718 }
719 });
720
721 /* Detect curves that are too close to other existing curves. */
722 curve_selection_.foreach_segment([&](const IndexMaskSegment segment) {
723 for (const int curve_i : segment) {
724 if (!curves_to_keep[curve_i]) {
725 continue;
726 }
727 if (!allow_remove_curve[curve_i]) {
728 continue;
729 }
730 const float3 &pos_cu = self_->deformed_root_positions_[curve_i];
731 const float dist_to_brush_sq_cu = math::distance_squared(pos_cu, brush_pos_cu);
732 if (dist_to_brush_sq_cu > brush_radius_sq_cu) {
733 continue;
734 }
735
736 root_points_kdtree_->foreach_in_radius(
737 pos_cu, minimum_distance_, [&](const int other_curve_i, const float /*distance_sq*/) {
738 if (other_curve_i == curve_i) {
739 return;
740 }
741 if (allow_remove_curve[other_curve_i]) {
742 curves_to_keep[other_curve_i] = false;
743 }
744 });
745 }
746 });
747 }
748};
749
751 const StrokeExtension &stroke_extension)
752{
753 DensitySubtractOperationExecutor executor{stroke};
754 executor.execute(*this, stroke_extension);
755}
756
760static bool use_add_density_mode(const BrushStrokeMode brush_mode,
761 const Scene &scene,
762 const Depsgraph &depsgraph,
763 const ARegion &region,
764 const View3D &v3d,
765 const Object &object,
766 const StrokeExtension &stroke_start)
767{
768 const Paint &paint = scene.toolsettings->curves_sculpt->paint;
770
772 brush.curves_sculpt_settings->density_mode);
773 const bool use_invert = brush_mode == BrushStrokeMode::Invert;
774
775 if (density_mode == BRUSH_CURVES_SCULPT_DENSITY_MODE_ADD) {
776 return !use_invert;
777 }
778 if (density_mode == BRUSH_CURVES_SCULPT_DENSITY_MODE_REMOVE) {
779 return use_invert;
780 }
781
782 const Object &curves_ob_orig = object;
783 const Curves &curves_id_orig = *id_cast<Curves *>(curves_ob_orig.data);
784 Object *surface_ob_orig = curves_id_orig.surface;
785 if (surface_ob_orig == nullptr) {
786 return true;
787 }
788 Object *surface_ob_eval = DEG_get_evaluated(&depsgraph, surface_ob_orig);
789 if (surface_ob_eval == nullptr) {
790 return true;
791 }
792 const CurvesGeometry &curves = curves_id_orig.geometry.wrap();
793 if (curves.curves_num() <= 1) {
794 return true;
795 }
796 const Mesh *surface_mesh_eval = BKE_object_get_evaluated_mesh(surface_ob_eval);
797 if (surface_mesh_eval == nullptr) {
798 return true;
799 }
800
801 const CurvesSurfaceTransforms transforms(curves_ob_orig, curves_id_orig.surface);
802 const bke::bvh::Tree &surface_bvh_eval = surface_mesh_eval->bvh_tris();
803
804 const float2 brush_pos_re = stroke_start.mouse_position;
805 /* Reduce radius so that only an inner circle is used to determine the existing density. */
806 const float brush_radius_re = BKE_brush_radius_get(&paint, &brush) * 0.5f;
807
808 /* Find the surface point under the brush. */
809 const std::optional<CurvesBrush3D> brush_3d = sample_curves_surface_3d_brush(
810 depsgraph, region, v3d, transforms, surface_bvh_eval, brush_pos_re, brush_radius_re);
811 if (!brush_3d.has_value()) {
812 return true;
813 }
814
815 const float3 brush_pos_cu = brush_3d->position_cu;
816 const float brush_radius_cu = brush_3d->radius_cu;
817 const float brush_radius_sq_cu = pow2f(brush_radius_cu);
818
819 const bke::crazyspace::GeometryDeformation deformation =
820 bke::crazyspace::get_evaluated_curves_deformation(depsgraph, curves_ob_orig);
821 const Span<int> offsets = curves.offsets();
822
823 /* Compute distance from brush to curve roots. */
824 Array<std::pair<float, int>> distances_sq_to_brush(curves.curves_num());
825 threading::EnumerableThreadSpecific<int> valid_curve_count_by_thread([&]() { return 0; });
826 threading::parallel_for(curves.curves_range(), 512, [&](const IndexRange range) {
827 int &valid_curve_count = valid_curve_count_by_thread.local();
828 for (const int curve_i : range) {
829 const int root_point_i = offsets[curve_i];
830 const float3 &root_pos_cu = deformation.positions[root_point_i];
831 const float dist_sq_cu = math::distance_squared(root_pos_cu, brush_pos_cu);
832 if (dist_sq_cu < brush_radius_sq_cu) {
833 distances_sq_to_brush[curve_i] = {math::distance_squared(root_pos_cu, brush_pos_cu),
834 curve_i};
835 valid_curve_count++;
836 }
837 else {
838 distances_sq_to_brush[curve_i] = {FLT_MAX, -1};
839 }
840 }
841 });
842 const int valid_curve_count = std::accumulate(
843 valid_curve_count_by_thread.begin(), valid_curve_count_by_thread.end(), 0);
844
845 /* Find a couple of curves that are closest to the brush center. */
846 const int check_curve_count = std::min<int>(8, valid_curve_count);
847 std::partial_sort(distances_sq_to_brush.begin(),
848 distances_sq_to_brush.begin() + check_curve_count,
849 distances_sq_to_brush.end());
850
851 /* Compute the minimum pair-wise distance between the curve roots that are close to the brush
852 * center. */
853 float min_dist_sq_cu = FLT_MAX;
854 for (const int i : IndexRange(check_curve_count)) {
855 const float3 &pos_i = deformation.positions[offsets[distances_sq_to_brush[i].second]];
856 for (int j = i + 1; j < check_curve_count; j++) {
857 const float3 &pos_j = deformation.positions[offsets[distances_sq_to_brush[j].second]];
858 const float dist_sq_cu = math::distance_squared(pos_i, pos_j);
859 math::min_inplace(min_dist_sq_cu, dist_sq_cu);
860 }
861 }
862
863 const float min_dist_cu = std::sqrt(min_dist_sq_cu);
864 if (min_dist_cu > brush.curves_sculpt_settings->minimum_distance) {
865 return true;
866 }
867
868 return false;
869}
870
871std::unique_ptr<CurvesSculptStrokeOperation> new_density_operation(
872 BrushStrokeMode brush_mode,
873 const Scene &scene,
874 const Depsgraph &depsgraph,
875 const ARegion &region,
876 const View3D &v3d,
877 const Object &object,
878 const StrokeExtension &stroke_start)
879{
880 if (use_add_density_mode(brush_mode, scene, depsgraph, region, v3d, object, stroke_start)) {
881 return std::make_unique<DensityAddOperation>();
882 }
883 return std::make_unique<DensitySubtractOperation>();
884}
885
886} // namespace blender::ed::sculpt_paint
General operations, lookup, etc. for blender objects.
#define M_PI
#define NC_GEOM
Definition WM_types.hh:406
#define ND_DATA
Definition WM_types.hh:552
#define BLI_assert_unreachable()
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
static RandomNumberGenerator from_random_seed()
Definition rand.cc:288
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr Span take_front(int64_t n) const
Definition BLI_span.hh:197
int64_t size() const
void remove_and_reorder(const int64_t index)
void append(const T &value)
IndexRange index_range() const
MutableSpan< T > as_mutable_span()
void extend(Span< T > array)
bool contains(StringRef name) const
AttributeAccessor attributes() const
Span< float3 > positions() const
IndexRange curves_range() const
MutableAttributeAccessor attributes_for_write()
void range_query(const float3 &point, const float radius, FunctionRef< bool(int)> fn) const
Definition bvh.cc:762
constexpr bool is_empty() const
void on_stroke_extended(const PaintStroke &stroke, const StrokeExtension &stroke_extension) override
void on_stroke_extended(const PaintStroke &stroke, const StrokeExtension &stroke_extension) override
void foreach_segment(Fn &&fn, Mode mode=exec_mode::serial) const
#define FLT_MAX
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
GeometryDeformation get_evaluated_curves_deformation(const Object *ob_eval, const Object &ob_orig)
int sample_surface_points_spherical(RandomNumberGenerator &rng, const Mesh &mesh, Span< int > tris_to_sample, const float3 &sample_pos, float sample_radius, float approximate_density, Vector< float3 > &r_bary_coords, Vector< int > &r_tri_indices, Vector< float3 > &r_positions)
int sample_surface_points_projected(RandomNumberGenerator &rng, const Mesh &mesh, const bke::bvh::Tree &mesh_bvhtree, const float2 &sample_pos_re, float sample_radius_re, FunctionRef< void(const float2 &pos_re, float3 &r_start, float3 &r_end)> region_position_to_ray, bool front_face_only, int tries_num, int max_points, Vector< float3 > &r_bary_coords, Vector< int > &r_tri_indices, Vector< float3 > &r_positions)
T sample_corner_attribute_with_bary_coords(const float3 &bary_weights, const int3 &corner_tri, const Span< T > corner_attribute)
CurvesGeometry curves_copy_curve_selection(const CurvesGeometry &curves, const IndexMask &curves_to_copy, const AttributeFilter &attribute_filter)
std::optional< Bounds< T > > min_max(const std::optional< Bounds< T > > &a, const T &b)
Definition BLI_bounds.hh:56
IndexMask retrieve_selected_curves(const bke::CurvesGeometry &curves, LinearAllocator<> &memory)
void fill_selection_true(GMutableSpan selection)
void report_invalid_uv_map(ReportList *reports)
float brush_strength_get(const Paint &paint, const Brush &brush, const StrokeExtension &stroke_extension)
void report_empty_evaluated_surface(ReportList *reports)
std::optional< CurvesBrush3D > sample_curves_surface_3d_brush(const Depsgraph &depsgraph, const ARegion &region, const View3D &v3d, const CurvesSurfaceTransforms &transforms, const bke::bvh::Tree &surface_bvh, const float2 &brush_pos_re, const float brush_radius_re)
void report_missing_uv_map_on_original_surface(ReportList *reports)
void remember_stroke_position(CurvesSculpt &curves_sculpt, const float3 &brush_position_wo)
void report_missing_uv_map_on_evaluated_surface(ReportList *reports)
void report_missing_surface(ReportList *reports)
float brush_radius_get(const Paint &paint, const Brush &brush, const StrokeExtension &stroke_extension)
void report_empty_original_surface(ReportList *reports)
Vector< float4x4 > get_symmetry_brush_transforms(const eCurvesSymmetryType symmetry)
std::unique_ptr< CurvesSculptStrokeOperation > new_density_operation(BrushStrokeMode brush_mode, const Scene &scene, const Depsgraph &depsgraph, const ARegion &region, const View3D &v3d, const Object &object, const StrokeExtension &stroke_start)
static bool use_add_density_mode(const BrushStrokeMode brush_mode, const Scene &scene, const Depsgraph &depsgraph, const ARegion &region, const View3D &v3d, const Object &object, const StrokeExtension &stroke_start)
float brush_radius_factor(const Brush &brush, const StrokeExtension &stroke_extension)
float transform_brush_radius(const float4x4 &transform, const float3 &brush_position, const float old_radius)
AddCurvesOnMeshOutputs add_curves_on_mesh(bke::CurvesGeometry &curves, const AddCurvesOnMeshInputs &inputs)
int calc_duplicates(const KDTreeNew< T > &tree, typename T::base_type range, Span< int > visit_order, MutableSpan< int > duplicates)
Definition kdtree.cc:867
T distance(const T &a, const T &b)
void min_inplace(T &a, const T &b)
CartesianBasis invert(const CartesianBasis &basis)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
void transform_points(const float4x4 &transform, MutableSpan< float3 > points, bool use_threading=true)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
void parallel_invoke(Functions &&...functions)
Definition BLI_task.hh:197
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
void WM_main_add_notifier(uint type, void *reference)
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
float4x4 ED_view3d_ob_project_mat_get(const RegionView3D *rv3d, const Object *ob)
float BKE_brush_radius_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1366
@ PAINT_FALLOFF_SHAPE_SPHERE
@ PAINT_FALLOFF_SHAPE_TUBE
float2 ED_view3d_project_float_v2_m4(const ARegion *region, const float co[3], const float4x4 &mat)
MatBase< float, 4, 4 > float4x4
void ED_region_tag_redraw(ARegion *region)
Definition area.cc:681
MINLINE float pow2f(float x)
@ BRUSH_CURVES_SCULPT_FLAG_INTERPOLATE_RADIUS
@ BRUSH_CURVES_SCULPT_FLAG_INTERPOLATE_LENGTH
@ BRUSH_CURVES_SCULPT_FLAG_INTERPOLATE_POINT_COUNT
@ BRUSH_CURVES_SCULPT_FLAG_INTERPOLATE_SHAPE
VecBase< float, 2 > float2
void DEG_id_tag_update(ID *id, unsigned int flags)
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
float BKE_brush_curve_strength(eBrushCurvePreset preset, const CurveMapping *cumap, float distance, float brush_radius)
Definition brush.cc:1691
const Brush * BKE_paint_brush_for_read(const Paint *paint)
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)
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
VecBase< float, 3 > float3
Mesh * BKE_object_get_evaluated_mesh(const Object *object_eval)
Definition object.cc:4436
eBrushCurvesSculptDensityMode
@ BRUSH_CURVES_SCULPT_DENSITY_MODE_ADD
@ BRUSH_CURVES_SCULPT_DENSITY_MODE_REMOVE
eBrushFalloffShape falloff_shape
struct BrushCurvesSculptSettings * curves_sculpt_settings
struct ToolSettings * toolsettings
CurvesSculpt * curves_sculpt
eUserpref_UI_Flag uiflag
void sample_projected_with_symmetry(RandomNumberGenerator &rng, Vector< float2 > &r_uvs, Vector< float3 > &r_positions_su)
void sample_spherical_with_symmetry(RandomNumberGenerator &rng, Vector< float2 > &r_uvs, Vector< float3 > &r_positions_su)
void execute(DensityAddOperation &self, const StrokeExtension &stroke_extension)
void reduce_density_spherical_with_symmetry(MutableSpan< bool > curves_to_keep)
std::unique_ptr< KDTreeNew< float3 > > root_points_kdtree_
void execute(DensitySubtractOperation &self, const StrokeExtension &stroke_extension)
void reduce_density_spherical(const float3 &brush_pos_cu, const float brush_radius_cu, MutableSpan< bool > curves_to_keep)
void reduce_density_projected_with_symmetry(MutableSpan< bool > curves_to_keep)
void reduce_density_projected(const float4x4 &brush_transform, MutableSpan< bool > curves_to_keep)