34# include <openvdb/openvdb.h>
35# include <openvdb/points/PointConversion.h>
36# include <openvdb/points/PointTransfer.h>
37# include <openvdb/tools/LevelSetUtil.h>
38# include <openvdb/tools/Morphology.h>
39# include <openvdb/tools/ParticlesToLevelSet.h>
40# include <openvdb/tools/PointIndexGrid.h>
47 switch (rasterize_type) {
59 switch (rasterize_type) {
72class OpenVDBParticleList {
74 using PosType = openvdb::Vec3R;
79 float voxel_size_inv_;
84 const float voxel_size)
85 : positions_(positions), radii_(radii), voxel_size_inv_(
math::rcp(voxel_size))
92 return size_t(positions_.
size());
95 void getPos(
size_t n, openvdb::Vec3R &xyz)
const
97 const float3 pos = positions_[n] * voxel_size_inv_;
101 void getPosRad(
size_t n, openvdb::Vec3R &xyz, openvdb::Real &radius)
const
103 this->getPos(n, xyz);
104 radius = radii_[n] * voxel_size_inv_;
108static openvdb::FloatGrid::Ptr points_to_sdf_grid_impl(
const Span<float3> positions,
109 const Span<float> radii,
110 const float voxel_size)
118 openvdb::FloatGrid::Ptr new_grid = openvdb::FloatGrid::create(1.0f);
121 openvdb::tools::ParticlesToLevelSet op{*new_grid};
124 op.setRmax(std::numeric_limits<float>::max());
125 OpenVDBParticleList particles{positions, radii, voxel_size};
126 op.rasterizeSpheres(particles);
129 new_grid->transform().postScale(voxel_size);
130 new_grid->setGridClass(openvdb::GRID_LEVEL_SET);
135bke::VolumeGrid<float> points_to_sdf_grid(
const Span<float3> positions,
136 const Span<float> radii,
137 const float voxel_size)
139 return bke::VolumeGrid<float>(points_to_sdf_grid_impl(positions, radii, voxel_size));
142bke::VolumeGridData *fog_volume_grid_add_from_points(Volume *volume,
143 const StringRefNull name,
144 const Span<float3> positions,
145 const Span<float> radii,
146 const float voxel_size,
149 openvdb::FloatGrid::Ptr new_grid = points_to_sdf_grid_impl(positions, radii, voxel_size);
150 new_grid->setGridClass(openvdb::GRID_FOG_VOLUME);
154 openvdb::tools::sdfToFogVolume(*new_grid);
157 openvdb::tools::foreach(new_grid->beginValueOn(),
158 [&](
const openvdb::FloatGrid::ValueOnIter &iter) {
159 iter.modifyValue([&](float &value) { value *= density; });
162 return BKE_volume_grid_add_vdb(*volume, name, std::move(new_grid));
165bool is_point_attribute_grid_supported(
const CPPType &cpp_type)
167 return ELEM(cpp_type,
168 CPPType::get<bool>(),
169 CPPType::get<float>(),
171 CPPType::get<int64_t>(),
172 CPPType::get<float3>(),
173 CPPType::get<int3>(),
174 CPPType::get<float4x4>());
178static std::string sanitize_name_for_openvdb(
const StringRef name)
181 std::string
result = name;
185 return !(isalnum(c) || (c ==
'_') || (c ==
'|') || (c ==
':'));
192[[maybe_unused]]
static std::string add_unique_vdb_attribute_name(
193 const StringRef name, VectorSet<std::string> &used_names)
195 const std::string vdb_base_name = sanitize_name_for_openvdb(name);
197 std::string vdb_name = vdb_base_name;
199 while (!used_names.add(vdb_name)) {
201 vdb_name = vdb_base_name +
"_" + std::to_string(duplicates);
206static std::optional<StringRef> find_vdb_attribute_name(
const PointAttributeNameMap &attribute_map,
207 const StringRef name)
209 for (
const std::pair<std::string, std::string> &name_pair : attribute_map) {
210 if (name_pair.first == name) {
211 return name_pair.second;
218template<
typename T>
class PointAttributeSpan {
223 using type_traits = bke::VolumeGridTraits<T>;
225 using value_type =
typename type_traits::PrimitiveType;
226 using PosType = value_type;
228 PointAttributeSpan(
const Span<T> data) : data_(
data) {}
234 void getPos(
size_t n, PosType &xyz)
const
236 xyz = type_traits::to_openvdb(data_[n]);
238 void get(value_type &value,
size_t n)
const
240 value = type_traits::to_openvdb(data_[n]);
242 void get(value_type &value,
size_t n, openvdb::Index m)
const
244 value = type_traits::to_openvdb(data_[n + m]);
248MappedPointDataGrid points_to_point_data_grid(
const Span<float3> positions,
255 const PointAttributeSpan positions_wrapper(positions);
260 const openvdb::math::Transform vdb_transform = BKE_volume_transform_to_openvdb(
transform);
261 const openvdb::math::Transform vdb_transform_cell_centered = BKE_volume_transform_to_openvdb(
262 transform_cell_centered);
265 openvdb::tools::PointIndexGrid::Ptr point_index_grid =
266 openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>(
267 positions_wrapper, vdb_transform_cell_centered);
269 openvdb::points::PointDataGrid::Ptr point_data_grid;
270 VectorSet<std::string> used_names;
271 Vector<std::pair<std::string, std::string>> attribute_map;
275 threading::isolate_task([&]() {
279 point_data_grid = openvdb::points::createPointDataGrid<openvdb::points::NullCodec,
280 openvdb::points::PointDataGrid>(
281 *point_index_grid, positions_wrapper, vdb_transform);
283 for (
const PointDataGridAttributeInfo &info : attributes) {
284 const CPPType &cpp_type = info.data.type();
285 bke::attribute_math::to_static_type(cpp_type, [&]<
typename ValueT>() {
286 using type_traits =
typename bke::VolumeGridTraits<ValueT>;
288 if constexpr (!std::is_same_v<typename type_traits::PrimitiveType, void>) {
294 using Codec = openvdb::points::NullCodec;
295 using AttributeArray =
296 openvdb::points::TypedAttributeArray<typename type_traits::PrimitiveType, Codec>;
297 if (!AttributeArray::isRegistered()) {
298 AttributeArray::registerType();
301 const std::string vdb_name = add_unique_vdb_attribute_name(info.name, used_names);
302 attribute_map.append_as(info.name, vdb_name);
304 openvdb::NamePair point_data_attribute = AttributeArray::attributeType();
305 openvdb::points::appendAttribute(
306 point_data_grid->tree(), vdb_name, point_data_attribute);
308 const PointAttributeSpan data_wrapper(info.data.typed<ValueT>());
309 openvdb::points::populateAttribute(
310 point_data_grid->tree(), point_index_grid->tree(), vdb_name, data_wrapper);
316 return {bke::GVolumeGrid(std::move(point_data_grid)), std::move(attribute_map)};
319MappedPointDataGrid points_to_point_data_grid(
const VArray<float3> positions,
320 const bke::AttributeAccessor &attributes,
321 const bke::AttributeFilter &attribute_filter,
324 const VArraySpan<float3> positions_span = positions;
326 Vector<GVArraySpan> attribute_arrays;
327 Vector<PointDataGridAttributeInfo> attributes_info;
328 MappedPointDataGrid
result;
329 attributes.foreach_attribute([&](
const bke::AttributeIter &iter) {
330 if (attribute_filter.allow_skip(iter.name)) {
333 const CPPType &cpp_type = bke::attribute_type_to_cpp_type(iter.data_type);
334 if (!is_point_attribute_grid_supported(cpp_type)) {
337 const bke::GAttributeReader reader = iter.get(bke::AttrDomain::Point);
341 attribute_arrays.append(*reader);
342 attributes_info.append({iter.name, attribute_arrays.last()});
344 result = points_to_point_data_grid(positions_span, attributes_info,
transform);
350namespace kernel_functions {
360inline int kernel_range(
const KernelType kernel_type)
362 using namespace geometry::grid_sampling;
364 switch (kernel_type) {
365 case KernelType::NearestPoint:
366 return std::max(NearestPointKernel::samples_left, NearestPointKernel::samples_right);
367 case KernelType::Linear:
368 return std::max(LinearKernel::samples_left, LinearKernel::samples_right);
369 case KernelType::Quadratic:
370 return std::max(QuadraticBSplineKernel::samples_left, QuadraticBSplineKernel::samples_right);
371 case KernelType::Cubic:
372 return std::max(CubicBSplineKernel::samples_left, CubicBSplineKernel::samples_right);
379inline float kernel_eval_component(
const KernelType kernel_type,
const float t)
381 switch (kernel_type) {
382 case KernelType::NearestPoint:
383 return geometry::grid_sampling::NearestPointKernel::weight(t);
384 case KernelType::Linear:
385 return geometry::grid_sampling::LinearKernel::weight(t);
386 case KernelType::Quadratic:
387 return geometry::grid_sampling::QuadraticBSplineKernel::weight(t);
388 case KernelType::Cubic:
389 return geometry::grid_sampling::CubicBSplineKernel::weight(t);
395inline float kernel_eval(
const KernelType kernel_type,
const float3 &v)
397 return kernel_eval_component(kernel_type,
v.x) * kernel_eval_component(kernel_type,
v.y) *
398 kernel_eval_component(kernel_type,
v.z);
435template<
typename AttributeT,
typename Gr
idValueT>
436struct KernelTransferBase :
public openvdb::points::TransformTransfer,
437 public openvdb::points::VolumeTransfer<
438 typename bke::VolumeGridTraits<GridValueT>::TreeType> {
439 using AttributeTraits = bke::VolumeGridTraits<AttributeT>;
440 using AttributeType =
typename AttributeTraits::PrimitiveType;
442 using GridTraits = bke::VolumeGridTraits<GridValueT>;
443 using TreeType =
typename GridTraits::TreeType;
444 using GridType = openvdb::Grid<TreeType>;
445 using GridValueType =
typename GridTraits::PrimitiveType;
446 using NodeMaskType =
typename TreeType::LeafNodeType::NodeMaskType;
448 static const int32_t LOG2DIM = TreeType::LeafNodeType::LOG2DIM;
449 static const int32_t DIM = TreeType::LeafNodeType::DIM;
455 StringRef value_attribute_;
457 std::optional<openvdb::points::AttributeHandle<openvdb::Vec3f>> position_handle_;
459 std::optional<openvdb::points::AttributeHandle<AttributeType>> value_handle_;
461 KernelTransferBase(
const KernelType kernel_type,
462 const openvdb::points::PointDataGrid &source,
463 const StringRef value_attribute,
466 openvdb::points::VolumeTransfer<TreeType>(dest.tree()),
467 kernel_type_(kernel_type),
468 kernel_range_(kernel_functions::kernel_range(kernel_type)),
469 value_attribute_(value_attribute)
473 KernelTransferBase(
const KernelTransferBase &other)
474 : TransformTransfer(other),
475 openvdb::points::VolumeTransfer<TreeType>(other),
476 kernel_type_(other.kernel_type_),
477 kernel_range_(other.kernel_range_),
478 value_attribute_(other.value_attribute_)
488 openvdb::Int32 range(
const openvdb::Coord & ,
size_t )
const
490 return kernel_range_;
493 AttributeType
get_value(
const openvdb::Index point_index)
495 return value_handle_->get(point_index);
498 bool startPointLeaf(
const openvdb::points::PointDataTree::LeafNodeType &leaf)
500 position_handle_.emplace(
501 openvdb::points::AttributeHandle<openvdb::Vec3f>(leaf.constAttributeArray(
"P")));
503 BLI_assert(leaf.hasAttribute(value_attribute_));
504 value_handle_.emplace(openvdb::points::AttributeHandle<AttributeType>(
505 leaf.constAttributeArray(value_attribute_)));
517 template<
typename ValueFn>
518 void add_points_to_voxels(
const openvdb::Coord &ijk,
519 const IndexRange point_index_range,
520 const openvdb::CoordBBox &target_bounds,
524 openvdb::CoordBBox intersect_box(ijk.offsetBy(-kernel_range_), ijk.offsetBy(kernel_range_));
525 intersect_box.intersect(target_bounds);
526 if (intersect_box.empty()) {
530 auto *
const data = this->
template buffer<0>();
533 for (
const openvdb::Index point_index : point_index_range) {
534 const openvdb::Vec3d source_position = ijk.asVec3d() +
535 this->position_handle_->get(point_index);
536 const openvdb::Vec3d target_position = this->transformSourceToTarget(source_position);
538 const openvdb::Coord &a(intersect_box.min());
539 const openvdb::Coord &
b(intersect_box.max());
540 for (openvdb::Coord c = a; c.x() <=
b.x(); ++c.x()) {
541 const openvdb::Index i = ((c.x() & (DIM - 1u)) << 2 * LOG2DIM);
542 for (c.y() = a.y(); c.y() <=
b.y(); ++c.y()) {
543 const openvdb::Index j = ((c.y() & (DIM - 1u)) << LOG2DIM);
544 for (c.z() = a.z(); c.z() <=
b.z(); ++c.z()) {
546 const openvdb::Index offset = i + j + (c.z() & (DIM - 1u));
547 if (!
mask.isOn(offset)) {
552 openvdb::Vec3f(c.asVec3d() - target_position).asV());
553 data[offset] += value_fn(point_index, kernel_distance);
560 bool endPointLeaf(
const openvdb::points::PointDataTree::LeafNodeType & )
567 bool finalize(
const openvdb::Coord & ,
size_t )
575template<
typename AttributeT,
typename Gr
idValueT>
576struct ValueTransfer :
public KernelTransferBase<AttributeT, GridValueT> {
577 using Base = KernelTransferBase<AttributeT, GridValueT>;
578 using AttributeType =
typename Base::AttributeType;
580 using KernelTransferBase<AttributeT, GridValueT>::KernelTransferBase;
582 void rasterizePoints(
const openvdb::Coord &ijk,
583 const openvdb::Index point_index_begin,
584 const openvdb::Index point_index_end,
585 const openvdb::CoordBBox &target_bounds)
587 this->add_points_to_voxels(
589 IndexRange::from_begin_end(point_index_begin, point_index_end),
591 [&](
const openvdb::Index point_index,
const float3 &kernel_distance) {
592 const AttributeType source_value = this->
get_value(point_index);
593 const float weight = kernel_functions::kernel_eval(this->kernel_type(), kernel_distance);
594 return weight * source_value;
602template<
typename Gr
idType>
603static typename GridType::Ptr prepare_destination_grid(
604 const openvdb::points::PointDataGrid &point_data_grid,
606 const KernelType kernel_type)
608 typename std::shared_ptr<GridType> dst_grid = GridType::create();
609 dst_grid->transform() = BKE_volume_transform_to_openvdb(
transform);
615 dst_grid->tree().topologyUnion(point_data_grid.tree());
622 const int max_offset = kernel_functions::kernel_range(kernel_type);
623 openvdb::tools::dilateActiveValues(dst_grid->tree(),
625 openvdb::tools::NN_FACE_EDGE_VERTEX,
626 openvdb::tools::TilePolicy::PRESERVE_TILES,
634 dst_grid->tree().voxelizeActiveTiles(
true);
640template<
typename AttributeT,
typename Gr
idValueT,
typename TransferT>
641static bke::GVolumeGrid points_rasterize_with_static_type(
642 const openvdb::points::PointDataGrid &point_data_grid,
643 const StringRef value_attribute,
644 const PointRasterizeAttributeInfo & ,
646 const KernelType kernel_type)
648 using GridTraits = bke::VolumeGridTraits<GridValueT>;
649 using TreeType =
typename GridTraits::TreeType;
650 using GridType = openvdb::Grid<TreeType>;
652 typename std::shared_ptr<GridType> dst_grid;
658 dst_grid = prepare_destination_grid<GridType>(point_data_grid,
transform, kernel_type);
666 TransferT
transfer(kernel_type, point_data_grid, value_attribute, *dst_grid);
667 openvdb::points::rasterize(point_data_grid, transfer);
674 dst_grid->setGridClass(openvdb::GridClass::GRID_FOG_VOLUME);
678 return bke::GVolumeGrid(std::move(dst_grid));
683static bke::GVolumeGrid points_attribute_rasterize(
684 const openvdb::points::PointDataGrid &point_data_grid,
685 const KernelType kernel_type,
686 const StringRef value_attribute,
687 const PointRasterizeAttributeInfo &attribute_info,
692 switch (attribute_info.type) {
693 case PointRasterizeType::Scalar:
694 result = points_rasterize_with_static_type<float, float, ValueTransfer<float, float>>(
695 point_data_grid, value_attribute, attribute_info,
transform, kernel_type);
697 case PointRasterizeType::Vector:
698 result = points_rasterize_with_static_type<float3, float3, ValueTransfer<float3, float3>>(
699 point_data_grid, value_attribute, attribute_info,
transform, kernel_type);
706void points_rasterize(
const MappedPointDataGrid &point_data_grid,
707 const KernelType kernel_type,
710 MutableSpan<bke::GVolumeGrid> r_attribute_grids)
718 if (!point_data_grid.grid || point_data_grid.grid->grid_type() != VOLUME_GRID_POINTS) {
721 bke::VolumeTreeAccessToken access_token;
722 const openvdb::points::PointDataGrid::ConstPtr vdb_point_data_grid =
723 openvdb::GridBase::grid<openvdb::points::PointDataGrid>(
724 point_data_grid.grid->grid_ptr(access_token));
727 for (
const int i : point_attributes.
index_range()) {
728 const PointRasterizeAttributeInfo &
attribute = point_attributes[i];
733 const std::optional<std::string> vdb_attribute_name = find_vdb_attribute_name(
734 point_data_grid.attribute_map,
attribute.name);
736 r_attribute_grids[i] = points_attribute_rasterize(
#define SCOPED_TIMER(name)
#define BLI_assert_unreachable()
SIMD_FORCE_INLINE btVector3 transform(const btVector3 &point) const
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
constexpr int64_t size() const
constexpr IndexRange index_range() const
static const CPPType & get()
constexpr int64_t size() const
VecBase< float, 3 > float3
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
int size(const AssetLibraryReference *library_reference)
const CPPType & points_rasterize_grid_type(const PointRasterizeType rasterize_type)
const CPPType & points_rasterize_attribute_type(const PointRasterizeType rasterize_type)
std::shared_ptr< const T > get(const GenericKey &key, FunctionRef< std::unique_ptr< T >()> compute_fn)
constexpr StringRefNull radius
int get_value(int colorid)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
ATTR_WARN_UNUSED_RESULT const BMVert * v
BMesh const char void * data
VecBase< float, 3 > float3
bool BKE_volume_voxel_size_valid(const float3 &voxel_size)