Blender V4.5
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_bvhutils.hh"
6#include "BKE_mesh.hh"
7#include "BKE_mesh_sample.hh"
8
9#include "NOD_rna_define.hh"
11
12#include "UI_interface.hh"
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").supported_type(GeometryComponent::Type::Mesh);
30 if (node != nullptr) {
31 const eCustomDataType data_type = eCustomDataType(node->custom1);
32 b.add_input(data_type, "Value").hide_value().field_on_all();
33 }
34 b.add_input<decl::Int>("Group ID")
35 .hide_value()
36 .field_on_all()
38 "Splits the faces of the input mesh into groups which can be sampled individually");
39 b.add_input<decl::Vector>("Sample Position").implicit_field(NODE_DEFAULT_INPUT_POSITION_FIELD);
40 b.add_input<decl::Int>("Sample Group ID").hide_value().supports_field();
41
42 if (node != nullptr) {
43 const eCustomDataType data_type = eCustomDataType(node->custom1);
44 b.add_output(data_type, "Value").dependent_field({3, 4});
45 }
46 b.add_output<decl::Bool>("Is Valid")
47 .dependent_field({3, 4})
48 .description(
49 "Whether the sampling was successful. It can fail when the sampled group is empty");
50}
51
52static void node_layout(uiLayout *layout, bContext * /*C*/, PointerRNA *ptr)
53{
54 layout->prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
55}
56
57static void node_init(bNodeTree * /*tree*/, bNode *node)
58{
59 node->custom1 = CD_PROP_FLOAT;
60}
61
63{
64 const NodeDeclaration &declaration = *params.node_type().static_declaration;
66
67 const std::optional<eCustomDataType> type = bke::socket_type_to_custom_data_type(
68 eNodeSocketDatatype(params.other_socket().type));
69 if (type && *type != CD_PROP_STRING) {
70 /* The input and output sockets have the same name. */
71 params.add_item(IFACE_("Value"), [type](LinkSearchOpParams &params) {
72 bNode &node = params.add_node("GeometryNodeSampleNearestSurface");
73 node.custom1 = *type;
74 params.update_and_connect_available_socket(node, "Value");
75 });
76 }
77}
78
79class SampleNearestSurfaceFunction : public mf::MultiFunction {
80 private:
81 GeometrySet source_;
83 VectorSet<int> group_indices_;
84
85 public:
87 : source_(std::move(geometry))
88 {
89 source_.ensure_owns_direct_data();
90 static const mf::Signature signature = []() {
91 mf::Signature signature;
92 mf::SignatureBuilder builder{"Sample Nearest Surface", signature};
93 builder.single_input<float3>("Position");
94 builder.single_input<int>("Sample ID");
95 builder.single_output<int>("Triangle Index");
96 builder.single_output<float3>("Sample Position");
97 builder.single_output<bool>("Is Valid", mf::ParamFlag::SupportsUnusedOutput);
98 return signature;
99 }();
100 this->set_signature(&signature);
101
102 const Mesh &mesh = *source_.get_mesh();
103
104 /* Compute group ids on mesh. */
106 FieldEvaluator field_evaluator{field_context, mesh.faces_num};
107 field_evaluator.add(group_id_field);
108 field_evaluator.evaluate();
109 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
110
111 /* Compute index masks for groups. */
112 IndexMaskMemory memory;
114 group_ids, memory, group_indices_);
115 const int groups_num = group_masks.size();
116
117 /* Construct BVH tree for each group. */
118 bvh_trees_.reinitialize(groups_num);
120 IndexRange(groups_num),
121 512,
122 [&](const IndexRange range) {
123 for (const int group_i : range) {
124 const IndexMask &group_mask = group_masks[group_i];
125 bvh_trees_[group_i] = bke::bvhtree_from_mesh_tris_init(mesh, group_mask);
126 }
127 },
129 [&](const int group_i) { return group_masks[group_i].size(); }, mesh.faces_num));
130 }
131
132 ~SampleNearestSurfaceFunction() override = default;
133
134 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
135 {
136 const VArray<float3> &positions = params.readonly_single_input<float3>(0, "Position");
137 const VArray<int> &sample_ids = params.readonly_single_input<int>(1, "Sample ID");
138 MutableSpan<int> triangle_index = params.uninitialized_single_output<int>(2, "Triangle Index");
139 MutableSpan<float3> sample_position = params.uninitialized_single_output<float3>(
140 3, "Sample Position");
141 MutableSpan<bool> is_valid_span = params.uninitialized_single_output_if_required<bool>(
142 4, "Is Valid");
143
144 mask.foreach_index([&](const int i) {
145 const float3 position = positions[i];
146 const int sample_id = sample_ids[i];
147 const int group_index = group_indices_.index_of_try(sample_id);
148 if (group_index == -1) {
149 triangle_index[i] = -1;
150 sample_position[i] = float3(0, 0, 0);
151 if (!is_valid_span.is_empty()) {
152 is_valid_span[i] = false;
153 }
154 return;
155 }
156 const bke::BVHTreeFromMesh &bvh = bvh_trees_[group_index];
157 BVHTreeNearest nearest;
158 nearest.dist_sq = FLT_MAX;
159 nearest.index = -1;
161 position,
162 &nearest,
164 const_cast<bke::BVHTreeFromMesh *>(&bvh));
165 triangle_index[i] = nearest.index;
166 sample_position[i] = nearest.co;
167 if (!is_valid_span.is_empty()) {
168 is_valid_span[i] = true;
169 }
170 });
171 }
172
174 {
175 ExecutionHints hints;
176 hints.min_grain_size = 512;
177 return hints;
178 }
179};
180
182{
183 GeometrySet geometry = params.extract_input<GeometrySet>("Mesh");
184 const Mesh *mesh = geometry.get_mesh();
185 if (mesh == nullptr) {
186 params.set_default_remaining_outputs();
187 return;
188 }
189 if (mesh->verts_num == 0) {
190 params.set_default_remaining_outputs();
191 return;
192 }
193 if (mesh->faces_num == 0) {
194 params.error_message_add(NodeWarningType::Error, TIP_("The source mesh must have faces"));
195 params.set_default_remaining_outputs();
196 return;
197 }
198
199 auto nearest_op = FieldOperation::Create(
200 std::make_shared<SampleNearestSurfaceFunction>(geometry,
201 params.extract_input<Field<int>>("Group ID")),
202 {params.extract_input<Field<float3>>("Sample Position"),
203 params.extract_input<Field<int>>("Sample Group ID")});
204 Field<int> triangle_indices(nearest_op, 0);
205 Field<float3> nearest_positions(nearest_op, 1);
206 Field<bool> is_valid(nearest_op, 2);
207
209 std::make_shared<bke::mesh_surface_sample::BaryWeightFromPositionFn>(geometry),
210 {nearest_positions, triangle_indices}));
211
212 GField field = params.extract_input<GField>("Value");
213 auto sample_op = FieldOperation::Create(
214 std::make_shared<bke::mesh_surface_sample::BaryWeightSampleFn>(geometry, std::move(field)),
215 {triangle_indices, bary_weights});
216
217 params.set_output("Value", GField(sample_op));
218 params.set_output("Is Valid", is_valid);
219}
220
221static void node_rna(StructRNA *srna)
222{
224 "data_type",
225 "Data Type",
226 "",
231}
232
233static void node_register()
234{
235 static blender::bke::bNodeType ntype;
236
237 geo_node_type_base(&ntype, "GeometryNodeSampleNearestSurface", GEO_NODE_SAMPLE_NEAREST_SURFACE);
238 ntype.ui_name = "Sample Nearest Surface";
239 ntype.ui_description =
240 "Calculate the interpolated value of a mesh attribute on the closest point of its surface";
241 ntype.enum_name_legacy = "SAMPLE_NEAREST_SURFACE";
243 ntype.initfunc = node_init;
244 ntype.declare = node_declare;
250
251 node_rna(ntype.rna_ext.srna);
252}
254
255} // namespace blender::nodes::node_geo_sample_nearest_surface_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:447
#define GEO_NODE_SAMPLE_NEAREST_SURFACE
int BLI_bvhtree_find_nearest(const BVHTree *tree, const float co[3], BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
#define TIP_(msgid)
#define IFACE_(msgid)
@ CD_PROP_FLOAT
@ CD_PROP_STRING
@ NODE_DEFAULT_INPUT_POSITION_FIELD
eNodeSocketDatatype
#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, IndexMaskMemory &memory, VectorSet< int > &r_index_by_group_id)
int64_t size() const
int add(GField field, GVArray *varray_ptr)
Definition field.cc:751
const GVArray & get_evaluated(const int field_index) const
Definition FN_field.hh:448
void set_signature(const Signature *signature)
static std::shared_ptr< FieldOperation > Create(std::shared_ptr< const mf::MultiFunction > function, Vector< GField > inputs={})
Definition FN_field.hh:242
Vector< SocketDeclaration * > inputs
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
void node_register_type(bNodeType &ntype)
Definition node.cc:2748
BVHTreeFromMesh bvhtree_from_mesh_tris_init(const Mesh &mesh, const IndexMask &faces_mask)
Definition bvhutils.cc:784
std::optional< eCustomDataType > socket_type_to_custom_data_type(eNodeSocketDatatype type)
Definition node.cc:5355
void node_type_size_preset(bNodeType &ntype, eNodeSizePreset size)
Definition node.cc:5585
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(uiLayout *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)
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:93
auto individual_task_sizes(Fn &&fn, const std::optional< int64_t > full_size=std::nullopt)
VecBase< float, 3 > float3
void geo_node_type_base(blender::bke::bNodeType *ntype, std::string idname, const std::optional< int16_t > legacy_type)
const EnumPropertyItem rna_enum_attribute_type_items[]
#define FLT_MAX
Definition stdcycles.h:14
StructRNA * srna
Definition RNA_types.hh:909
int16_t custom1
BVHTree_NearestPointCallback nearest_callback
Defines a node type.
Definition BKE_node.hh:226
std::string ui_description
Definition BKE_node.hh:232
void(* initfunc)(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:277
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:347
const char * enum_name_legacy
Definition BKE_node.hh:235
void(* draw_buttons)(uiLayout *, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:247
NodeGatherSocketLinkOperationsFunction gather_link_search_ops
Definition BKE_node.hh:371
NodeDeclareFunction declare
Definition BKE_node.hh:355
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< blender::StringRef > name_opt, int icon, std::optional< blender::StringRef > placeholder=std::nullopt)
i
Definition text_draw.cc:230
PointerRNA * ptr
Definition wm_files.cc:4226