Welcome to mirror list, hosted at ThFree Co, Russian Federation.

node_geo_curve_to_points.cc « nodes « geometry « nodes « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0ddf06dc8c79c1d45314e055c05393dce5b220c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/* SPDX-License-Identifier: GPL-2.0-or-later */

#include "BLI_array.hh"
#include "BLI_task.hh"
#include "BLI_timeit.hh"

#include "BKE_pointcloud.h"
#include "BKE_spline.hh"

#include "UI_interface.h"
#include "UI_resources.h"

#include "node_geometry_util.hh"

namespace blender::nodes::node_geo_curve_to_points_cc {

NODE_STORAGE_FUNCS(NodeGeometryCurveToPoints)

static void node_declare(NodeDeclarationBuilder &b)
{
  b.add_input<decl::Geometry>(N_("Curve")).supported_type(GEO_COMPONENT_TYPE_CURVE);
  b.add_input<decl::Int>(N_("Count"))
      .default_value(10)
      .min(2)
      .max(100000)
      .make_available(
          [](bNode &node) { node_storage(node).mode = GEO_NODE_CURVE_RESAMPLE_COUNT; });
  b.add_input<decl::Float>(N_("Length"))
      .default_value(0.1f)
      .min(0.001f)
      .subtype(PROP_DISTANCE)
      .make_available(
          [](bNode &node) { node_storage(node).mode = GEO_NODE_CURVE_RESAMPLE_LENGTH; });
  b.add_output<decl::Geometry>(N_("Points"));
  b.add_output<decl::Vector>(N_("Tangent")).field_source();
  b.add_output<decl::Vector>(N_("Normal")).field_source();
  b.add_output<decl::Vector>(N_("Rotation")).field_source();
}

static void node_layout(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
{
  uiItemR(layout, ptr, "mode", 0, "", ICON_NONE);
}

static void node_init(bNodeTree *UNUSED(tree), bNode *node)
{
  NodeGeometryCurveToPoints *data = MEM_cnew<NodeGeometryCurveToPoints>(__func__);

  data->mode = GEO_NODE_CURVE_RESAMPLE_COUNT;
  node->storage = data;
}

static void node_update(bNodeTree *ntree, bNode *node)
{
  const NodeGeometryCurveToPoints &storage = node_storage(*node);
  const GeometryNodeCurveResampleMode mode = (GeometryNodeCurveResampleMode)storage.mode;

  bNodeSocket *count_socket = ((bNodeSocket *)node->inputs.first)->next;
  bNodeSocket *length_socket = count_socket->next;

  nodeSetSocketAvailability(ntree, count_socket, mode == GEO_NODE_CURVE_RESAMPLE_COUNT);
  nodeSetSocketAvailability(ntree, length_socket, mode == GEO_NODE_CURVE_RESAMPLE_LENGTH);
}

static void curve_create_default_rotation_attribute(Span<float3> tangents,
                                                    Span<float3> normals,
                                                    MutableSpan<float3> rotations)
{
  threading::parallel_for(IndexRange(rotations.size()), 512, [&](IndexRange range) {
    for (const int i : range) {
      rotations[i] =
          float4x4::from_normalized_axis_data({0, 0, 0}, normals[i], tangents[i]).to_euler();
    }
  });
}

static Array<int> calculate_spline_point_offsets(GeoNodeExecParams &params,
                                                 const GeometryNodeCurveResampleMode mode,
                                                 const CurveEval &curve,
                                                 const Span<SplinePtr> splines)
{
  const int size = curve.splines().size();
  switch (mode) {
    case GEO_NODE_CURVE_RESAMPLE_COUNT: {
      const int count = params.get_input<int>("Count");
      if (count < 1) {
        return {0};
      }
      Array<int> offsets(size + 1);
      int offset = 0;
      for (const int i : IndexRange(size)) {
        offsets[i] = offset;
        if (splines[i]->evaluated_points_num() > 0) {
          offset += count;
        }
      }
      offsets.last() = offset;
      return offsets;
    }
    case GEO_NODE_CURVE_RESAMPLE_LENGTH: {
      /* Don't allow asymptotic count increase for low resolution values. */
      const float resolution = std::max(params.get_input<float>("Length"), 0.0001f);
      Array<int> offsets(size + 1);
      int offset = 0;
      for (const int i : IndexRange(size)) {
        offsets[i] = offset;
        if (splines[i]->evaluated_points_num() > 0) {
          offset += splines[i]->length() / resolution + 1;
        }
      }
      offsets.last() = offset;
      return offsets;
    }
    case GEO_NODE_CURVE_RESAMPLE_EVALUATED: {
      return curve.evaluated_point_offsets();
    }
  }
  BLI_assert_unreachable();
  return {0};
}

/**
 * \note Relies on the fact that all attributes on point clouds are stored contiguously.
 */
static GMutableSpan ensure_point_attribute(PointCloudComponent &points,
                                           const AttributeIDRef &attribute_id,
                                           const eCustomDataType data_type)
{
  GAttributeWriter attribute = points.attributes_for_write()->lookup_or_add_for_write(
      attribute_id, ATTR_DOMAIN_POINT, data_type);
  GMutableSpan span = attribute.varray.get_internal_span();
  attribute.finish();
  return span;
}

template<typename T>
static MutableSpan<T> ensure_point_attribute(PointCloudComponent &points,
                                             const AttributeIDRef &attribute_id)
{
  AttributeWriter<T> attribute = points.attributes_for_write()->lookup_or_add_for_write<T>(
      attribute_id, ATTR_DOMAIN_POINT);
  MutableSpan<T> span = attribute.varray.get_internal_span();
  attribute.finish();
  return span;
}

namespace {
struct AnonymousAttributeIDs {
  StrongAnonymousAttributeID tangent_id;
  StrongAnonymousAttributeID normal_id;
  StrongAnonymousAttributeID rotation_id;
};

struct ResultAttributes {
  MutableSpan<float3> positions;
  MutableSpan<float> radii;

  Map<AttributeIDRef, GMutableSpan> point_attributes;

  MutableSpan<float3> tangents;
  MutableSpan<float3> normals;
  MutableSpan<float3> rotations;
};
}  // namespace

static ResultAttributes create_attributes_for_transfer(PointCloudComponent &points,
                                                       const CurveEval &curve,
                                                       const AnonymousAttributeIDs &attributes)
{
  ResultAttributes outputs;

  outputs.positions = ensure_point_attribute<float3>(points, "position");
  outputs.radii = ensure_point_attribute<float>(points, "radius");

  if (attributes.tangent_id) {
    outputs.tangents = ensure_point_attribute<float3>(points, attributes.tangent_id.get());
  }
  if (attributes.normal_id) {
    outputs.normals = ensure_point_attribute<float3>(points, attributes.normal_id.get());
  }
  if (attributes.rotation_id) {
    outputs.rotations = ensure_point_attribute<float3>(points, attributes.rotation_id.get());
  }

  /* Because of the invariants of the curve component, we use the attributes of the first spline
   * as a representative for the attribute meta data all splines. Attributes from the spline domain
   * are handled separately. */
  curve.splines().first()->attributes.foreach_attribute(
      [&](const AttributeIDRef &id, const AttributeMetaData &meta_data) {
        if (id.should_be_kept()) {
          outputs.point_attributes.add_new(
              id, ensure_point_attribute(points, id, meta_data.data_type));
        }
        return true;
      },
      ATTR_DOMAIN_POINT);

  return outputs;
}

/**
 * TODO: For non-poly splines, this has double copies that could be avoided as part
 * of a general look at optimizing uses of #Spline::interpolate_to_evaluated.
 */
static void copy_evaluated_point_attributes(const Span<SplinePtr> splines,
                                            const Span<int> offsets,
                                            ResultAttributes &data)
{
  threading::parallel_for(splines.index_range(), 64, [&](IndexRange range) {
    for (const int i : range) {
      const Spline &spline = *splines[i];
      const int offset = offsets[i];
      const int size = offsets[i + 1] - offsets[i];

      data.positions.slice(offset, size).copy_from(spline.evaluated_positions());
      spline.interpolate_to_evaluated(spline.radii()).materialize(data.radii.slice(offset, size));

      for (const Map<AttributeIDRef, GMutableSpan>::Item item : data.point_attributes.items()) {
        const AttributeIDRef attribute_id = item.key;
        const GMutableSpan dst = item.value;

        BLI_assert(spline.attributes.get_for_read(attribute_id));
        GSpan spline_span = *spline.attributes.get_for_read(attribute_id);

        spline.interpolate_to_evaluated(spline_span).materialize(dst.slice(offset, size).data());
      }

      if (!data.tangents.is_empty()) {
        data.tangents.slice(offset, size).copy_from(spline.evaluated_tangents());
      }
      if (!data.normals.is_empty()) {
        data.normals.slice(offset, size).copy_from(spline.evaluated_normals());
      }
    }
  });
}

static void copy_uniform_sample_point_attributes(const Span<SplinePtr> splines,
                                                 const Span<int> offsets,
                                                 ResultAttributes &data)
{
  threading::parallel_for(splines.index_range(), 64, [&](IndexRange range) {
    for (const int i : range) {
      const Spline &spline = *splines[i];
      const int offset = offsets[i];
      const int num = offsets[i + 1] - offsets[i];
      if (num == 0) {
        continue;
      }

      const Array<float> uniform_samples = spline.sample_uniform_index_factors(num);

      spline.sample_with_index_factors<float3>(
          spline.evaluated_positions(), uniform_samples, data.positions.slice(offset, num));
      spline.sample_with_index_factors<float>(spline.interpolate_to_evaluated(spline.radii()),
                                              uniform_samples,
                                              data.radii.slice(offset, num));

      for (const Map<AttributeIDRef, GMutableSpan>::Item item : data.point_attributes.items()) {
        const AttributeIDRef attribute_id = item.key;
        const GMutableSpan dst = item.value;

        BLI_assert(spline.attributes.get_for_read(attribute_id));
        GSpan spline_span = *spline.attributes.get_for_read(attribute_id);

        spline.sample_with_index_factors(
            spline.interpolate_to_evaluated(spline_span), uniform_samples, dst.slice(offset, num));
      }

      if (!data.tangents.is_empty()) {
        Span<float3> src_tangents = spline.evaluated_tangents();
        MutableSpan<float3> sampled_tangents = data.tangents.slice(offset, num);
        spline.sample_with_index_factors<float3>(src_tangents, uniform_samples, sampled_tangents);
        for (float3 &vector : sampled_tangents) {
          vector = math::normalize(vector);
        }
      }

      if (!data.normals.is_empty()) {
        Span<float3> src_normals = spline.evaluated_normals();
        MutableSpan<float3> sampled_normals = data.normals.slice(offset, num);
        spline.sample_with_index_factors<float3>(src_normals, uniform_samples, sampled_normals);
        for (float3 &vector : sampled_normals) {
          vector = math::normalize(vector);
        }
      }
    }
  });
}

static void copy_spline_domain_attributes(const CurveEval &curve,
                                          const Span<int> offsets,
                                          PointCloudComponent &points)
{
  curve.attributes.foreach_attribute(
      [&](const AttributeIDRef &attribute_id, const AttributeMetaData &meta_data) {
        const GSpan curve_attribute = *curve.attributes.get_for_read(attribute_id);
        const CPPType &type = curve_attribute.type();
        const GMutableSpan dst = ensure_point_attribute(points, attribute_id, meta_data.data_type);

        for (const int i : curve.splines().index_range()) {
          const int offset = offsets[i];
          const int num = offsets[i + 1] - offsets[i];
          type.fill_assign_n(curve_attribute[i], dst[offset], num);
        }

        return true;
      },
      ATTR_DOMAIN_CURVE);
}

static void node_geo_exec(GeoNodeExecParams params)
{
  const NodeGeometryCurveToPoints &storage = node_storage(params.node());
  const GeometryNodeCurveResampleMode mode = (GeometryNodeCurveResampleMode)storage.mode;
  GeometrySet geometry_set = params.extract_input<GeometrySet>("Curve");

  AnonymousAttributeIDs attribute_outputs;
  attribute_outputs.tangent_id = StrongAnonymousAttributeID("Tangent");
  attribute_outputs.normal_id = StrongAnonymousAttributeID("Normal");
  attribute_outputs.rotation_id = StrongAnonymousAttributeID("Rotation");

  GeometryComponentEditData::remember_deformed_curve_positions_if_necessary(geometry_set);

  geometry_set.modify_geometry_sets([&](GeometrySet &geometry_set) {
    if (!geometry_set.has_curves()) {
      geometry_set.remove_geometry_during_modify();
      return;
    }
    const std::unique_ptr<CurveEval> curve = curves_to_curve_eval(
        *geometry_set.get_curves_for_read());
    const Span<SplinePtr> splines = curve->splines();
    curve->assert_valid_point_attributes();

    const Array<int> offsets = calculate_spline_point_offsets(params, mode, *curve, splines);
    const int total_num = offsets.last();
    if (total_num == 0) {
      geometry_set.remove_geometry_during_modify();
      return;
    }

    geometry_set.replace_pointcloud(BKE_pointcloud_new_nomain(total_num));
    PointCloudComponent &points = geometry_set.get_component_for_write<PointCloudComponent>();
    ResultAttributes point_attributes = create_attributes_for_transfer(
        points, *curve, attribute_outputs);

    switch (mode) {
      case GEO_NODE_CURVE_RESAMPLE_COUNT:
      case GEO_NODE_CURVE_RESAMPLE_LENGTH:
        copy_uniform_sample_point_attributes(splines, offsets, point_attributes);
        break;
      case GEO_NODE_CURVE_RESAMPLE_EVALUATED:
        copy_evaluated_point_attributes(splines, offsets, point_attributes);
        break;
    }

    copy_spline_domain_attributes(*curve, offsets, points);

    if (!point_attributes.rotations.is_empty()) {
      curve_create_default_rotation_attribute(
          point_attributes.tangents, point_attributes.normals, point_attributes.rotations);
    }

    geometry_set.keep_only_during_modify({GEO_COMPONENT_TYPE_POINT_CLOUD});
  });

  params.set_output("Points", std::move(geometry_set));
  if (attribute_outputs.tangent_id) {
    params.set_output(
        "Tangent",
        AnonymousAttributeFieldInput::Create<float3>(std::move(attribute_outputs.tangent_id),
                                                     params.attribute_producer_name()));
  }
  if (attribute_outputs.normal_id) {
    params.set_output(
        "Normal",
        AnonymousAttributeFieldInput::Create<float3>(std::move(attribute_outputs.normal_id),
                                                     params.attribute_producer_name()));
  }
  if (attribute_outputs.rotation_id) {
    params.set_output(
        "Rotation",
        AnonymousAttributeFieldInput::Create<float3>(std::move(attribute_outputs.rotation_id),
                                                     params.attribute_producer_name()));
  }
}

}  // namespace blender::nodes::node_geo_curve_to_points_cc

void register_node_type_geo_curve_to_points()
{
  namespace file_ns = blender::nodes::node_geo_curve_to_points_cc;

  static bNodeType ntype;

  geo_node_type_base(&ntype, GEO_NODE_CURVE_TO_POINTS, "Curve to Points", NODE_CLASS_GEOMETRY);
  ntype.declare = file_ns::node_declare;
  ntype.geometry_node_execute = file_ns::node_geo_exec;
  ntype.draw_buttons = file_ns::node_layout;
  node_type_storage(
      &ntype, "NodeGeometryCurveToPoints", node_free_standard_storage, node_copy_standard_storage);
  node_type_init(&ntype, file_ns::node_init);
  node_type_update(&ntype, file_ns::node_update);
  nodeRegisterType(&ntype);
}