Blender V5.3
node_geo_proximity.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 "BLI_math_vector.hh"
6#include "BLI_task.hh"
7
8#include "BKE_bvh.hh"
9#include "BKE_geometry_set.hh"
10#include "BKE_mesh.hh"
11#include "BKE_pointcloud.hh"
12
14
15#include "NOD_rna_define.hh"
16
18#include "UI_resources.hh"
19
20#include "node_geometry_util.hh"
21
23
25
27{
28 b.add_input<decl::Geometry>("Geometry"_ustr, "Target"_ustr)
31 .description("Geometry to find the closest point on");
32 b.add_input<decl::Int>("Group ID"_ustr)
33 .hide_value()
34 .evaluated_geometry_field()
35 .description(
36 "Splits the elements of the input geometry into groups which can be sampled "
37 "individually");
38 auto &sample_position = b.add_input<decl::Vector>("Sample Position"_ustr, "Source Position"_ustr)
40 .structure_type(StructureType::Dynamic);
41 auto &sample_group_id = b.add_input<decl::Int>("Sample Group ID"_ustr)
42 .hide_value()
43 .structure_type(StructureType::Dynamic);
44
45 const std::array<int, 2> dynamic_inputs = {sample_position.index(), sample_group_id.index()};
46 b.add_output<decl::Vector>("Position"_ustr)
47 .inferred_structure_type(dynamic_inputs)
48 .propagate_references(dynamic_inputs);
49 b.add_output<decl::Float>("Distance"_ustr)
50 .inferred_structure_type(dynamic_inputs)
51 .propagate_references(dynamic_inputs);
52 b.add_output<decl::Bool>("Is Valid"_ustr)
53 .inferred_structure_type(dynamic_inputs)
54 .propagate_references(dynamic_inputs)
55 .description(
56 "Whether the sampling was successful. It can fail when the sampled group is empty");
57}
58
59static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
60{
61 layout.prop(ptr, "target_element", UI_ITEM_NONE, "", ICON_NONE);
62}
63
64static void geo_proximity_init(bNodeTree * /*tree*/, bNode *node)
65{
66 NodeGeometryProximity *node_storage = MEM_new<NodeGeometryProximity>(__func__);
68 node->storage = node_storage;
69}
70
71class ProximityFunction : public mf::MultiFunction {
72 private:
74 struct GroupTrees {
81
82 const bke::bvh::Tree *find(const int id) const
83 {
84 const int64_t group = this->ids.index_of_try(id);
85 return group == -1 ? nullptr : this->trees[group];
86 }
87 };
88
89 GeometrySet target_;
90 Field<int> group_id_field_;
92
93 mutable CacheMutex mutex_;
94 mutable GroupTrees mesh_trees_;
95 mutable GroupTrees pointcloud_trees_;
96
97 public:
100 const Field<int> &group_id_field)
101 : target_(std::move(target)), group_id_field_(std::move(group_id_field)), type_(type)
102 {
103 static const mf::Signature signature = []() {
104 mf::Signature signature;
105 mf::SignatureBuilder builder{"Geometry Proximity", signature};
106 builder.single_input<float3>("Source Position");
107 builder.single_input<int>("Sample ID");
108 builder.single_output<float3>("Position", mf::ParamFlag::SupportsUnusedOutput);
109 builder.single_output<float>("Distance", mf::ParamFlag::SupportsUnusedOutput);
110 builder.single_output<bool>("Is Valid", mf::ParamFlag::SupportsUnusedOutput);
111 return signature;
112 }();
113 this->set_signature(&signature);
114 }
115
116 ~ProximityFunction() override = default;
117
122 static void build_group_trees(const VArray<int> &group_ids,
123 const FunctionRef<const bke::bvh::Tree &()> cached_tree,
124 const FunctionRef<bke::bvh::Tree(const IndexMask &)> build_tree,
125 GroupTrees &r_trees)
126 {
127 IndexMaskMemory memory;
128 const Vector<IndexMask> group_masks = IndexMask::from_group_ids(group_ids, memory);
129 const int groups_num = group_masks.size();
130
131 r_trees.ids.reserve(groups_num);
132 for (const IndexMask &group_mask : group_masks) {
133 r_trees.ids.add_new(group_ids[group_mask.first()]);
134 }
135 r_trees.owned_trees.reinitialize(groups_num);
136 r_trees.trees.reinitialize(groups_num);
138 IndexRange(groups_num),
139 512,
140 [&](const IndexRange range) {
141 for (const int group_i : range) {
142 const IndexMask &group_mask = group_masks[group_i];
143 if (group_mask.size() == group_ids.size()) {
144 r_trees.trees[group_i] = &cached_tree();
145 }
146 else {
147 r_trees.owned_trees[group_i] = build_tree(group_mask);
148 r_trees.trees[group_i] = &*r_trees.owned_trees[group_i];
149 }
150 }
151 },
153 [&](const int group_i) { return group_masks[group_i].size(); }, group_ids.size()));
154 }
155
156 void init_for_pointcloud(const PointCloud &pointcloud, const Field<int> &group_id_field) const
157 {
158 bke::PointCloudFieldContext field_context{pointcloud};
159 FieldEvaluator field_evaluator{field_context, pointcloud.totpoint};
160 field_evaluator.add(group_id_field);
161 field_evaluator.evaluate();
162 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
163
165 group_ids,
166 [&]() -> const bke::bvh::Tree & { return pointcloud.bvh_tree(); },
167 [&](const IndexMask &mask) {
168 return bke::bvh::Tree::from_points(pointcloud.positions(), mask);
169 },
170 pointcloud_trees_);
171 }
172
173 void init_for_mesh(const Mesh &mesh, const Field<int> &group_id_field) const
174 {
175 const bke::AttrDomain domain = this->get_domain_on_mesh();
176 const int domain_size = mesh.attributes().domain_size(domain);
177 bke::MeshFieldContext field_context{mesh, domain};
178 FieldEvaluator field_evaluator{field_context, domain_size};
179 field_evaluator.add(group_id_field);
180 field_evaluator.evaluate();
181 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
182
183 switch (type_) {
186 group_ids,
187 [&]() -> const bke::bvh::Tree & { return mesh.bvh_verts(); },
188 [&](const IndexMask &mask) {
189 return bke::bvh::Tree::from_points(mesh.vert_positions(), mask);
190 },
191 mesh_trees_);
192 break;
195 group_ids,
196 [&]() -> const bke::bvh::Tree & { return mesh.bvh_edges(); },
197 [&](const IndexMask &mask) {
198 return bke::bvh::Tree::from_edges(mesh.vert_positions(), mesh.edges(), mask);
199 },
200 mesh_trees_);
201 break;
204 group_ids,
205 [&]() -> const bke::bvh::Tree & { return mesh.bvh_tris(); },
206 [&](const IndexMask &mask) { return bke::bvh::Tree::from_tris(mesh, mask, false); },
207 mesh_trees_);
208 break;
209 }
210 }
211
225
226 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
227 {
228 const VArray<float3> &sample_positions = params.readonly_single_input<float3>(
229 0, "Source Position");
230 const VArray<int> &sample_ids = params.readonly_single_input<int>(1, "Sample ID");
231 MutableSpan<float3> positions = params.uninitialized_single_output_if_required<float3>(
232 2, "Position");
233 MutableSpan<float> distances = params.uninitialized_single_output_if_required<float>(
234 3, "Distance");
235 MutableSpan<bool> is_valid_span = params.uninitialized_single_output_if_required<bool>(
236 4, "Is Valid");
237
238 mask.foreach_index([&](const int i) {
239 const float3 sample_position = sample_positions[i];
240 const int sample_id = sample_ids[i];
241 const bke::bvh::Tree *mesh_bvh = mesh_trees_.find(sample_id);
242 const bke::bvh::Tree *pointcloud_bvh = pointcloud_trees_.find(sample_id);
243 if (!mesh_bvh && !pointcloud_bvh) {
244 if (!positions.is_empty()) {
245 positions[i] = float3(0, 0, 0);
246 }
247 if (!is_valid_span.is_empty()) {
248 is_valid_span[i] = false;
249 }
250 if (!distances.is_empty()) {
251 distances[i] = 0.0f;
252 }
253 return;
254 }
255 /* Take mesh and pointcloud bvh tree into account. The final result is the closer of the two.
256 * The distance from the first query is passed into the second query as a maximum distance,
257 * so that the mesh result is kept when both are the same distance away. */
258 float3 nearest_position(0.0f);
259 float nearest_distance = FLT_MAX;
260 if (mesh_bvh) {
261 if (const std::optional<bke::bvh::ClosestPointResult> result = mesh_bvh->closest_point(
262 sample_position))
263 {
264 nearest_position = result->position;
265 nearest_distance = math::distance(sample_position, result->position);
266 }
267 }
268 if (pointcloud_bvh) {
269 if (const std::optional<bke::bvh::ClosestPointResult> result =
270 pointcloud_bvh->closest_point(sample_position, nearest_distance))
271 {
272 nearest_position = result->position;
273 nearest_distance = math::distance(sample_position, result->position);
274 }
275 }
276
277 if (!positions.is_empty()) {
278 positions[i] = nearest_position;
279 }
280 if (!is_valid_span.is_empty()) {
281 is_valid_span[i] = true;
282 }
283 if (!distances.is_empty()) {
284 distances[i] = nearest_distance;
285 }
286 });
287 }
288
290 {
291 ExecutionHints hints;
292 hints.min_grain_size = 512;
293 return hints;
294 }
295
296 void hash_unique(UniqueHashBytes &hash) const override
297 {
298 static constexpr int8_t id = 0;
299 hash.add(&id);
300 hash.add(target_.get_mesh());
301 hash.add(target_.get_pointcloud());
302 hash.add(type_);
303 fn::FieldHashDeep field_hash;
304 hash.add(field_hash.ensure(group_id_field_));
305 }
306
307 void prepare_for_execution() const override
308 {
309 mutex_.ensure([&]() {
310 if (target_.has_pointcloud() && type_ == GEO_NODE_PROX_TARGET_POINTS) {
311 const PointCloud &pointcloud = *target_.get_pointcloud();
312 this->init_for_pointcloud(pointcloud, group_id_field_);
313 }
314 if (target_.has_mesh()) {
315 const Mesh &mesh = *target_.get_mesh();
316 this->init_for_mesh(mesh, group_id_field_);
317 }
318 });
319 }
320};
321
323{
324 GeometrySet target = params.extract_input<GeometrySet>("Target"_ustr);
326
327 if (!target.has_mesh() && !target.has_pointcloud()) {
329 return;
330 }
331
332 const NodeGeometryProximity &storage = node_storage(params.node());
333 const auto target_type = GeometryNodeProximityTargetType(storage.target_element);
334
335 Field<int> group_id_field = params.extract_input<Field<int>>("Group ID"_ustr);
336 auto sample_position = params.extract_input<bke::SocketValueVariant>("Source Position"_ustr);
337 auto sample_group_id = params.extract_input<bke::SocketValueVariant>("Sample Group ID"_ustr);
338
339 std::string error_message;
344 std::make_shared<ProximityFunction>(
345 std::move(target), target_type, std::move(group_id_field)),
346 {&sample_position, &sample_group_id},
347 {&position, &distance, &is_valid},
348 params.user_data(),
349 error_message))
350 {
352 params.error_message_add(NodeWarningType::Error, std::move(error_message));
353 return;
354 }
355
356 params.set_output("Position"_ustr, std::move(position));
357 params.set_output("Distance"_ustr, std::move(distance));
358 params.set_output("Is Valid"_ustr, std::move(is_valid));
359}
360
361static void node_rna(StructRNA *srna)
362{
363 static const EnumPropertyItem target_element_items[] = {
365 "POINTS",
366 ICON_NONE,
367 "Points",
368 "Calculate the proximity to the target's points (faster than the other modes)"},
370 "EDGES",
371 ICON_NONE,
372 "Edges",
373 "Calculate the proximity to the target's edges"},
375 "FACES",
376 ICON_NONE,
377 "Faces",
378 "Calculate the proximity to the target's faces"},
379 {0, nullptr, 0, nullptr, nullptr},
380 };
381
383 "target_element",
384 "Target Geometry",
385 "Element of the target geometry to calculate the distance from",
386 target_element_items,
387 NOD_storage_enum_accessors(target_element),
389}
390
391static void node_register()
392{
393 static bke::bNodeType ntype;
394
395 geo_node_type_base(&ntype, "GeometryNodeProximity"_ustr, GEO_NODE_PROXIMITY);
396 ntype.ui_name = "Geometry Proximity";
397 ntype.ui_description = "Compute the closest location on the target geometry";
398 ntype.enum_name_legacy = "PROXIMITY";
402 ntype, "NodeGeometryProximity", node_free_standard_storage, node_copy_standard_storage);
403 ntype.declare = node_declare;
407
408 node_rna(ntype.rna_ext.srna);
409}
411
412} // namespace blender::nodes::node_geo_proximity_cc
#define NODE_STORAGE_FUNCS(StorageT)
Definition BKE_node.hh:1353
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_PROXIMITY
General operations for point clouds.
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_storage_enum_accessors(member)
#define UI_ITEM_NONE
#define BLI_assert_unreachable()
static Vector< IndexMask, 4 > from_group_ids(const VArray< int > &group_ids, LinearAllocator<> &memory)
constexpr IndexRange()=default
int64_t index_of_try(const Key &key) const
void reserve(const int64_t n)
void add_new(const Key &key)
int64_t size() const
std::optional< ClosestPointResult > closest_point(const float3 &point, float radius=std::numeric_limits< float >::max()) const
Definition bvh.cc:709
static Tree from_edges(Span< float3 > positions, Span< int2 > edges, const IndexMask &mask)
Definition bvh.cc:415
static Tree from_points(Span< float3 > positions, const IndexMask &mask)
Definition bvh.cc:391
static Tree from_tris(const Mesh &mesh, const IndexMask &mask, bool map_global_indices)
Definition bvh.cc:325
int add(GField field, GVArray *varray_ptr)
const GVArray & get_evaluated(const int field_index) const
void set_signature(const Signature *signature)
void error_message_add(const NodeWarningType type, StringRef message) const
T extract_input(const UString identifier)
GeoNodesUserData * user_data() const
void set_output(const UString identifier, T &&value)
static void build_group_trees(const VArray< int > &group_ids, const FunctionRef< const bke::bvh::Tree &()> cached_tree, const FunctionRef< bke::bvh::Tree(const IndexMask &)> build_tree, GroupTrees &r_trees)
void hash_unique(UniqueHashBytes &hash) const override
ProximityFunction(GeometrySet target, GeometryNodeProximityTargetType type, const Field< int > &group_id_field)
void init_for_pointcloud(const PointCloud &pointcloud, const Field< int > &group_id_field) const
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
void init_for_mesh(const Mesh &mesh, const Field< int > &group_id_field) const
#define FLT_MAX
#define storage(slot, qualifiers)
#define position
float distance(float, float) RET
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
void node_type_storage(bNodeType &ntype, std::optional< StringRefNull > storagename, void(*freefunc)(bNode *node), void(*copyfunc)(bNodeTree *dest_ntree, bNode *dest_node, const bNode *src_node))
Definition node.cc:6166
T distance(const T &a, const T &b)
static void node_geo_exec(GeoNodeExecParams params)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static void node_declare(NodeDeclarationBuilder &b)
static void node_rna(StructRNA *srna)
static void geo_proximity_init(bNodeTree *, bNode *node)
PropertyRNA * RNA_def_node_enum(StructRNA *srna, const char *identifier, const char *ui_name, const char *ui_description, const EnumPropertyItem *static_items, const EnumRNAAccessors accessors, std::optional< int > default_value, const EnumPropertyItemFunc item_func, const bool allow_animation)
bool execute_multi_function_on_value_variant(const MultiFunction &fn, const std::shared_ptr< MultiFunction > &owned_fn, const Span< SocketValueVariant * > input_values, const Span< SocketValueVariant * > output_values, GeoNodesUserData *user_data, std::string &r_error_message)
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 individual_task_sizes(Fn &&fn, const std::optional< int64_t > full_size=std::nullopt)
GeometryNodeProximityTargetType
@ GEO_NODE_PROX_TARGET_EDGES
@ GEO_NODE_PROX_TARGET_FACES
@ GEO_NODE_PROX_TARGET_POINTS
__int64 int64_t
Definition BKE_text.h:90
void node_copy_standard_storage(bNodeTree *, bNode *dest_node, const bNode *src_node)
Definition node_util.cc:57
void node_free_standard_storage(bNode *node)
Definition node_util.cc:45
VecBase< float, 3 > float3
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
signed char int8_t
Definition BKE_text.h:76
#define hash
Definition noise_c.cc:156
GeometryNodeProximityTargetType target_element
Defines a node type.
Definition BKE_node.hh:265
void(*) draw_buttons(ui::Layout &, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:290
std::string ui_description
Definition BKE_node.hh:271
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:385
void(*) initfunc(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:320
const char * enum_name_legacy
Definition BKE_node.hh:274
NodeDeclareFunction declare
Definition BKE_node.hh:393
UniqueHash ensure(const GFieldRef &field)
Definition field.cc:113
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< StringRef > name_opt, int icon, std::optional< StringRef > placeholder=std::nullopt)