Blender V5.3
sculpt_add.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 <algorithm>
6
7#include "sculpt_intern.hh"
8
9#include "BLI_array_utils.hh"
10#include "BLI_bounds.hh"
11#include "BLI_kdtree_new.hh"
12#include "BLI_math_geom_c.hh"
13#include "BLI_math_matrix.hh"
14#include "BLI_rand.hh"
15#include "BLI_vector.hh"
16
17#include "DEG_depsgraph.hh"
18
19#include "BKE_brush.hh"
20#include "BKE_bvhutils.hh"
21#include "BKE_context.hh"
22#include "BKE_curves.hh"
23#include "BKE_geometry_set.hh"
24#include "BKE_mesh.hh"
25#include "BKE_mesh_runtime.hh"
26#include "BKE_mesh_sample.hh"
27#include "BKE_modifier.hh"
28#include "BKE_object.hh"
29#include "BKE_paint.hh"
30
31#include "DNA_brush_enums.h"
32#include "DNA_brush_types.h"
33#include "DNA_curves_types.h"
34#include "DNA_object_types.h"
35#include "DNA_screen_types.h"
36
37#include "ED_screen.hh"
38#include "ED_view3d.hh"
39
41
42#include "WM_api.hh"
43
45
53
55
56using bke::CurvesGeometry;
57
59 private:
61 std::unique_ptr<KDTreeNew<float3>> curve_roots_kdtree_;
63 Array<float3> curve_root_positions_;
64
65 friend struct AddOperationExecutor;
66
67 public:
68 void on_stroke_extended(const PaintStroke &stroke,
69 const StrokeExtension &stroke_extension) override;
70};
71
77 AddOperation *self_ = nullptr;
79
83
85 Mesh *surface_eval_ = nullptr;
91
93 const Brush *brush_ = nullptr;
97
100
102
103 AddOperationExecutor(const PaintStroke &stroke) : ctx_(stroke) {}
104
105 void execute(AddOperation &self, const StrokeExtension &stroke_extension)
106 {
107 self_ = &self;
109
110 curves_id_orig_ = id_cast<Curves *>(curves_ob_orig_->data);
111 curves_orig_ = &curves_id_orig_->geometry.wrap();
112
113 if (curves_id_orig_->surface == nullptr || curves_id_orig_->surface->type != OB_MESH) {
114 report_missing_surface(stroke_extension.reports);
115 return;
116 }
117
119
120 Object &surface_ob_orig = *curves_id_orig_->surface;
121 const Mesh &surface_orig = *id_cast<const Mesh *>(surface_ob_orig.data);
122 if (surface_orig.faces_num == 0) {
123 report_empty_original_surface(stroke_extension.reports);
124 return;
125 }
126
128 if (surface_ob_eval_ == nullptr) {
129 return;
130 }
132 if (surface_eval_->faces_num == 0) {
133 report_empty_evaluated_surface(stroke_extension.reports);
134 return;
135 }
136 surface_positions_eval_ = surface_eval_->vert_positions();
139 surface_bvh_eval_ = &surface_eval_->bvh_tris();
140
145 brush_pos_re_ = stroke_extension.mouse_position;
146
149 add_amount_ = std::max(0, brush_settings_->add_amount);
150
151 if (add_amount_ == 0) {
152 return;
153 }
154
155 /* Find UV map. */
156 VArraySpan<float2> surface_uv_map;
157 if (curves_id_orig_->surface_uv_map != nullptr) {
158 surface_uv_map = *surface_orig.attributes().lookup<float2>(curves_id_orig_->surface_uv_map,
160 surface_uv_map_eval_ = *surface_eval_->attributes().lookup<float2>(
162 }
163
164 if (surface_uv_map.is_empty()) {
166 return;
167 }
170 return;
171 }
172
174
175 /* Sample points on the surface using one of multiple strategies. */
176 Vector<float2> sampled_uvs;
177 if (add_amount_ == 1) {
178 this->sample_in_center_with_symmetry(sampled_uvs);
179 }
180 else if (falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
181 this->sample_projected_with_symmetry(rng, sampled_uvs);
182 }
183 else if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
184 this->sample_spherical_with_symmetry(rng, sampled_uvs);
185 }
186 else {
188 }
189
190 if (sampled_uvs.is_empty()) {
191 /* No new points have been added. */
192 return;
193 }
194
195 const Span<int3> surface_corner_tris_orig = surface_orig.corner_tris();
196 const Span<float3> corner_normals_su = surface_orig.corner_normals();
197 const geometry::ReverseUVSampler reverse_uv_sampler{surface_uv_map, surface_corner_tris_orig};
198
200 add_inputs.uvs = sampled_uvs;
209 add_inputs.interpolate_resolution = curves_orig_->attributes().contains("resolution");
212 add_inputs.fallback_point_count = std::max(2, brush_settings_->points_per_curve);
213 add_inputs.transforms = &transforms_;
214 add_inputs.surface_corner_tris = surface_corner_tris_orig;
215 add_inputs.reverse_uv_sampler = &reverse_uv_sampler;
216 add_inputs.surface = &surface_orig;
217 add_inputs.corner_normals_su = corner_normals_su;
218
219 if (add_inputs.interpolate_length || add_inputs.interpolate_radius ||
220 add_inputs.interpolate_shape || add_inputs.interpolate_point_count ||
221 add_inputs.interpolate_resolution)
222 {
224 add_inputs.old_roots_kdtree = self_->curve_roots_kdtree_.get();
225 }
226
228 *curves_orig_, add_inputs);
230 if (bke::GSpanAttributeWriter selection = attributes.lookup_for_write_span(".selection")) {
231 curves::fill_selection_true(selection.span.slice(selection.domain == bke::AttrDomain::Point ?
232 add_outputs.new_points_range :
233 add_outputs.new_curves_range));
234 selection.finish();
235 }
236 if (U.uiflag & USER_ORBIT_SELECTION) {
237 if (const std::optional<Bounds<float3>> center_cu = bounds::min_max(
238 curves_orig_->positions().slice(add_outputs.new_points_range)))
239 {
243 }
244 }
245
246 if (add_outputs.uv_error) {
247 report_invalid_uv_map(stroke_extension.reports);
248 }
249
253 }
254
259 {
260 float3 ray_start_wo, ray_end_wo;
262 ctx_.depsgraph, ctx_.region, ctx_.v3d, brush_pos_re_, ray_start_wo, ray_end_wo, true);
263 const float3 ray_start_cu = math::transform_point(transforms_.world_to_curves, ray_start_wo);
264 const float3 ray_end_cu = math::transform_point(transforms_.world_to_curves, ray_end_wo);
265
266 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
268
269 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
270 const float4x4 transform = transforms_.curves_to_surface * brush_transform;
271 this->sample_in_center(r_sampled_uvs,
272 math::transform_point(transform, ray_start_cu),
273 math::transform_point(transform, ray_end_cu));
274 }
275 }
276
277 void sample_in_center(Vector<float2> &r_sampled_uvs,
278 const float3 &ray_start_su,
279 const float3 &ray_end_su)
280 {
281 const float3 ray_direction_su = ray_end_su - ray_start_su;
282 const bke::bvh::Ray ray(ray_start_su, ray_direction_su);
283 const std::optional<bke::bvh::RayHit> ray_hit = surface_bvh_eval_->ray_intersect(ray);
284 if (!ray_hit) {
285 return;
286 }
287 const int tri_index = ray_hit->index;
288 const int3 &tri = surface_corner_tris_eval_[tri_index];
289 const float3 brush_pos_su = ray_hit->position(ray);
292
294 bary_coords, tri, surface_uv_map_eval_);
295 r_sampled_uvs.append(uv);
296 }
297
302 {
303 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
305 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
306 this->sample_projected(rng, r_sampled_uvs, brush_transform);
307 }
308 }
309
311 Vector<float2> &r_sampled_uvs,
312 const float4x4 &brush_transform)
313 {
314 const int old_amount = r_sampled_uvs.size();
315 const int max_iterations = 100;
316 int current_iteration = 0;
317 while (r_sampled_uvs.size() < old_amount + add_amount_) {
318 if (current_iteration++ >= max_iterations) {
319 break;
320 }
321 Vector<float3> bary_coords;
322 Vector<int> tri_indices;
323 Vector<float3> positions_su;
324
325 const int missing_amount = add_amount_ + old_amount - r_sampled_uvs.size();
327 rng,
332 [&](const float2 &pos_re, float3 &r_start_su, float3 &r_end_su) {
333 float3 start_wo, end_wo;
335 ctx_.depsgraph, ctx_.region, ctx_.v3d, pos_re, start_wo, end_wo, true);
336 const float3 start_cu = math::transform_point(transforms_.world_to_curves, start_wo);
337 const float3 start_cu_tx = math::transform_point(brush_transform, start_cu);
339 const float3 end_cu_tx = math::transform_point(brush_transform, end_cu);
340 r_start_su = math::transform_point(transforms_.curves_to_surface, start_cu_tx);
342 },
345 missing_amount,
346 bary_coords,
347 tri_indices,
348 positions_su);
349
350 for (const int i : IndexRange(new_points)) {
352 bary_coords[i], surface_corner_tris_eval_[tri_indices[i]], surface_uv_map_eval_);
353 r_sampled_uvs.append(uv);
354 }
355 }
356 }
357
362 {
363 const std::optional<CurvesBrush3D> brush_3d = sample_curves_surface_3d_brush(
365 *ctx_.region,
366 *ctx_.v3d,
371 if (!brush_3d.has_value()) {
372 return;
373 }
374
375 float3 view_ray_start_wo, view_ray_end_wo;
377 ctx_.region,
378 ctx_.v3d,
380 view_ray_start_wo,
381 view_ray_end_wo,
382 true);
383
385 view_ray_start_wo);
387 view_ray_end_wo);
388
389 const Vector<float4x4> symmetry_brush_transforms = get_symmetry_brush_transforms(
391 for (const float4x4 &brush_transform : symmetry_brush_transforms) {
392 const float4x4 transform = transforms_.curves_to_surface * brush_transform;
393
394 const float3 brush_pos_su = math::transform_point(transform, brush_3d->position_cu);
395 const float3 view_direction_su = math::normalize(
396 math::transform_point(transform, view_ray_end_cu) -
397 math::transform_point(transform, view_ray_start_cu));
398 const float brush_radius_su = transform_brush_radius(
399 transform, brush_3d->position_cu, brush_3d->radius_cu);
400
401 this->sample_spherical(rng, r_sampled_uvs, brush_pos_su, brush_radius_su, view_direction_su);
402 }
403 }
404
406 Vector<float2> &r_sampled_uvs,
407 const float3 &brush_pos_su,
408 const float brush_radius_su,
409 const float3 &view_direction_su)
410 {
411 const float brush_radius_sq_su = pow2f(brush_radius_su);
412
413 /* Find surface triangles within brush radius. */
414 Vector<int> selected_tri_indices;
415 if (use_front_face_) {
416 surface_bvh_eval_->range_query(brush_pos_su, brush_radius_su, [&](const int index) {
421 float3 normal_su;
422 normal_tri_v3(normal_su, v0_su, v1_su, v2_su);
423 if (math::dot(normal_su, view_direction_su) >= 0.0f) {
424 return true;
425 }
426 selected_tri_indices.append(index);
427 return true;
428 });
429 }
430 else {
431 surface_bvh_eval_->range_query(brush_pos_su, brush_radius_su, [&](const int index) {
432 selected_tri_indices.append(index);
433 return true;
434 });
435 }
436
437 /* Density used for sampling points. This does not have to be exact, because the loop below
438 * automatically runs until enough samples have been found. If too many samples are found, some
439 * will be discarded afterwards. */
440 const float brush_plane_area_su = M_PI * brush_radius_sq_su;
441 const float approximate_density_su = add_amount_ / brush_plane_area_su;
442
443 /* Usually one or two iterations should be enough. */
444 const int max_iterations = 5;
445 int current_iteration = 0;
446
447 const int old_amount = r_sampled_uvs.size();
448 while (r_sampled_uvs.size() < old_amount + add_amount_) {
449 if (current_iteration++ >= max_iterations) {
450 break;
451 }
452 Vector<float3> bary_coords;
453 Vector<int> tri_indices;
454 Vector<float3> positions_su;
456 rng,
458 selected_tri_indices,
459 brush_pos_su,
460 brush_radius_su,
461 approximate_density_su,
462 bary_coords,
463 tri_indices,
464 positions_su);
465 for (const int i : IndexRange(new_points)) {
467 bary_coords[i], surface_corner_tris_eval_[tri_indices[i]], surface_uv_map_eval_);
468 r_sampled_uvs.append(uv);
469 }
470 }
471
472 /* Remove samples when there are too many. */
473 while (r_sampled_uvs.size() > old_amount + add_amount_) {
474 const int index_to_remove = rng.get_int32(add_amount_) + old_amount;
475 r_sampled_uvs.remove_and_reorder(index_to_remove);
476 }
477 }
478
480 {
481 if (self_->curve_roots_kdtree_ == nullptr) {
482 const Span<int> offsets = curves_orig_->offsets();
483 const Span<float3> positions = curves_orig_->positions();
484 self_->curve_root_positions_.reinitialize(curves_orig_->curves_num());
485 array_utils::gather(positions,
487 self_->curve_root_positions_.as_mutable_span());
488 self_->curve_roots_kdtree_ = std::make_unique<KDTreeNew<float3>>(
489 self_->curve_root_positions_.as_span());
490 }
491 }
492};
493
495 const StrokeExtension &stroke_extension)
496{
497 AddOperationExecutor executor{stroke};
498 executor.execute(*this, stroke_extension);
499}
500
501std::unique_ptr<CurvesSculptStrokeOperation> new_add_operation()
502{
503 return std::make_unique<AddOperation>();
504}
505
506} // namespace blender::ed::sculpt_paint
Low-level operations for curves.
General operations, lookup, etc. for blender objects.
#define M_PI
Object is a sort of wrapper for general info.
#define NC_GEOM
Definition WM_types.hh:406
#define ND_DATA
Definition WM_types.hh:552
#define BLI_assert_unreachable()
Span< T > as_span() const
Definition BLI_array.hh:254
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
constexpr IndexRange()=default
static RandomNumberGenerator from_random_seed()
Definition rand.cc:288
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)
bool is_empty() const
bool contains(StringRef name) const
AttributeAccessor attributes() const
Span< float3 > positions() const
MutableAttributeAccessor attributes_for_write()
GSpanAttributeWriter lookup_for_write_span(StringRef name)
std::optional< RayHit > ray_intersect(const Ray &ray) const
Definition bvh.cc:439
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 gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
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)
float3 compute_bary_coord_in_triangle(Span< float3 > vert_positions, Span< int > corner_verts, const int3 &corner_tri, const float3 &position)
T sample_corner_attribute_with_bary_coords(const float3 &bary_weights, const int3 &corner_tri, const Span< T > corner_attribute)
std::optional< Bounds< T > > min_max(const std::optional< Bounds< T > > &a, const T &b)
Definition BLI_bounds.hh:56
void fill_selection_true(GMutableSpan selection)
std::unique_ptr< CurvesSculptStrokeOperation > new_add_operation()
void report_invalid_uv_map(ReportList *reports)
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)
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)
T dot(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
void WM_main_add_notifier(uint type, void *reference)
UserDef U
Definition blender.cc:58
@ PAINT_FALLOFF_SHAPE_SPHERE
@ PAINT_FALLOFF_SHAPE_TUBE
float normal_tri_v3(float n[3], const float v1[3], const float v2[3], const float v3[3])
Definition math_geom.cc:45
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
VecBase< int32_t, 3 > int3
void DEG_id_tag_update(ID *id, unsigned int flags)
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
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
eBrushFalloffShape falloff_shape
struct BrushCurvesSculptSettings * curves_sculpt_settings
struct ToolSettings * toolsettings
CurvesSculpt * curves_sculpt
void sample_spherical_with_symmetry(RandomNumberGenerator &rng, Vector< float2 > &r_sampled_uvs)
void sample_in_center_with_symmetry(Vector< float2 > &r_sampled_uvs)
void sample_projected_with_symmetry(RandomNumberGenerator &rng, Vector< float2 > &r_sampled_uvs)
void sample_in_center(Vector< float2 > &r_sampled_uvs, const float3 &ray_start_su, const float3 &ray_end_su)
const BrushCurvesSculptSettings * brush_settings_
Definition sculpt_add.cc:94
AddOperationExecutor(const PaintStroke &stroke)
void sample_spherical(RandomNumberGenerator &rng, Vector< float2 > &r_sampled_uvs, const float3 &brush_pos_su, const float brush_radius_su, const float3 &view_direction_su)
void sample_projected(RandomNumberGenerator &rng, Vector< float2 > &r_sampled_uvs, const float4x4 &brush_transform)
void execute(AddOperation &self, const StrokeExtension &stroke_extension)