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

node_geo_accumulate_field.cc « nodes « geometry « nodes « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9af445090e90c2b8f92badeb7fde1c00f6cc969b (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/* SPDX-License-Identifier: GPL-2.0-or-later */

#include "BKE_attribute_math.hh"

#include "NOD_socket_search_link.hh"

#include "node_geometry_util.hh"

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

namespace blender::nodes::node_geo_accumulate_field_cc {

NODE_STORAGE_FUNCS(NodeAccumulateField)

static void node_declare(NodeDeclarationBuilder &b)
{
  std::string value_in_description = "The values to be accumulated";
  std::string leading_out_description =
      "The running total of values in the corresponding group, starting at the first value";
  std::string trailing_out_description =
      "The running total of values in the corresponding group, starting at zero";
  std::string total_out_description = "The total of all of the values in the corresponding group";

  b.add_input<decl::Vector>(N_("Value"), "Value Vector")
      .default_value({1.0f, 1.0f, 1.0f})
      .supports_field()
      .description(N_(value_in_description));
  b.add_input<decl::Float>(N_("Value"), "Value Float")
      .default_value(1.0f)
      .supports_field()
      .description(N_(value_in_description));
  b.add_input<decl::Int>(N_("Value"), "Value Int")
      .default_value(1)
      .supports_field()
      .description(N_(value_in_description));
  b.add_input<decl::Int>(N_("Group Index"))
      .supports_field()
      .description(
          N_("An index used to group values together for multiple separate accumulations"));

  b.add_output<decl::Vector>(N_("Leading"), "Leading Vector")
      .field_source()
      .description(N_(leading_out_description));
  b.add_output<decl::Float>(N_("Leading"), "Leading Float")
      .field_source()
      .description(N_(leading_out_description));
  b.add_output<decl::Int>(N_("Leading"), "Leading Int")
      .field_source()
      .description(N_(leading_out_description));

  b.add_output<decl::Vector>(N_("Trailing"), "Trailing Vector")
      .field_source()
      .description(N_(trailing_out_description));
  b.add_output<decl::Float>(N_("Trailing"), "Trailing Float")
      .field_source()
      .description(N_(trailing_out_description));
  b.add_output<decl::Int>(N_("Trailing"), "Trailing Int")
      .field_source()
      .description(N_(trailing_out_description));

  b.add_output<decl::Vector>(N_("Total"), "Total Vector")
      .field_source()
      .description(N_(total_out_description));
  b.add_output<decl::Float>(N_("Total"), "Total Float")
      .field_source()
      .description(N_(total_out_description));
  b.add_output<decl::Int>(N_("Total"), "Total Int")
      .field_source()
      .description(N_(total_out_description));
}

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

static void node_init(bNodeTree * /*tree*/, bNode *node)
{
  NodeAccumulateField *data = MEM_cnew<NodeAccumulateField>(__func__);
  data->data_type = CD_PROP_FLOAT;
  data->domain = ATTR_DOMAIN_POINT;
  node->storage = data;
}

static void node_update(bNodeTree *ntree, bNode *node)
{
  const NodeAccumulateField &storage = node_storage(*node);
  const eCustomDataType data_type = eCustomDataType(storage.data_type);

  bNodeSocket *sock_in_vector = static_cast<bNodeSocket *>(node->inputs.first);
  bNodeSocket *sock_in_float = sock_in_vector->next;
  bNodeSocket *sock_in_int = sock_in_float->next;

  bNodeSocket *sock_out_vector = static_cast<bNodeSocket *>(node->outputs.first);
  bNodeSocket *sock_out_float = sock_out_vector->next;
  bNodeSocket *sock_out_int = sock_out_float->next;

  bNodeSocket *sock_out_first_vector = sock_out_int->next;
  bNodeSocket *sock_out_first_float = sock_out_first_vector->next;
  bNodeSocket *sock_out_first_int = sock_out_first_float->next;
  bNodeSocket *sock_out_total_vector = sock_out_first_int->next;
  bNodeSocket *sock_out_total_float = sock_out_total_vector->next;
  bNodeSocket *sock_out_total_int = sock_out_total_float->next;

  nodeSetSocketAvailability(ntree, sock_in_vector, data_type == CD_PROP_FLOAT3);
  nodeSetSocketAvailability(ntree, sock_in_float, data_type == CD_PROP_FLOAT);
  nodeSetSocketAvailability(ntree, sock_in_int, data_type == CD_PROP_INT32);

  nodeSetSocketAvailability(ntree, sock_out_vector, data_type == CD_PROP_FLOAT3);
  nodeSetSocketAvailability(ntree, sock_out_float, data_type == CD_PROP_FLOAT);
  nodeSetSocketAvailability(ntree, sock_out_int, data_type == CD_PROP_INT32);

  nodeSetSocketAvailability(ntree, sock_out_first_vector, data_type == CD_PROP_FLOAT3);
  nodeSetSocketAvailability(ntree, sock_out_first_float, data_type == CD_PROP_FLOAT);
  nodeSetSocketAvailability(ntree, sock_out_first_int, data_type == CD_PROP_INT32);

  nodeSetSocketAvailability(ntree, sock_out_total_vector, data_type == CD_PROP_FLOAT3);
  nodeSetSocketAvailability(ntree, sock_out_total_float, data_type == CD_PROP_FLOAT);
  nodeSetSocketAvailability(ntree, sock_out_total_int, data_type == CD_PROP_INT32);
}

enum class AccumulationMode { Leading = 0, Trailing = 1 };

static std::optional<eCustomDataType> node_type_from_other_socket(const bNodeSocket &socket)
{
  switch (socket.type) {
    case SOCK_FLOAT:
      return CD_PROP_FLOAT;
    case SOCK_BOOLEAN:
    case SOCK_INT:
      return CD_PROP_INT32;
    case SOCK_VECTOR:
    case SOCK_RGBA:
      return CD_PROP_FLOAT3;
    default:
      return {};
  }
}

static void node_gather_link_searches(GatherLinkSearchOpParams &params)
{
  const std::optional<eCustomDataType> type = node_type_from_other_socket(params.other_socket());
  if (!type) {
    return;
  }
  if (params.in_out() == SOCK_OUT) {
    params.add_item(
        IFACE_("Leading"),
        [type](LinkSearchOpParams &params) {
          bNode &node = params.add_node("GeometryNodeAccumulateField");
          node_storage(node).data_type = *type;
          params.update_and_connect_available_socket(node, "Leading");
        },
        0);
    params.add_item(
        IFACE_("Trailing"),
        [type](LinkSearchOpParams &params) {
          bNode &node = params.add_node("GeometryNodeAccumulateField");
          node_storage(node).data_type = *type;
          params.update_and_connect_available_socket(node, "Trailing");
        },
        -1);
    params.add_item(
        IFACE_("Total"),
        [type](LinkSearchOpParams &params) {
          bNode &node = params.add_node("GeometryNodeAccumulateField");
          node_storage(node).data_type = *type;
          params.update_and_connect_available_socket(node, "Total");
        },
        -2);
  }
  else {
    params.add_item(
        IFACE_("Value"),
        [type](LinkSearchOpParams &params) {
          bNode &node = params.add_node("GeometryNodeAccumulateField");
          node_storage(node).data_type = *type;
          params.update_and_connect_available_socket(node, "Value");
        },
        0);

    params.add_item(
        IFACE_("Group Index"),
        [type](LinkSearchOpParams &params) {
          bNode &node = params.add_node("GeometryNodeAccumulateField");
          node_storage(node).data_type = *type;
          params.update_and_connect_available_socket(node, "Group Index");
        },
        -1);
  }
}

template<typename T> class AccumulateFieldInput final : public bke::GeometryFieldInput {
 private:
  Field<T> input_;
  Field<int> group_index_;
  eAttrDomain source_domain_;
  AccumulationMode accumulation_mode_;

 public:
  AccumulateFieldInput(const eAttrDomain source_domain,
                       Field<T> input,
                       Field<int> group_index,
                       AccumulationMode accumulation_mode)
      : bke::GeometryFieldInput(CPPType::get<T>(), "Accumulation"),
        input_(input),
        group_index_(group_index),
        source_domain_(source_domain),
        accumulation_mode_(accumulation_mode)
  {
  }

  GVArray get_varray_for_context(const bke::GeometryFieldContext &context,
                                 const IndexMask /*mask*/) const final
  {
    const AttributeAccessor attributes = *context.attributes();
    const int domain_size = attributes.domain_size(source_domain_);
    if (domain_size == 0) {
      return {};
    }

    const bke::GeometryFieldContext source_context{
        context.geometry(), context.type(), source_domain_};
    fn::FieldEvaluator evaluator{source_context, domain_size};
    evaluator.add(input_);
    evaluator.add(group_index_);
    evaluator.evaluate();
    const VArray<T> values = evaluator.get_evaluated<T>(0);
    const VArray<int> group_indices = evaluator.get_evaluated<int>(1);

    Array<T> accumulations_out(domain_size);

    if (group_indices.is_single()) {
      T accumulation = T();
      if (accumulation_mode_ == AccumulationMode::Leading) {
        for (const int i : values.index_range()) {
          accumulation = values[i] + accumulation;
          accumulations_out[i] = accumulation;
        }
      }
      else {
        for (const int i : values.index_range()) {
          accumulations_out[i] = accumulation;
          accumulation = values[i] + accumulation;
        }
      }
    }
    else {
      Map<int, T> accumulations;
      if (accumulation_mode_ == AccumulationMode::Leading) {
        for (const int i : values.index_range()) {
          T &accumulation_value = accumulations.lookup_or_add_default(group_indices[i]);
          accumulation_value += values[i];
          accumulations_out[i] = accumulation_value;
        }
      }
      else {
        for (const int i : values.index_range()) {
          T &accumulation_value = accumulations.lookup_or_add_default(group_indices[i]);
          accumulations_out[i] = accumulation_value;
          accumulation_value += values[i];
        }
      }
    }

    return attributes.adapt_domain<T>(
        VArray<T>::ForContainer(std::move(accumulations_out)), source_domain_, context.domain());
  }

  uint64_t hash() const override
  {
    return get_default_hash_4(input_, group_index_, source_domain_, accumulation_mode_);
  }

  bool is_equal_to(const fn::FieldNode &other) const override
  {
    if (const AccumulateFieldInput *other_accumulate = dynamic_cast<const AccumulateFieldInput *>(
            &other)) {
      return input_ == other_accumulate->input_ &&
             group_index_ == other_accumulate->group_index_ &&
             source_domain_ == other_accumulate->source_domain_ &&
             accumulation_mode_ == other_accumulate->accumulation_mode_;
    }
    return false;
  }

  std::optional<eAttrDomain> preferred_domain(
      const GeometryComponent & /*component*/) const override
  {
    return source_domain_;
  }
};

template<typename T> class TotalFieldInput final : public bke::GeometryFieldInput {
 private:
  Field<T> input_;
  Field<int> group_index_;
  eAttrDomain source_domain_;

 public:
  TotalFieldInput(const eAttrDomain source_domain, Field<T> input, Field<int> group_index)
      : bke::GeometryFieldInput(CPPType::get<T>(), "Total Value"),
        input_(input),
        group_index_(group_index),
        source_domain_(source_domain)
  {
  }

  GVArray get_varray_for_context(const bke::GeometryFieldContext &context,
                                 IndexMask /*mask*/) const final
  {
    const AttributeAccessor attributes = *context.attributes();
    const int domain_size = attributes.domain_size(source_domain_);
    if (domain_size == 0) {
      return {};
    }

    const bke::GeometryFieldContext source_context{
        context.geometry(), context.type(), source_domain_};
    fn::FieldEvaluator evaluator{source_context, domain_size};
    evaluator.add(input_);
    evaluator.add(group_index_);
    evaluator.evaluate();
    const VArray<T> values = evaluator.get_evaluated<T>(0);
    const VArray<int> group_indices = evaluator.get_evaluated<int>(1);

    if (group_indices.is_single()) {
      T accumulation = T();
      for (const int i : values.index_range()) {
        accumulation = values[i] + accumulation;
      }
      return VArray<T>::ForSingle(accumulation, domain_size);
    }

    Array<T> accumulations_out(domain_size);
    Map<int, T> accumulations;
    for (const int i : values.index_range()) {
      T &value = accumulations.lookup_or_add_default(group_indices[i]);
      value = value + values[i];
    }
    for (const int i : values.index_range()) {
      accumulations_out[i] = accumulations.lookup(group_indices[i]);
    }

    return attributes.adapt_domain<T>(
        VArray<T>::ForContainer(std::move(accumulations_out)), source_domain_, context.domain());
  }

  uint64_t hash() const override
  {
    return get_default_hash_3(input_, group_index_, source_domain_);
  }

  bool is_equal_to(const fn::FieldNode &other) const override
  {
    if (const TotalFieldInput *other_field = dynamic_cast<const TotalFieldInput *>(&other)) {
      return input_ == other_field->input_ && group_index_ == other_field->group_index_ &&
             source_domain_ == other_field->source_domain_;
    }
    return false;
  }

  std::optional<eAttrDomain> preferred_domain(
      const GeometryComponent & /*component*/) const override
  {
    return source_domain_;
  }
};

template<typename T> std::string identifier_suffix()
{
  if constexpr (std::is_same_v<T, int>) {
    return "Int";
  }
  if constexpr (std::is_same_v<T, float>) {
    return "Float";
  }
  if constexpr (std::is_same_v<T, float3>) {
    return "Vector";
  }
}

static void node_geo_exec(GeoNodeExecParams params)
{
  const NodeAccumulateField &storage = node_storage(params.node());
  const eCustomDataType data_type = eCustomDataType(storage.data_type);
  const eAttrDomain source_domain = eAttrDomain(storage.domain);

  Field<int> group_index_field = params.extract_input<Field<int>>("Group Index");
  attribute_math::convert_to_static_type(data_type, [&](auto dummy) {
    using T = decltype(dummy);
    if constexpr (std::is_same_v<T, int> || std::is_same_v<T, float> ||
                  std::is_same_v<T, float3>) {
      const std::string suffix = " " + identifier_suffix<T>();
      Field<T> input_field = params.extract_input<Field<T>>("Value" + suffix);
      if (params.output_is_required("Leading" + suffix)) {
        params.set_output(
            "Leading" + suffix,
            Field<T>{std::make_shared<AccumulateFieldInput<T>>(
                source_domain, input_field, group_index_field, AccumulationMode::Leading)});
      }
      if (params.output_is_required("Trailing" + suffix)) {
        params.set_output(
            "Trailing" + suffix,
            Field<T>{std::make_shared<AccumulateFieldInput<T>>(
                source_domain, input_field, group_index_field, AccumulationMode::Trailing)});
      }
      if (params.output_is_required("Total" + suffix)) {
        params.set_output("Total" + suffix,
                          Field<T>{std::make_shared<TotalFieldInput<T>>(
                              source_domain, input_field, group_index_field)});
      }
    }
  });
}
}  // namespace blender::nodes::node_geo_accumulate_field_cc

void register_node_type_geo_accumulate_field()
{
  namespace file_ns = blender::nodes::node_geo_accumulate_field_cc;

  static bNodeType ntype;

  geo_node_type_base(&ntype, GEO_NODE_ACCUMULATE_FIELD, "Accumulate Field", NODE_CLASS_CONVERTER);
  ntype.geometry_node_execute = file_ns::node_geo_exec;
  node_type_init(&ntype, file_ns::node_init);
  node_type_update(&ntype, file_ns::node_update);
  ntype.draw_buttons = file_ns::node_layout;
  ntype.declare = file_ns::node_declare;
  ntype.gather_link_search_ops = file_ns::node_gather_link_searches;
  node_type_storage(
      &ntype, "NodeAccumulateField", node_free_standard_storage, node_copy_standard_storage);
  nodeRegisterType(&ntype);
}