Blender V5.3
node_geo_raycast.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 "DNA_mesh_types.h"
6
7#include "BKE_bvh.hh"
8#include "BKE_bvhutils.hh"
10#include "BKE_mesh_sample.hh"
11
12#include "NOD_rna_define.hh"
14
16#include "UI_resources.hh"
17
18#include "RNA_enum_types.hh"
19
21
22#include "node_geometry_util.hh"
23
25
27
29
32 "INTERPOLATED",
33 0,
34 N_("Interpolated"),
35 N_("Interpolate the attribute from the corners of the hit face")},
37 "NEAREST",
38 0,
39 N_("Nearest"),
40 N_("Use the attribute value of the closest mesh element")},
41 {0, nullptr, 0, nullptr, nullptr},
42};
43
45{
46 const bNode *node = b.node_or_null();
47
48 b.add_input<decl::Geometry>("Target Geometry"_ustr)
49 .only_realized_data()
50 .supported_type(GeometryComponent::Type::Mesh)
51 .description("Geometry to cast rays onto");
52 if (node != nullptr) {
53 const eCustomDataType data_type = eCustomDataType(node_storage(*node).data_type);
54 /* TODO: Field interfacing depends on the offset of the next declarations! */
55 b.add_input(data_type, "Attribute"_ustr).hide_value().evaluated_geometry_field();
56 }
57 b.add_input<decl::Menu>("Interpolation"_ustr)
58 .static_items(interpolation_items)
60 .description("Mapping from the target geometry to hit points");
61
62 const int source_position = b.add_input<decl::Vector>("Source Position"_ustr)
63 .default_input_type(NODE_DEFAULT_INPUT_POSITION_FIELD)
64 .structure_type(StructureType::Dynamic)
65 .index();
66 const int ray_direction = b.add_input<decl::Vector>("Ray Direction"_ustr)
67 .default_value({0.0f, 0.0f, -1.0f})
68 .structure_type(StructureType::Dynamic)
69 .index();
70 const int ray_length = b.add_input<decl::Float>("Ray Length"_ustr)
71 .default_value(100.0f)
72 .min(0.0f)
74 .structure_type(StructureType::Dynamic)
75 .index();
76
77 const Vector<int> dynamic_inputs({source_position, ray_direction, ray_length});
78
79 b.add_output<decl::Bool>("Is Hit"_ustr)
80 .inferred_structure_type(dynamic_inputs)
81 .propagate_references(dynamic_inputs);
82 b.add_output<decl::Vector>("Hit Position"_ustr)
83 .inferred_structure_type(dynamic_inputs)
84 .propagate_references(dynamic_inputs);
85 b.add_output<decl::Vector>("Hit Normal"_ustr)
86 .inferred_structure_type(dynamic_inputs)
87 .propagate_references(dynamic_inputs);
88 b.add_output<decl::Float>("Hit Distance"_ustr)
89 .inferred_structure_type(dynamic_inputs)
90 .propagate_references(dynamic_inputs);
91
92 if (node != nullptr) {
93 const eCustomDataType data_type = eCustomDataType(node_storage(*node).data_type);
94 b.add_output(data_type, "Attribute"_ustr)
95 .inferred_structure_type(dynamic_inputs)
96 .propagate_references(dynamic_inputs);
97 }
98}
99
100static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
101{
102 layout.prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
103}
104
105static void node_init(bNodeTree * /*tree*/, bNode *node)
106{
107 NodeGeometryRaycast *data = MEM_new<NodeGeometryRaycast>(__func__);
108 data->data_type = CD_PROP_FLOAT;
109 node->storage = data;
110}
111
113{
114 const NodeDeclaration &declaration = *params.node_type().static_declaration;
115 search_link_ops_for_declarations(params, declaration.inputs);
116 search_link_ops_for_declarations(params, declaration.outputs);
117
118 const std::optional<eCustomDataType> type = bke::socket_type_to_custom_data_type(
119 params.other_socket().type);
120 if (type && *type != CD_PROP_STRING) {
121 /* The input and output sockets have the same name. */
122 params.add_item(IFACE_("Attribute"), [type](LinkSearchOpParams &params) {
123 bNode &node = params.add_node("GeometryNodeRaycast"_ustr);
124 node_storage(node).data_type = *type;
125 params.update_and_connect_available_socket(node, "Attribute"_ustr);
126 });
127 }
128}
129
130static void raycast_to_mesh(const IndexMask &mask,
131 const Mesh &mesh,
132 const VArray<float3> &ray_origins,
133 const VArray<float3> &ray_directions,
134 const VArray<float> &ray_lengths,
135 const MutableSpan<bool> r_hit,
136 const MutableSpan<int> r_hit_indices,
137 const MutableSpan<float3> r_hit_positions,
138 const MutableSpan<float3> r_hit_normals,
139 const MutableSpan<float> r_hit_distances,
140 const MutableSpan<float3> r_bary_weights)
141{
142 const bke::bvh::Tree &tree_data = mesh.bvh_tris();
143 mask.foreach_index([&](const int i) {
144 bke::bvh::Ray ray{};
145 ray.origin = ray_origins[i];
146 ray.direction = ray_directions[i];
147 ray.dist_max = ray_lengths[i];
148
149 if (const std::optional<bke::bvh::RayHit> hit = tree_data.ray_intersect(ray)) {
150 if (!r_hit.is_empty()) {
151 r_hit[i] = true;
152 }
153 if (!r_hit_indices.is_empty()) {
154 /* The caller must be able to handle invalid indices anyway, so don't clamp this value. */
155 r_hit_indices[i] = hit->index;
156 }
157 if (!r_hit_positions.is_empty()) {
158 r_hit_positions[i] = hit->position(ray);
159 }
160 if (!r_hit_normals.is_empty()) {
161 r_hit_normals[i] = math::normalize(hit->normal);
162 }
163 if (!r_hit_distances.is_empty()) {
164 r_hit_distances[i] = hit->distance;
165 }
166 if (!r_bary_weights.is_empty()) {
167 r_bary_weights[i] = hit->bary_coord;
168 }
169 }
170 else {
171 if (!r_hit.is_empty()) {
172 r_hit[i] = false;
173 }
174 if (!r_hit_indices.is_empty()) {
175 r_hit_indices[i] = -1;
176 }
177 if (!r_hit_positions.is_empty()) {
178 r_hit_positions[i] = float3(0.0f, 0.0f, 0.0f);
179 }
180 if (!r_hit_normals.is_empty()) {
181 r_hit_normals[i] = float3(0.0f, 0.0f, 0.0f);
182 }
183 if (!r_hit_distances.is_empty()) {
184 r_hit_distances[i] = ray_lengths[i];
185 }
186 if (!r_bary_weights.is_empty()) {
187 r_bary_weights[i] = float3(0);
188 }
189 }
190 });
191}
192
193class RaycastFunction : public mf::MultiFunction {
194 private:
195 GeometrySet target_;
196
197 public:
198 RaycastFunction(GeometrySet target) : target_(std::move(target))
199 {
200 target_.ensure_owns_direct_data();
201 static const mf::Signature signature = []() {
202 mf::Signature signature;
203 mf::SignatureBuilder builder{"Raycast", signature};
204 builder.single_input<float3>("Source Position");
205 builder.single_input<float3>("Ray Direction");
206 builder.single_input<float>("Ray Length");
207 builder.single_output<bool>("Is Hit", mf::ParamFlag::SupportsUnusedOutput);
208 builder.single_output<float3>("Hit Position", mf::ParamFlag::SupportsUnusedOutput);
209 builder.single_output<float3>("Hit Normal", mf::ParamFlag::SupportsUnusedOutput);
210 builder.single_output<float>("Distance", mf::ParamFlag::SupportsUnusedOutput);
211 builder.single_output<int>("Triangle Index", mf::ParamFlag::SupportsUnusedOutput);
212 builder.single_output<float3>("Barycentric Weight", mf::ParamFlag::SupportsUnusedOutput);
213 return signature;
214 }();
215 this->set_signature(&signature);
216 }
217
218 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
219 {
220 BLI_assert(target_.has_mesh());
221 const Mesh &mesh = *target_.get_mesh();
222
224 mask,
225 mesh,
226 params.readonly_single_input<float3>(0, "Source Position"),
227 params.readonly_single_input<float3>(1, "Ray Direction"),
228 params.readonly_single_input<float>(2, "Ray Length"),
229 params.uninitialized_single_output_if_required<bool>(3, "Is Hit"),
230 params.uninitialized_single_output_if_required<int>(7, "Triangle Index"),
231 params.uninitialized_single_output_if_required<float3>(4, "Hit Position"),
232 params.uninitialized_single_output_if_required<float3>(5, "Hit Normal"),
233 params.uninitialized_single_output_if_required<float>(6, "Distance"),
234 params.uninitialized_single_output_if_required<float3>(8, "Barycentric Weight"));
235 }
236
237 void hash_unique(UniqueHashBytes &hash) const override
238 {
239 static constexpr int8_t id = 0;
240 hash.add(&id);
241 hash.add(target_.get_mesh());
242 }
243};
244
246{
247 GeometrySet target = params.extract_input<GeometrySet>("Target Geometry"_ustr);
248 const auto mapping = params.get_input<GeometryNodeRaycastMapMode>("Interpolation"_ustr);
249
250 if (target.is_empty()) {
252 return;
253 }
254
255 if (!target.has_mesh()) {
257 return;
258 }
259
260 if (target.get_mesh()->faces_num == 0) {
261 params.error_message_add(NodeWarningType::Error, TIP_("The target mesh must have faces"));
263 return;
264 }
265
266 std::string error_message;
267
268 bke::SocketValueVariant normalized_direction;
269 {
270 auto ray_direction = params.extract_input<bke::SocketValueVariant>("Ray Direction"_ustr);
271
272 static const mf::MultiFunction &normalize_fn = fn::multi_function::registry::lookup(
273 "normalize(float3)"_ustr);
275 {&ray_direction},
276 {&normalized_direction},
277 params.user_data(),
278 error_message))
279 {
281 params.error_message_add(NodeWarningType::Error, std::move(error_message));
282 return;
283 }
284 }
285
286 auto position = params.extract_input<bke::SocketValueVariant>("Source Position"_ustr);
287 auto ray_length = params.extract_input<bke::SocketValueVariant>("Ray Length"_ustr);
288
289 const bool attribute_required = params.output_is_required("Attribute"_ustr);
290 const bool bary_weight_required = attribute_required && mapping == GEO_NODE_RAYCAST_INTERPOLATED;
291
293 bke::SocketValueVariant hit_position;
294 bke::SocketValueVariant hit_normal;
295 bke::SocketValueVariant hit_distance;
296 bke::SocketValueVariant triangle_index;
297 bke::SocketValueVariant bary_weights;
298 if (!execute_multi_function_on_value_variant(std::make_unique<RaycastFunction>(target),
299 {&position, &normalized_direction, &ray_length},
300 {&is_hit,
301 &hit_position,
302 &hit_normal,
303 &hit_distance,
304 &triangle_index,
305 bary_weight_required ? &bary_weights : nullptr},
306 params.user_data(),
307 error_message))
308 {
310 params.error_message_add(NodeWarningType::Error, std::move(error_message));
311 return;
312 }
313
314 params.set_output("Is Hit"_ustr, std::move(is_hit));
315 params.set_output("Hit Position"_ustr, hit_position);
316 params.set_output("Hit Normal"_ustr, std::move(hit_normal));
317 params.set_output("Hit Distance"_ustr, std::move(hit_distance));
318
319 if (!attribute_required) {
320 return;
321 }
322
323 GField field = params.extract_input<GField>("Attribute"_ustr);
324 bke::SocketValueVariant triangle_index_copy = triangle_index;
325 switch (mapping) {
327 bke::SocketValueVariant sampled_atribute;
329 std::make_shared<bke::mesh_surface_sample::BaryWeightSampleFn>(std::move(target),
330 std::move(field)),
331 {&triangle_index, &bary_weights},
332 {&sampled_atribute},
333 params.user_data(),
334 error_message))
335 {
337 params.error_message_add(NodeWarningType::Error, std::move(error_message));
338 return;
339 }
340 params.set_output("Attribute"_ustr, std::move(sampled_atribute));
341 break;
342 }
344 bke::SocketValueVariant nearest_corner;
346 std::make_shared<bke::mesh_surface_sample::NearestCornerFromPositionFn>(target),
347 {&hit_position, &triangle_index_copy},
348 {&nearest_corner},
349 params.user_data(),
350 error_message))
351 {
353 params.error_message_add(NodeWarningType::Error, std::move(error_message));
354 return;
355 }
356 bke::SocketValueVariant sampled_atribute;
358 std::make_shared<bke::SampleIndexFunction>(
359 std::move(target), std::move(field), bke::AttrDomain::Corner),
360 {&nearest_corner},
361 {&sampled_atribute},
362 params.user_data(),
363 error_message))
364 {
366 params.error_message_add(NodeWarningType::Error, std::move(error_message));
367 return;
368 }
369 params.set_output("Attribute"_ustr, std::move(sampled_atribute));
370 break;
371 }
372 }
373}
374
375static void node_rna(StructRNA *srna)
376{
378 "data_type",
379 "Data Type",
380 "Type of data stored in attribute",
385}
386
387static void node_register()
388{
389 static bke::bNodeType ntype;
390
391 geo_node_type_base(&ntype, "GeometryNodeRaycast"_ustr, GEO_NODE_RAYCAST);
392 ntype.ui_name = "Raycast";
393 ntype.ui_description =
394 "Cast rays from the context geometry onto a target geometry, and retrieve information from "
395 "each hit point";
396 ntype.enum_name_legacy = "RAYCAST";
399 ntype.initfunc = node_init;
401 ntype, "NodeGeometryRaycast", node_free_standard_storage, node_copy_standard_storage);
402 ntype.declare = node_declare;
407
408 node_rna(ntype.rna_ext.srna);
409}
411
412} // namespace blender::nodes::node_geo_raycast_cc
#define NODE_STORAGE_FUNCS(StorageT)
Definition BKE_node.hh:1353
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_RAYCAST
#define TIP_(msgid)
#define IFACE_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_storage_enum_accessors(member)
#define UI_ITEM_NONE
constexpr bool is_empty() const
Definition BLI_span.hh:515
std::optional< RayHit > ray_intersect(const Ray &ray) const
Definition bvh.cc:439
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)
T get_input(const UString identifier) const
GeoNodesUserData * user_data() const
bool output_is_required(const UString identifier) const
void set_output(const UString identifier, T &&value)
void update_and_connect_available_socket(bNode &new_node, UString socket_name)
Vector< SocketDeclaration * > inputs
Vector< SocketDeclaration * > outputs
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
void hash_unique(UniqueHashBytes &hash) const override
#define position
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
std::optional< eCustomDataType > socket_type_to_custom_data_type(eNodeSocketDatatype type)
Definition node.cc:5911
const MultiFunction & lookup(UString id)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
const EnumPropertyItem * attribute_type_type_with_socket_fn(bContext *, PointerRNA *, PropertyRNA *, bool *r_free)
static EnumPropertyItem interpolation_items[]
static void node_geo_exec(GeoNodeExecParams params)
static void node_init(bNodeTree *, bNode *node)
static void node_rna(StructRNA *srna)
static void raycast_to_mesh(const IndexMask &mask, const Mesh &mesh, const VArray< float3 > &ray_origins, const VArray< float3 > &ray_directions, const VArray< float > &ray_lengths, const MutableSpan< bool > r_hit, const MutableSpan< int > r_hit_indices, const MutableSpan< float3 > r_hit_positions, const MutableSpan< float3 > r_hit_normals, const MutableSpan< float > r_hit_distances, const MutableSpan< float3 > r_bary_weights)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static void node_gather_link_searches(GatherLinkSearchOpParams &params)
static void node_declare(NodeDeclarationBuilder &b)
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)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
@ GEO_NODE_RAYCAST_NEAREST
@ GEO_NODE_RAYCAST_INTERPOLATED
BMesh const char void * data
const EnumPropertyItem rna_enum_attribute_type_items[]
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
@ PROP_DISTANCE
Definition RNA_types.hh:313
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
const Mesh * get_mesh() const
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
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)
#define N_(msgid)