Blender V5.3
node_geo_sample_nearest_surface.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 "BKE_bvh.hh"
6#include "BKE_mesh.hh"
7#include "BKE_mesh_sample.hh"
8
9#include "NOD_rna_define.hh"
11
13#include "UI_resources.hh"
14
15#include "RNA_enum_types.hh"
16
17#include "BLI_task.hh"
18
19#include "node_geometry_util.hh"
20
22
24
26{
27 const bNode *node = b.node_or_null();
28
29 b.add_input<decl::Geometry>("Mesh"_ustr)
30 .supported_type(GeometryComponent::Type::Mesh)
31 .description("Mesh to find the closest surface point on");
32 if (node != nullptr) {
33 const eCustomDataType data_type = eCustomDataType(node->custom1);
34 b.add_input(data_type, "Value"_ustr).hide_value().evaluated_geometry_field();
35 }
36 b.add_input<decl::Int>("Group ID"_ustr)
37 .hide_value()
38 .evaluated_geometry_field()
40 "Splits the faces of the input mesh into groups which can be sampled individually");
41 auto &sample_position = b.add_input<decl::Vector>("Sample Position"_ustr)
42 .default_input_type(NODE_DEFAULT_INPUT_POSITION_FIELD)
43 .structure_type(StructureType::Dynamic);
44 auto &sample_group_id = b.add_input<decl::Int>("Sample Group ID"_ustr)
45 .hide_value()
46 .structure_type(StructureType::Dynamic);
47
48 std::array<int, 2> dynamic_inputs = {sample_position.index(), sample_group_id.index()};
49 if (node != nullptr) {
50 const eCustomDataType data_type = eCustomDataType(node->custom1);
51 b.add_output(data_type, "Value"_ustr)
52 .inferred_structure_type(dynamic_inputs)
53 .propagate_references(dynamic_inputs);
54 }
55 b.add_output<decl::Bool>("Is Valid"_ustr)
56 .inferred_structure_type(dynamic_inputs)
57 .propagate_references(dynamic_inputs)
59 "Whether the sampling was successful. It can fail when the sampled group is empty");
60}
61
62static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
63{
64 layout.prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
65}
66
67static void node_init(bNodeTree * /*tree*/, bNode *node)
68{
69 node->custom1 = CD_PROP_FLOAT;
70}
71
73{
74 const NodeDeclaration &declaration = *params.node_type().static_declaration;
75 search_link_ops_for_declarations(params, declaration.inputs);
76
77 const std::optional<eCustomDataType> type = bke::socket_type_to_custom_data_type(
78 params.other_socket().type);
79 if (type && *type != CD_PROP_STRING) {
80 /* The input and output sockets have the same name. */
81 params.add_item(IFACE_("Value"), [type](LinkSearchOpParams &params) {
82 bNode &node = params.add_node("GeometryNodeSampleNearestSurface"_ustr);
83 node.custom1 = *type;
84 params.update_and_connect_available_socket(node, "Value"_ustr);
85 });
86 }
87}
88
89class SampleNearestSurfaceFunction : public mf::MultiFunction {
90 private:
91 GeometrySet source_;
92 Field<int> group_id_field_;
93
94 mutable CacheMutex mutex_;
95 mutable const bke::bvh::Tree *single_tree_ = nullptr;
96 mutable Array<bke::bvh::Tree> bvh_trees_;
97 mutable VectorSet<int> group_indices_;
98
99 public:
101 : source_(std::move(geometry)), group_id_field_(std::move(group_id_field))
102 {
103 source_.ensure_owns_direct_data();
104 static const mf::Signature signature = []() {
105 mf::Signature signature;
106 mf::SignatureBuilder builder{"Sample Nearest Surface", signature};
107 builder.single_input<float3>("Position");
108 builder.single_input<int>("Sample ID");
109 builder.single_output<int>("Triangle Index");
110 builder.single_output<float3>("Barycentric Weight");
111 builder.single_output<bool>("Is Valid", mf::ParamFlag::SupportsUnusedOutput);
112 return signature;
113 }();
114 this->set_signature(&signature);
115 }
116
117 void prepare_for_execution() const override
118 {
119 mutex_.ensure([&]() {
120 const Mesh &mesh = *source_.get_mesh();
121
122 /* Compute group ids on mesh. */
124 FieldEvaluator field_evaluator{field_context, mesh.faces_num};
125 field_evaluator.add(group_id_field_);
126 field_evaluator.evaluate();
127 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
128
129 /* Compute index masks for groups. */
130 IndexMaskMemory memory;
131 const Vector<IndexMask> group_masks = IndexMask::from_group_ids(group_ids, memory);
132 const int groups_num = group_masks.size();
133 group_indices_.reserve(groups_num);
134 for (const IndexMask &group_mask : group_masks) {
135 group_indices_.add_new(group_ids[group_mask.first()]);
136 }
137
138 if (groups_num == 1) {
139 single_tree_ = &mesh.bvh_tris();
140 }
141 else {
142 bvh_trees_.reinitialize(groups_num);
144 IndexRange(groups_num),
145 512,
146 [&](const IndexRange range) {
147 for (const int group_i : range) {
148 const IndexMask &group_mask = group_masks[group_i];
149 bvh_trees_[group_i] = bke::bvh::Tree::from_tris(mesh, group_mask, true);
150 }
151 },
153 [&](const int group_i) { return group_masks[group_i].size(); }, mesh.faces_num));
154 }
155 });
156 }
157
158 ~SampleNearestSurfaceFunction() override = default;
159
160 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
161 {
162 const VArray<float3> &positions = params.readonly_single_input<float3>(0, "Position");
163 const VArray<int> &sample_ids = params.readonly_single_input<int>(1, "Sample ID");
164 MutableSpan<int> triangle_index = params.uninitialized_single_output<int>(2, "Triangle Index");
165 MutableSpan<float3> bary_weights = params.uninitialized_single_output<float3>(
166 3, "Barycentric Weight");
167 MutableSpan<bool> is_valid_span = params.uninitialized_single_output_if_required<bool>(
168 4, "Is Valid");
169
170 mask.foreach_index([&](const int i) {
171 const float3 position = positions[i];
172 const int sample_id = sample_ids[i];
173 const int group_index = group_indices_.index_of_try(sample_id);
174 if (group_index == -1) {
175 triangle_index[i] = -1;
176 bary_weights[i] = float3(0, 0, 0);
177 if (!is_valid_span.is_empty()) {
178 is_valid_span[i] = false;
179 }
180 return;
181 }
182 const bke::bvh::Tree &bvh = single_tree_ ? *single_tree_ : bvh_trees_[group_index];
183 const std::optional<bke::bvh::ClosestPointResult> result = bvh.closest_point(position);
184 if (!result) {
185 triangle_index[i] = -1;
186 bary_weights[i] = float3(0, 0, 0);
187 if (!is_valid_span.is_empty()) {
188 is_valid_span[i] = false;
189 }
190 return;
191 }
192 triangle_index[i] = result->index;
193 bary_weights[i] = result->bary_coord;
194 if (!is_valid_span.is_empty()) {
195 is_valid_span[i] = true;
196 }
197 });
198 }
199
201 {
202 ExecutionHints hints;
203 hints.min_grain_size = 512;
204 return hints;
205 }
206
207 void hash_unique(UniqueHashBytes &hash) const override
208 {
209 static constexpr int8_t id = 0;
210 hash.add(&id);
211 hash.add(source_.get_mesh());
212 fn::FieldHashDeep field_hash;
213 hash.add(field_hash.ensure(group_id_field_));
214 }
215};
216
218{
219 GeometrySet geometry = params.extract_input<GeometrySet>("Mesh"_ustr);
220 const Mesh *mesh = geometry.get_mesh();
221 if (mesh == nullptr) {
223 return;
224 }
225 if (mesh->verts_num == 0) {
227 return;
228 }
229 if (mesh->faces_num == 0) {
230 params.error_message_add(NodeWarningType::Error, TIP_("The source mesh must have faces"));
232 return;
233 }
234
235 GField value = params.extract_input<GField>("Value"_ustr);
236 Field<int> group_id_field = params.extract_input<Field<int>>("Group ID"_ustr);
237 auto sample_position = params.extract_input<bke::SocketValueVariant>("Sample Position"_ustr);
238 auto sample_group_id = params.extract_input<bke::SocketValueVariant>("Sample Group ID"_ustr);
239
240 std::string error_message;
241
242 bke::SocketValueVariant triangle_index;
243 bke::SocketValueVariant bary_weights;
246 std::make_shared<SampleNearestSurfaceFunction>(geometry, group_id_field),
247 {&sample_position, &sample_group_id},
248 {&triangle_index, &bary_weights, &is_valid},
249 params.user_data(),
250 error_message))
251 {
253 params.error_message_add(NodeWarningType::Error, std::move(error_message));
254 return;
255 }
256
257 bke::SocketValueVariant sample_value;
259 std::make_shared<bke::mesh_surface_sample::BaryWeightSampleFn>(geometry,
260 std::move(value)),
261 {&triangle_index, &bary_weights},
262 {&sample_value},
263 params.user_data(),
264 error_message))
265 {
267 params.error_message_add(NodeWarningType::Error, std::move(error_message));
268 return;
269 }
270
271 params.set_output("Value"_ustr, std::move(sample_value));
272 params.set_output("Is Valid"_ustr, std::move(is_valid));
273}
274
275static void node_rna(StructRNA *srna)
276{
278 "data_type",
279 "Data Type",
280 "",
285}
286
287static void node_register()
288{
289 static bke::bNodeType ntype;
290
292 &ntype, "GeometryNodeSampleNearestSurface"_ustr, GEO_NODE_SAMPLE_NEAREST_SURFACE);
293 ntype.ui_name = "Sample Nearest Surface";
294 ntype.ui_description =
295 "Calculate the interpolated value of a mesh attribute on the closest point of its surface";
296 ntype.enum_name_legacy = "SAMPLE_NEAREST_SURFACE";
298 ntype.initfunc = node_init;
299 ntype.declare = node_declare;
305
306 node_rna(ntype.rna_ext.srna);
307}
309
310} // namespace blender::nodes::node_geo_sample_nearest_surface_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_SAMPLE_NEAREST_SURFACE
#define TIP_(msgid)
#define IFACE_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
static Vector< IndexMask, 4 > from_group_ids(const VArray< int > &group_ids, LinearAllocator<> &memory)
constexpr IndexRange()=default
int64_t size() const
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)
const bke::bNodeType & node_type() const
void add_item(std::string socket_name, SocketLinkOperation::LinkSocketFn fn, int weight=0)
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)
void update_and_connect_available_socket(bNode &new_node, UString socket_name)
Vector< SocketDeclaration * > inputs
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
#define position
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
std::optional< eCustomDataType > socket_type_to_custom_data_type(eNodeSocketDatatype type)
Definition node.cc:5911
const EnumPropertyItem * attribute_type_type_with_socket_fn(bContext *, PointerRNA *, PropertyRNA *, bool *r_free)
static void node_gather_link_searches(GatherLinkSearchOpParams &params)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
void search_link_ops_for_declarations(GatherLinkSearchOpParams &params, Span< SocketDeclaration * > declarations)
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)
const EnumPropertyItem rna_enum_attribute_type_items[]
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
eNodeSocketDatatype type
static constexpr int _160
Definition BKE_node.hh:246
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
NodeGatherSocketLinkOperationsFunction gather_link_search_ops
Definition BKE_node.hh:409
NodeDeclareFunction declare
Definition BKE_node.hh:393
nodes::NodeDeclaration * static_declaration
Definition BKE_node.hh:402
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)