Blender V5.3
node_geo_distribute_points_in_grid.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#ifdef WITH_OPENVDB
6# include <openvdb/openvdb.h>
7# include <openvdb/tools/Interpolation.h>
8# include <openvdb/tools/PointScatter.h>
9
10# include <algorithm>
11#endif
12
13#include "DNA_node_types.h"
15
16#include "BKE_pointcloud.hh"
17#include "BKE_volume_grid.hh"
18
19#include "NOD_rna_define.hh"
20
22#include "UI_resources.hh"
23
24#include "GEO_randomize.hh"
25
26#include "node_geometry_util.hh"
27
29
30enum class DistributeMode {
31 Random = 0,
32 Grid = 1,
33};
34
36{
37 b.add_input<decl::Float>("Grid"_ustr).hide_value().structure_type(StructureType::Grid);
38 auto &density = b.add_input<decl::Float>("Density"_ustr)
39 .default_value(1.0f)
40 .min(0.0f)
41 .max(100000.0f)
43 .description(
44 "When combined with each voxel's value, determines the number of points "
45 "to sample per unit volume")
46 .make_available(
47 [](bNode &node) { node.custom1 = int16_t(DistributeMode::Random); });
48 auto &seed =
49 b.add_input<decl::Int>("Seed"_ustr)
50 .min(-10000)
51 .max(10000)
52 .description("Seed used by the random number generator to generate random points")
53 .make_available([](bNode &node) { node.custom1 = int16_t(DistributeMode::Random); });
54 auto &spacing = b.add_input<decl::Vector>("Spacing"_ustr)
55 .default_value({0.3, 0.3, 0.3})
56 .min(0.0001f)
57 .subtype(PROP_XYZ)
58 .description("Spacing between grid points")
59 .make_available(
60 [](bNode &node) { node.custom1 = int16_t(DistributeMode::Grid); });
61 auto &threshold = b.add_input<decl::Float>("Threshold"_ustr)
62 .default_value(0.1f)
63 .min(0.0f)
64 .max(FLT_MAX)
65 .description("Minimum density of a voxel to contain a grid point")
66 .make_available(
67 [](bNode &node) { node.custom1 = int16_t(DistributeMode::Grid); });
68 b.add_output<decl::Geometry>("Points"_ustr).propagate_all_geometry();
69
70 const bNode *node = b.node_or_null();
71 if (node != nullptr) {
72 const auto mode = DistributeMode(node->custom1);
73 density.available(mode == DistributeMode::Random);
74 seed.available(mode == DistributeMode::Random);
75 spacing.available(mode == DistributeMode::Grid);
76 threshold.available(mode == DistributeMode::Grid);
77 }
78}
79
80static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
81{
82 layout.prop(ptr, "mode", UI_ITEM_NONE, "", ICON_NONE);
83}
84
85static void node_init(bNodeTree * /*tree*/, bNode *node)
86{
88}
89
90#ifdef WITH_OPENVDB
91/* Implements the interface required by #openvdb::tools::NonUniformPointScatter. */
92class PositionsVDBWrapper {
93 private:
94 Vector<float3> &vector_;
95
96 public:
97 PositionsVDBWrapper(Vector<float3> &vector) : vector_(vector) {}
98 PositionsVDBWrapper(const PositionsVDBWrapper &wrapper) = default;
99
100 void add(const openvdb::Vec3R &pos)
101 {
102 vector_.append(float3(float(pos[0]), float(pos[1]), float(pos[2])));
103 }
104};
105
106/* Use #std::mt19937 as a random number generator. It has a very long period and thus there should
107 * be no visible patterns in the generated points. */
108using RNGType = std::mt19937;
109/* Non-uniform scatter allows the amount of points to be scaled with the volume's density. */
110using NonUniformPointScatterVDB =
111 openvdb::tools::NonUniformPointScatter<PositionsVDBWrapper, RNGType>;
112
113static void point_scatter_density_random(const openvdb::FloatGrid &grid,
114 const float density,
115 const int seed,
116 Vector<float3> &r_positions)
117{
118 /* Setup and call into OpenVDB's point scatter API. */
119 PositionsVDBWrapper vdb_position_wrapper(r_positions);
120 RNGType random_generator(seed);
121 NonUniformPointScatterVDB point_scatter(vdb_position_wrapper, density, random_generator);
122 point_scatter(grid);
123}
124
125static void point_scatter_density_grid(const openvdb::FloatGrid &grid,
126 const float3 spacing,
127 const float threshold,
128 Vector<float3> &r_positions)
129{
130 const openvdb::Vec3d half_voxel(0.5, 0.5, 0.5);
131 const openvdb::Vec3d voxel_spacing(double(spacing.x) / grid.voxelSize().x(),
132 double(spacing.y) / grid.voxelSize().y(),
133 double(spacing.z) / grid.voxelSize().z());
134
135 /* Abort if spacing is zero. */
136 const double min_spacing = std::min({voxel_spacing.x(), voxel_spacing.y(), voxel_spacing.z()});
137 if (std::abs(min_spacing) < 0.0001) {
138 return;
139 }
140
141 /* Iterate through tiles and voxels on the grid. */
142 for (openvdb::FloatGrid::ValueOnCIter cell = grid.cbeginValueOn(); cell; ++cell) {
143 /* Check if the cell's value meets the minimum threshold. */
144 if (cell.getValue() < threshold) {
145 continue;
146 }
147 /* Compute the bounding box of each tile/voxel. */
148 const openvdb::CoordBBox bbox = cell.getBoundingBox();
149 const openvdb::Vec3d box_min = bbox.min().asVec3d() - half_voxel;
150 const openvdb::Vec3d box_max = bbox.max().asVec3d() + half_voxel;
151
152 /* Pick a starting point rounded up to the nearest possible point. */
153 double abs_spacing_x = std::abs(voxel_spacing.x());
154 double abs_spacing_y = std::abs(voxel_spacing.y());
155 double abs_spacing_z = std::abs(voxel_spacing.z());
156 const openvdb::Vec3d start(ceil(box_min.x() / abs_spacing_x) * abs_spacing_x,
157 ceil(box_min.y() / abs_spacing_y) * abs_spacing_y,
158 ceil(box_min.z() / abs_spacing_z) * abs_spacing_z);
159
160 /* Iterate through all possible points in box. */
161 for (double x = start.x(); x < box_max.x(); x += abs_spacing_x) {
162 for (double y = start.y(); y < box_max.y(); y += abs_spacing_y) {
163 for (double z = start.z(); z < box_max.z(); z += abs_spacing_z) {
164 /* Transform with grid matrix and add point. */
165 const openvdb::Vec3d idx_pos(x, y, z);
166 const openvdb::Vec3d local_pos = grid.indexToWorld(idx_pos);
167 r_positions.append({float(local_pos.x()), float(local_pos.y()), float(local_pos.z())});
168 }
169 }
170 }
171 }
172}
173
174#endif /* WITH_OPENVDB */
175
177{
178#ifdef WITH_OPENVDB
180 "Grid"_ustr);
181 if (!volume_grid) {
183 return;
184 }
185
186 bke::VolumeTreeAccessToken tree_token;
187 const openvdb::GridBase &base_grid = volume_grid.grid(tree_token);
188 if (!base_grid.isType<openvdb::FloatGrid>()) {
190 return;
191 }
192 const openvdb::FloatGrid &grid = static_cast<const openvdb::FloatGrid &>(base_grid);
193
194 const DistributeMode mode = DistributeMode(params.node().custom1);
195
196 float density;
197 int seed;
198 float3 spacing{0, 0, 0};
199 float threshold;
200 if (mode == DistributeMode::Random) {
201 density = params.extract_input<float>("Density"_ustr);
202 seed = params.extract_input<int>("Seed"_ustr);
203 }
204 else if (mode == DistributeMode::Grid) {
205 spacing = params.extract_input<float3>("Spacing"_ustr);
206 threshold = params.extract_input<float>("Threshold"_ustr);
207 }
208
209 Vector<float3> positions;
210 switch (mode) {
212 point_scatter_density_random(grid, density, seed, positions);
213 break;
215 point_scatter_density_grid(grid, spacing, threshold, positions);
216 break;
217 }
218
220 pointcloud->positions_for_write().copy_from(positions);
221
223
224 params.set_output("Points"_ustr, GeometrySet::from_pointcloud(pointcloud));
225#else
227#endif
228}
229
230static void node_rna(StructRNA *srna)
231{
232 static const EnumPropertyItem mode_items[] = {
234 "DENSITY_RANDOM",
235 0,
236 "Random",
237 "Distribute points randomly inside of the volume"},
239 "DENSITY_GRID",
240 0,
241 "Grid",
242 "Distribute the points in a grid pattern inside of the volume"},
243 {0, nullptr, 0, nullptr, nullptr},
244 };
245
247 "mode",
248 "Distribution Method",
249 "Method to use for scattering points",
250 mode_items,
253}
254
255static void node_register()
256{
257 static bke::bNodeType ntype;
259 &ntype, "GeometryNodeDistributePointsInGrid"_ustr, GEO_NODE_DISTRIBUTE_POINTS_IN_GRID);
260 ntype.ui_name = "Distribute Points in Grid";
261 ntype.ui_description = "Generate points inside a volume grid";
262 ntype.enum_name_legacy = "DISTRIBUTE_POINTS_IN_GRID";
264 ntype.initfunc = node_init;
266 ntype.declare = node_declare;
270
271 node_rna(ntype.rna_ext.srna);
272}
274
275} // namespace blender::nodes::node_geo_distribute_points_in_grid_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_DISTRIBUTE_POINTS_IN_GRID
General operations for point clouds.
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
int64_t size() const
void append(const T &value)
T extract_input(const UString identifier)
void set_output(const UString identifier, T &&value)
#define FLT_MAX
#define ceil
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
void debug_randomize_point_order(PointCloud *pointcloud)
Definition randomize.cc:258
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
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 node_geo_exec_with_missing_openvdb(GeoNodeExecParams &params)
PointCloud * BKE_pointcloud_new_nomain(PointCloudType type, int totpoint)
VecBase< float, 3 > float3
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
signed short int16_t
Definition BKE_text.h:77
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define min(a, b)
Definition sort.cc:38
static constexpr int _180
Definition BKE_node.hh:247
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
NodeDeclareFunction declare
Definition BKE_node.hh:393
static GeometrySet from_pointcloud(PointCloud *pointcloud, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
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)
float z
Definition sky_math.h:136
float y
Definition sky_math.h:136
float x
Definition sky_math.h:136