HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MeshToVolume.h
Go to the documentation of this file.
1 ///////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4 //
5 // All rights reserved. This software is distributed under the
6 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
7 //
8 // Redistributions of source code must retain the above copyright
9 // and license notice and the following restrictions and disclaimer.
10 //
11 // * Neither the name of DreamWorks Animation nor the names of
12 // its contributors may be used to endorse or promote products derived
13 // from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
20 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 // IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
27 // LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
28 //
29 ///////////////////////////////////////////////////////////////////////////
30 
31 /// @file MeshToVolume.h
32 ///
33 /// @brief Convert polygonal meshes that consist of quads and/or triangles
34 /// into signed or unsigned distance field volumes.
35 ///
36 /// @note The signed distance field conversion requires a closed surface
37 /// but not necessarily a manifold surface. Supports surfaces with
38 /// self intersections and degenerate faces and is independent of
39 /// mesh surface normals / polygon orientation.
40 ///
41 /// @author Mihai Alden
42 
43 #ifndef OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
44 #define OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
45 
46 #include <openvdb/Platform.h> // for OPENVDB_HAS_CXX11
47 #include <openvdb/Types.h>
48 #include <openvdb/math/FiniteDifference.h> // for GodunovsNormSqrd
49 #include <openvdb/math/Proximity.h> // for closestPointOnTriangleToPoint
51 #include <openvdb/util/Util.h>
52 
53 #include "ChangeBackground.h"
54 #include "Prune.h" // for pruneInactive and pruneLevelSet
55 #include "SignedFloodFill.h" // for signedFloodFillWithValues
56 
57 #include <tbb/blocked_range.h>
58 #include <tbb/enumerable_thread_specific.h>
59 #include <tbb/parallel_for.h>
60 #include <tbb/parallel_reduce.h>
61 #include <tbb/partitioner.h>
62 #include <tbb/task_group.h>
63 #include <tbb/task_scheduler_init.h>
64 
65 #include <hboost/mpl/at.hpp>
66 #include <hboost/mpl/int.hpp>
67 #include <hboost/mpl/size.hpp>
68 
69 #include <algorithm> // for std::sort()
70 #include <cmath> // for std::isfinite(), std::isnan()
71 #include <deque>
72 #include <limits>
73 #include <memory>
74 #include <sstream>
75 #include <type_traits>
76 #include <vector>
77 
78 namespace openvdb {
80 namespace OPENVDB_VERSION_NAME {
81 namespace tools {
82 
83 
84 ////////////////////////////////////////
85 
86 
87 /// @brief Mesh to volume conversion flags
89 
90  /// Switch from the default signed distance field conversion that classifies
91  /// regions as either inside or outside the mesh boundary to a unsigned distance
92  /// field conversion that only computes distance values. This conversion type
93  /// does not require a closed watertight mesh.
95 
96  /// Disable the cleanup step that removes voxels created by self intersecting
97  /// portions of the mesh.
99 
100  /// Disable the distance renormalization step that smooths out bumps caused
101  /// by self intersecting or overlapping portions of the mesh
103 
104  /// Disable the cleanup step that removes active voxels that exceed the
105  /// narrow band limits. (Only relevant for small limits)
107 };
108 
109 
110 /// @brief Convert polygonal meshes that consist of quads and/or triangles into
111 /// signed or unsigned distance field volumes.
112 ///
113 /// @note Requires a closed surface but not necessarily a manifold surface.
114 /// Supports surfaces with self intersections and degenerate faces
115 /// and is independent of mesh surface normals.
116 ///
117 /// @interface MeshDataAdapter
118 /// Expected interface for the MeshDataAdapter class
119 /// @code
120 /// struct MeshDataAdapter {
121 /// size_t polygonCount() const; // Total number of polygons
122 /// size_t pointCount() const; // Total number of points
123 /// size_t vertexCount(size_t n) const; // Vertex count for polygon n
124 ///
125 /// // Return position pos in local grid index space for polygon n and vertex v
126 /// void getIndexSpacePoint(size_t n, size_t v, openvdb::Vec3d& pos) const;
127 /// };
128 /// @endcode
129 ///
130 /// @param mesh mesh data access class that conforms to the MeshDataAdapter
131 /// interface
132 /// @param transform world-to-index-space transform
133 /// @param exteriorBandWidth exterior narrow band width in voxel units
134 /// @param interiorBandWidth interior narrow band width in voxel units
135 /// (set to std::numeric_limits<float>::max() to fill object
136 /// interior with distance values)
137 /// @param flags optional conversion flags defined in @c MeshToVolumeFlags
138 /// @param polygonIndexGrid optional grid output that will contain the closest-polygon
139 /// index for each voxel in the narrow band region
140 template <typename GridType, typename MeshDataAdapter>
141 inline typename GridType::Ptr
143  const MeshDataAdapter& mesh,
144  const math::Transform& transform,
145  float exteriorBandWidth = 3.0f,
146  float interiorBandWidth = 3.0f,
147  int flags = 0,
148  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
149 
150 
151 /// @brief Convert polygonal meshes that consist of quads and/or triangles into
152 /// signed or unsigned distance field volumes.
153 ///
154 /// @param interrupter a callback to interrupt the conversion process that conforms
155 /// to the util::NullInterrupter interface
156 /// @param mesh mesh data access class that conforms to the MeshDataAdapter
157 /// interface
158 /// @param transform world-to-index-space transform
159 /// @param exteriorBandWidth exterior narrow band width in voxel units
160 /// @param interiorBandWidth interior narrow band width in voxel units (set this value to
161 /// std::numeric_limits<float>::max() to fill interior regions
162 /// with distance values)
163 /// @param flags optional conversion flags defined in @c MeshToVolumeFlags
164 /// @param polygonIndexGrid optional grid output that will contain the closest-polygon
165 /// index for each voxel in the active narrow band region
166 template <typename GridType, typename MeshDataAdapter, typename Interrupter>
167 inline typename GridType::Ptr
169  Interrupter& interrupter,
170  const MeshDataAdapter& mesh,
171  const math::Transform& transform,
172  float exteriorBandWidth = 3.0f,
173  float interiorBandWidth = 3.0f,
174  int flags = 0,
175  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
176 
177 
178 ////////////////////////////////////////
179 
180 
181 /// @brief Contiguous quad and triangle data adapter class
182 ///
183 /// @details PointType and PolygonType must provide element access
184 /// through the square brackets operator.
185 /// @details Points are assumed to be in local grid index space.
186 /// @details The PolygonType tuple can have either three or four components
187 /// this property must be specified in a static member variable
188 /// named @c size, similar to the math::Tuple class.
189 /// @details A four component tuple can represent a quads or a triangle
190 /// if the fourth component set to @c util::INVALID_INDEX
191 template<typename PointType, typename PolygonType>
193 
194  QuadAndTriangleDataAdapter(const std::vector<PointType>& points,
195  const std::vector<PolygonType>& polygons)
196  : mPointArray(points.empty() ? nullptr : &points[0])
197  , mPointArraySize(points.size())
198  , mPolygonArray(polygons.empty() ? nullptr : &polygons[0])
199  , mPolygonArraySize(polygons.size())
200  {
201  }
202 
203  QuadAndTriangleDataAdapter(const PointType * pointArray, size_t pointArraySize,
204  const PolygonType* polygonArray, size_t polygonArraySize)
205  : mPointArray(pointArray)
206  , mPointArraySize(pointArraySize)
207  , mPolygonArray(polygonArray)
208  , mPolygonArraySize(polygonArraySize)
209  {
210  }
211 
212  size_t polygonCount() const { return mPolygonArraySize; }
213  size_t pointCount() const { return mPointArraySize; }
214 
215  /// @brief Vertex count for polygon @a n
216  size_t vertexCount(size_t n) const {
217  return (PolygonType::size == 3 || mPolygonArray[n][3] == util::INVALID_IDX) ? 3 : 4;
218  }
219 
220  /// @brief Returns position @a pos in local grid index space
221  /// for polygon @a n and vertex @a v
222  void getIndexSpacePoint(size_t n, size_t v, Vec3d& pos) const {
223  const PointType& p = mPointArray[mPolygonArray[n][int(v)]];
224  pos[0] = double(p[0]);
225  pos[1] = double(p[1]);
226  pos[2] = double(p[2]);
227  }
228 
229 private:
230  PointType const * const mPointArray;
231  size_t const mPointArraySize;
232  PolygonType const * const mPolygonArray;
233  size_t const mPolygonArraySize;
234 }; // struct QuadAndTriangleDataAdapter
235 
236 
237 ////////////////////////////////////////
238 
239 
240 // Convenience functions for the mesh to volume converter that wrap stl containers.
241 //
242 // Note the meshToVolume() method declared above is more flexible and better suited
243 // for arbitrary data structures.
244 
245 
246 /// @brief Convert a triangle mesh to a level set volume.
247 ///
248 /// @return a grid of type @c GridType containing a narrow-band level set
249 /// representation of the input mesh.
250 ///
251 /// @throw TypeError if @c GridType is not scalar or not floating-point
252 ///
253 /// @note Requires a closed surface but not necessarily a manifold surface.
254 /// Supports surfaces with self intersections and degenerate faces
255 /// and is independent of mesh surface normals.
256 ///
257 /// @param xform transform for the output grid
258 /// @param points list of world space point positions
259 /// @param triangles triangle index list
260 /// @param halfWidth half the width of the narrow band, in voxel units
261 template<typename GridType>
262 inline typename GridType::Ptr
264  const openvdb::math::Transform& xform,
265  const std::vector<Vec3s>& points,
266  const std::vector<Vec3I>& triangles,
267  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
268 
269 /// Adds support for a @a interrupter callback used to cancel the conversion.
270 template<typename GridType, typename Interrupter>
271 inline typename GridType::Ptr
273  Interrupter& interrupter,
274  const openvdb::math::Transform& xform,
275  const std::vector<Vec3s>& points,
276  const std::vector<Vec3I>& triangles,
277  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
278 
279 
280 /// @brief Convert a quad mesh to a level set volume.
281 ///
282 /// @return a grid of type @c GridType containing a narrow-band level set
283 /// representation of the input mesh.
284 ///
285 /// @throw TypeError if @c GridType is not scalar or not floating-point
286 ///
287 /// @note Requires a closed surface but not necessarily a manifold surface.
288 /// Supports surfaces with self intersections and degenerate faces
289 /// and is independent of mesh surface normals.
290 ///
291 /// @param xform transform for the output grid
292 /// @param points list of world space point positions
293 /// @param quads quad index list
294 /// @param halfWidth half the width of the narrow band, in voxel units
295 template<typename GridType>
296 inline typename GridType::Ptr
298  const openvdb::math::Transform& xform,
299  const std::vector<Vec3s>& points,
300  const std::vector<Vec4I>& quads,
301  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
302 
303 /// Adds support for a @a interrupter callback used to cancel the conversion.
304 template<typename GridType, typename Interrupter>
305 inline typename GridType::Ptr
307  Interrupter& interrupter,
308  const openvdb::math::Transform& xform,
309  const std::vector<Vec3s>& points,
310  const std::vector<Vec4I>& quads,
311  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
312 
313 
314 /// @brief Convert a triangle and quad mesh to a level set volume.
315 ///
316 /// @return a grid of type @c GridType containing a narrow-band level set
317 /// representation of the input mesh.
318 ///
319 /// @throw TypeError if @c GridType is not scalar or not floating-point
320 ///
321 /// @note Requires a closed surface but not necessarily a manifold surface.
322 /// Supports surfaces with self intersections and degenerate faces
323 /// and is independent of mesh surface normals.
324 ///
325 /// @param xform transform for the output grid
326 /// @param points list of world space point positions
327 /// @param triangles triangle index list
328 /// @param quads quad index list
329 /// @param halfWidth half the width of the narrow band, in voxel units
330 template<typename GridType>
331 inline typename GridType::Ptr
333  const openvdb::math::Transform& xform,
334  const std::vector<Vec3s>& points,
335  const std::vector<Vec3I>& triangles,
336  const std::vector<Vec4I>& quads,
337  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
338 
339 /// Adds support for a @a interrupter callback used to cancel the conversion.
340 template<typename GridType, typename Interrupter>
341 inline typename GridType::Ptr
343  Interrupter& interrupter,
344  const openvdb::math::Transform& xform,
345  const std::vector<Vec3s>& points,
346  const std::vector<Vec3I>& triangles,
347  const std::vector<Vec4I>& quads,
348  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
349 
350 
351 /// @brief Convert a triangle and quad mesh to a signed distance field
352 /// with an asymmetrical narrow band.
353 ///
354 /// @return a grid of type @c GridType containing a narrow-band signed
355 /// distance field representation of the input mesh.
356 ///
357 /// @throw TypeError if @c GridType is not scalar or not floating-point
358 ///
359 /// @note Requires a closed surface but not necessarily a manifold surface.
360 /// Supports surfaces with self intersections and degenerate faces
361 /// and is independent of mesh surface normals.
362 ///
363 /// @param xform transform for the output grid
364 /// @param points list of world space point positions
365 /// @param triangles triangle index list
366 /// @param quads quad index list
367 /// @param exBandWidth the exterior narrow-band width in voxel units
368 /// @param inBandWidth the interior narrow-band width in voxel units
369 template<typename GridType>
370 inline typename GridType::Ptr
372  const openvdb::math::Transform& xform,
373  const std::vector<Vec3s>& points,
374  const std::vector<Vec3I>& triangles,
375  const std::vector<Vec4I>& quads,
376  float exBandWidth,
377  float inBandWidth);
378 
379 /// Adds support for a @a interrupter callback used to cancel the conversion.
380 template<typename GridType, typename Interrupter>
381 inline typename GridType::Ptr
383  Interrupter& interrupter,
384  const openvdb::math::Transform& xform,
385  const std::vector<Vec3s>& points,
386  const std::vector<Vec3I>& triangles,
387  const std::vector<Vec4I>& quads,
388  float exBandWidth,
389  float inBandWidth);
390 
391 
392 /// @brief Convert a triangle and quad mesh to an unsigned distance field.
393 ///
394 /// @return a grid of type @c GridType containing a narrow-band unsigned
395 /// distance field representation of the input mesh.
396 ///
397 /// @throw TypeError if @c GridType is not scalar or not floating-point
398 ///
399 /// @note Does not requires a closed surface.
400 ///
401 /// @param xform transform for the output grid
402 /// @param points list of world space point positions
403 /// @param triangles triangle index list
404 /// @param quads quad index list
405 /// @param bandWidth the width of the narrow band, in voxel units
406 template<typename GridType>
407 inline typename GridType::Ptr
409  const openvdb::math::Transform& xform,
410  const std::vector<Vec3s>& points,
411  const std::vector<Vec3I>& triangles,
412  const std::vector<Vec4I>& quads,
413  float bandWidth);
414 
415 /// Adds support for a @a interrupter callback used to cancel the conversion.
416 template<typename GridType, typename Interrupter>
417 inline typename GridType::Ptr
419  Interrupter& interrupter,
420  const openvdb::math::Transform& xform,
421  const std::vector<Vec3s>& points,
422  const std::vector<Vec3I>& triangles,
423  const std::vector<Vec4I>& quads,
424  float bandWidth);
425 
426 
427 ////////////////////////////////////////
428 
429 
430 /// @brief Return a grid of type @c GridType containing a narrow-band level set
431 /// representation of a box.
432 ///
433 /// @param bbox a bounding box in world units
434 /// @param xform world-to-index-space transform
435 /// @param halfWidth half the width of the narrow band, in voxel units
436 template<typename GridType, typename VecType>
437 inline typename GridType::Ptr
439  const openvdb::math::Transform& xform,
440  typename VecType::ValueType halfWidth = LEVEL_SET_HALF_WIDTH);
441 
442 
443 ////////////////////////////////////////
444 
445 
446 /// @brief Traces the exterior voxel boundary of closed objects in the input
447 /// volume @a tree. Exterior voxels are marked with a negative sign,
448 /// voxels with a value below @c 0.75 are left unchanged and act as
449 /// the boundary layer.
450 ///
451 /// @note Does not propagate sign information into tile regions.
452 template <typename FloatTreeT>
453 inline void
454 traceExteriorBoundaries(FloatTreeT& tree);
455 
456 
457 ////////////////////////////////////////
458 
459 
460 /// @brief Extracts and stores voxel edge intersection data from a mesh.
462 {
463 public:
464 
465  //////////
466 
467  ///@brief Internal edge data type.
468  struct EdgeData {
469  EdgeData(float dist = 1.0)
471  , mXPrim(util::INVALID_IDX)
472  , mYPrim(util::INVALID_IDX)
473  , mZPrim(util::INVALID_IDX)
474  {
475  }
476 
477  //@{
478  /// Required by several of the tree nodes
479  /// @note These methods don't perform meaningful operations.
480  bool operator< (const EdgeData&) const { return false; }
481  bool operator> (const EdgeData&) const { return false; }
482  template<class T> EdgeData operator+(const T&) const { return *this; }
483  template<class T> EdgeData operator-(const T&) const { return *this; }
484  EdgeData operator-() const { return *this; }
485  //@}
486 
487  bool operator==(const EdgeData& rhs) const
488  {
489  return mXPrim == rhs.mXPrim && mYPrim == rhs.mYPrim && mZPrim == rhs.mZPrim;
490  }
491 
494  };
495 
498 
499 
500  //////////
501 
502 
504 
505 
506  /// @brief Threaded method to extract voxel edge data, the closest
507  /// intersection point and corresponding primitive index,
508  /// from the given mesh.
509  ///
510  /// @param pointList List of points in grid index space, preferably unique
511  /// and shared by different polygons.
512  /// @param polygonList List of triangles and/or quads.
513  void convert(const std::vector<Vec3s>& pointList, const std::vector<Vec4I>& polygonList);
514 
515 
516  /// @brief Returns intersection points with corresponding primitive
517  /// indices for the given @c ijk voxel.
518  void getEdgeData(Accessor& acc, const Coord& ijk,
519  std::vector<Vec3d>& points, std::vector<Index32>& primitives);
520 
521  /// @return An accessor of @c MeshToVoxelEdgeData::Accessor type that
522  /// provides random read access to the internal tree.
523  Accessor getAccessor() { return Accessor(mTree); }
524 
525 private:
526  void operator=(const MeshToVoxelEdgeData&) {}
527  TreeType mTree;
528  class GenEdgeData;
529 };
530 
531 
532 ////////////////////////////////////////////////////////////////////////////////
533 ////////////////////////////////////////////////////////////////////////////////
534 
535 
536 // Internal utility objects and implementation details
537 
538 namespace mesh_to_volume_internal {
539 
540 template<typename PointType>
542 
543  TransformPoints(const PointType* pointsIn, PointType* pointsOut,
544  const math::Transform& xform)
545  : mPointsIn(pointsIn), mPointsOut(pointsOut), mXform(&xform)
546  {
547  }
548 
549  void operator()(const tbb::blocked_range<size_t>& range) const {
550 
551  Vec3d pos;
552 
553  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
554 
555  const PointType& wsP = mPointsIn[n];
556  pos[0] = double(wsP[0]);
557  pos[1] = double(wsP[1]);
558  pos[2] = double(wsP[2]);
559 
560  pos = mXform->worldToIndex(pos);
561 
562  PointType& isP = mPointsOut[n];
563  isP[0] = typename PointType::value_type(pos[0]);
564  isP[1] = typename PointType::value_type(pos[1]);
565  isP[2] = typename PointType::value_type(pos[2]);
566  }
567  }
568 
569  PointType const * const mPointsIn;
570  PointType * const mPointsOut;
571  math::Transform const * const mXform;
572 }; // TransformPoints
573 
574 
575 template<typename ValueType>
576 struct Tolerance
577 {
578  static ValueType epsilon() { return ValueType(1e-7); }
579  static ValueType minNarrowBandWidth() { return ValueType(1.0 + 1e-6); }
580 };
581 
582 
583 ////////////////////////////////////////
584 
585 
586 template<typename TreeType>
588 {
589 public:
590 
591  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
592 
593  using LeafNodeType = typename TreeType::LeafNodeType;
594  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
595 
596  CombineLeafNodes(TreeType& lhsDistTree, Int32TreeType& lhsIdxTree,
597  LeafNodeType ** rhsDistNodes, Int32LeafNodeType ** rhsIdxNodes)
598  : mDistTree(&lhsDistTree)
599  , mIdxTree(&lhsIdxTree)
600  , mRhsDistNodes(rhsDistNodes)
601  , mRhsIdxNodes(rhsIdxNodes)
602  {
603  }
604 
605  void operator()(const tbb::blocked_range<size_t>& range) const {
606 
607  tree::ValueAccessor<TreeType> distAcc(*mDistTree);
608  tree::ValueAccessor<Int32TreeType> idxAcc(*mIdxTree);
609 
610  using DistValueType = typename LeafNodeType::ValueType;
611  using IndexValueType = typename Int32LeafNodeType::ValueType;
612 
613  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
614 
615  const Coord& origin = mRhsDistNodes[n]->origin();
616 
617  LeafNodeType* lhsDistNode = distAcc.probeLeaf(origin);
618  Int32LeafNodeType* lhsIdxNode = idxAcc.probeLeaf(origin);
619 
620  DistValueType* lhsDistData = lhsDistNode->buffer().data();
621  IndexValueType* lhsIdxData = lhsIdxNode->buffer().data();
622 
623  const DistValueType* rhsDistData = mRhsDistNodes[n]->buffer().data();
624  const IndexValueType* rhsIdxData = mRhsIdxNodes[n]->buffer().data();
625 
626 
627  for (Index32 offset = 0; offset < LeafNodeType::SIZE; ++offset) {
628 
629  if (rhsIdxData[offset] != Int32(util::INVALID_IDX)) {
630 
631  const DistValueType& lhsValue = lhsDistData[offset];
632  const DistValueType& rhsValue = rhsDistData[offset];
633 
634  if (rhsValue < lhsValue) {
635  lhsDistNode->setValueOn(offset, rhsValue);
636  lhsIdxNode->setValueOn(offset, rhsIdxData[offset]);
637  } else if (math::isExactlyEqual(rhsValue, lhsValue)) {
638  lhsIdxNode->setValueOn(offset,
639  std::min(lhsIdxData[offset], rhsIdxData[offset]));
640  }
641  }
642  }
643 
644  delete mRhsDistNodes[n];
645  delete mRhsIdxNodes[n];
646  }
647  }
648 
649 private:
650 
651  TreeType * const mDistTree;
652  Int32TreeType * const mIdxTree;
653 
654  LeafNodeType ** const mRhsDistNodes;
655  Int32LeafNodeType ** const mRhsIdxNodes;
656 }; // class CombineLeafNodes
657 
658 
659 ////////////////////////////////////////
660 
661 
662 template<typename TreeType>
664 {
665  using LeafNodeType = typename TreeType::LeafNodeType;
666 
667  StashOriginAndStoreOffset(std::vector<LeafNodeType*>& nodes, Coord* coordinates)
668  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
669  {
670  }
671 
672  void operator()(const tbb::blocked_range<size_t>& range) const {
673  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
674  Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
675  mCoordinates[n] = origin;
676  origin[0] = static_cast<int>(n);
677  }
678  }
679 
681  Coord * const mCoordinates;
682 };
683 
684 
685 template<typename TreeType>
687 {
688  using LeafNodeType = typename TreeType::LeafNodeType;
689 
690  RestoreOrigin(std::vector<LeafNodeType*>& nodes, const Coord* coordinates)
691  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
692  {
693  }
694 
695  void operator()(const tbb::blocked_range<size_t>& range) const {
696  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
697  Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
698  origin[0] = mCoordinates[n][0];
699  }
700  }
701 
703  Coord const * const mCoordinates;
704 };
705 
706 
707 template<typename TreeType>
709 {
710 public:
711  using LeafNodeType = typename TreeType::LeafNodeType;
712 
713  ComputeNodeConnectivity(const TreeType& tree, const Coord* coordinates,
714  size_t* offsets, size_t numNodes, const CoordBBox& bbox)
715  : mTree(&tree)
716  , mCoordinates(coordinates)
717  , mOffsets(offsets)
718  , mNumNodes(numNodes)
719  , mBBox(bbox)
720  {
721  }
722 
724 
725  // Disallow assignment
727 
728  void operator()(const tbb::blocked_range<size_t>& range) const {
729 
730  size_t* offsetsNextX = mOffsets;
731  size_t* offsetsPrevX = mOffsets + mNumNodes;
732  size_t* offsetsNextY = mOffsets + mNumNodes * 2;
733  size_t* offsetsPrevY = mOffsets + mNumNodes * 3;
734  size_t* offsetsNextZ = mOffsets + mNumNodes * 4;
735  size_t* offsetsPrevZ = mOffsets + mNumNodes * 5;
736 
738  Coord ijk;
739 
740  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
741  const Coord& origin = mCoordinates[n];
742  offsetsNextX[n] = findNeighbourNode(acc, origin, Coord(LeafNodeType::DIM, 0, 0));
743  offsetsPrevX[n] = findNeighbourNode(acc, origin, Coord(-LeafNodeType::DIM, 0, 0));
744  offsetsNextY[n] = findNeighbourNode(acc, origin, Coord(0, LeafNodeType::DIM, 0));
745  offsetsPrevY[n] = findNeighbourNode(acc, origin, Coord(0, -LeafNodeType::DIM, 0));
746  offsetsNextZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, LeafNodeType::DIM));
747  offsetsPrevZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, -LeafNodeType::DIM));
748  }
749  }
750 
752  const Coord& start, const Coord& step) const
753  {
754  Coord ijk = start + step;
755  CoordBBox bbox(mBBox);
756 
757  while (bbox.isInside(ijk)) {
758  const LeafNodeType* node = acc.probeConstLeaf(ijk);
759  if (node) return static_cast<size_t>(node->origin()[0]);
760  ijk += step;
761  }
762 
764  }
765 
766 
767 private:
768  TreeType const * const mTree;
769  Coord const * const mCoordinates;
770  size_t * const mOffsets;
771 
772  const size_t mNumNodes;
773  const CoordBBox mBBox;
774 }; // class ComputeNodeConnectivity
775 
776 
777 template<typename TreeType>
779 {
781 
782  using LeafNodeType = typename TreeType::LeafNodeType;
783 
785  {
786  mLeafNodes.reserve(tree.leafCount());
787  tree.getNodes(mLeafNodes);
788 
789  if (mLeafNodes.empty()) return;
790 
791  CoordBBox bbox;
792  tree.evalLeafBoundingBox(bbox);
793 
794  const tbb::blocked_range<size_t> range(0, mLeafNodes.size());
795 
796  // stash the leafnode origin coordinate and temporarily store the
797  // linear offset in the origin.x variable.
798  std::unique_ptr<Coord[]> coordinates{new Coord[mLeafNodes.size()]};
799  tbb::parallel_for(range,
800  StashOriginAndStoreOffset<TreeType>(mLeafNodes, coordinates.get()));
801 
802  // build the leafnode offset table
803  mOffsets.reset(new size_t[mLeafNodes.size() * 6]);
804 
805 
806  tbb::parallel_for(range, ComputeNodeConnectivity<TreeType>(
807  tree, coordinates.get(), mOffsets.get(), mLeafNodes.size(), bbox));
808 
809  // restore the leafnode origin coordinate
810  tbb::parallel_for(range, RestoreOrigin<TreeType>(mLeafNodes, coordinates.get()));
811  }
812 
813  size_t size() const { return mLeafNodes.size(); }
814 
815  std::vector<LeafNodeType*>& nodes() { return mLeafNodes; }
816  const std::vector<LeafNodeType*>& nodes() const { return mLeafNodes; }
817 
818 
819  const size_t* offsetsNextX() const { return mOffsets.get(); }
820  const size_t* offsetsPrevX() const { return mOffsets.get() + mLeafNodes.size(); }
821 
822  const size_t* offsetsNextY() const { return mOffsets.get() + mLeafNodes.size() * 2; }
823  const size_t* offsetsPrevY() const { return mOffsets.get() + mLeafNodes.size() * 3; }
824 
825  const size_t* offsetsNextZ() const { return mOffsets.get() + mLeafNodes.size() * 4; }
826  const size_t* offsetsPrevZ() const { return mOffsets.get() + mLeafNodes.size() * 5; }
827 
828 private:
829  std::vector<LeafNodeType*> mLeafNodes;
830  std::unique_ptr<size_t[]> mOffsets;
831 }; // struct LeafNodeConnectivityTable
832 
833 
834 template<typename TreeType>
836 {
837 public:
838 
839  enum Axis { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2 };
840 
841  using ValueType = typename TreeType::ValueType;
842  using LeafNodeType = typename TreeType::LeafNodeType;
844 
845  SweepExteriorSign(Axis axis, const std::vector<size_t>& startNodeIndices,
846  ConnectivityTable& connectivity)
847  : mStartNodeIndices(startNodeIndices.empty() ? nullptr : &startNodeIndices[0])
848  , mConnectivity(&connectivity)
849  , mAxis(axis)
850  {
851  }
852 
853  void operator()(const tbb::blocked_range<size_t>& range) const {
854 
855  std::vector<LeafNodeType*>& nodes = mConnectivity->nodes();
856 
857  // Z Axis
858  size_t idxA = 0, idxB = 1;
859  Index step = 1;
860 
861  const size_t* nextOffsets = mConnectivity->offsetsNextZ();
862  const size_t* prevOffsets = mConnectivity->offsetsPrevZ();
863 
864  if (mAxis == Y_AXIS) {
865 
866  idxA = 0;
867  idxB = 2;
868  step = LeafNodeType::DIM;
869 
870  nextOffsets = mConnectivity->offsetsNextY();
871  prevOffsets = mConnectivity->offsetsPrevY();
872 
873  } else if (mAxis == X_AXIS) {
874 
875  idxA = 1;
876  idxB = 2;
877  step = LeafNodeType::DIM * LeafNodeType::DIM;
878 
879  nextOffsets = mConnectivity->offsetsNextX();
880  prevOffsets = mConnectivity->offsetsPrevX();
881  }
882 
883  Coord ijk(0, 0, 0);
884 
885  int& a = ijk[idxA];
886  int& b = ijk[idxB];
887 
888  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
889 
890  size_t startOffset = mStartNodeIndices[n];
891  size_t lastOffset = startOffset;
892 
893  Index pos(0);
894 
895  for (a = 0; a < int(LeafNodeType::DIM); ++a) {
896  for (b = 0; b < int(LeafNodeType::DIM); ++b) {
897 
898  pos = LeafNodeType::coordToOffset(ijk);
899  size_t offset = startOffset;
900 
901  // sweep in +axis direction until a boundary voxel is hit.
902  while ( offset != ConnectivityTable::INVALID_OFFSET &&
903  traceVoxelLine(*nodes[offset], pos, step) ) {
904 
905  lastOffset = offset;
906  offset = nextOffsets[offset];
907  }
908 
909  // find last leafnode in +axis direction
910  offset = lastOffset;
911  while (offset != ConnectivityTable::INVALID_OFFSET) {
912  lastOffset = offset;
913  offset = nextOffsets[offset];
914  }
915 
916  // sweep in -axis direction until a boundary voxel is hit.
917  offset = lastOffset;
918  pos += step * (LeafNodeType::DIM - 1);
919  while ( offset != ConnectivityTable::INVALID_OFFSET &&
920  traceVoxelLine(*nodes[offset], pos, -step)) {
921  offset = prevOffsets[offset];
922  }
923  }
924  }
925  }
926  }
927 
928 
929  bool traceVoxelLine(LeafNodeType& node, Index pos, Index step) const {
930 
931  ValueType* data = node.buffer().data();
932 
933  bool isOutside = true;
934 
935  for (Index i = 0; i < LeafNodeType::DIM; ++i) {
936 
937  ValueType& dist = data[pos];
938 
939  if (dist < ValueType(0.0)) {
940  isOutside = true;
941  } else {
942  // Boundary voxel check. (Voxel that intersects the surface)
943  if (!(dist > ValueType(0.75))) isOutside = false;
944 
945  if (isOutside) dist = ValueType(-dist);
946  }
947 
948  pos += step;
949  }
950 
951  return isOutside;
952  }
953 
954 
955 private:
956  size_t const * const mStartNodeIndices;
957  ConnectivityTable * const mConnectivity;
958 
959  const Axis mAxis;
960 }; // class SweepExteriorSign
961 
962 
963 template<typename LeafNodeType>
964 inline void
965 seedFill(LeafNodeType& node)
966 {
967  using ValueType = typename LeafNodeType::ValueType;
968  using Queue = std::deque<Index>;
969 
970 
971  ValueType* data = node.buffer().data();
972 
973  // find seed points
974  Queue seedPoints;
975  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
976  if (data[pos] < 0.0) seedPoints.push_back(pos);
977  }
978 
979  if (seedPoints.empty()) return;
980 
981  // clear sign information
982  for (Queue::iterator it = seedPoints.begin(); it != seedPoints.end(); ++it) {
983  ValueType& dist = data[*it];
984  dist = -dist;
985  }
986 
987  // flood fill
988 
989  Coord ijk(0, 0, 0);
990  Index pos(0), nextPos(0);
991 
992  while (!seedPoints.empty()) {
993 
994  pos = seedPoints.back();
995  seedPoints.pop_back();
996 
997  ValueType& dist = data[pos];
998 
999  if (!(dist < ValueType(0.0))) {
1000 
1001  dist = -dist; // flip sign
1002 
1003  ijk = LeafNodeType::offsetToLocalCoord(pos);
1004 
1005  if (ijk[0] != 0) { // i - 1, j, k
1006  nextPos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
1007  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1008  }
1009 
1010  if (ijk[0] != (LeafNodeType::DIM - 1)) { // i + 1, j, k
1011  nextPos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
1012  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1013  }
1014 
1015  if (ijk[1] != 0) { // i, j - 1, k
1016  nextPos = pos - LeafNodeType::DIM;
1017  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1018  }
1019 
1020  if (ijk[1] != (LeafNodeType::DIM - 1)) { // i, j + 1, k
1021  nextPos = pos + LeafNodeType::DIM;
1022  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1023  }
1024 
1025  if (ijk[2] != 0) { // i, j, k - 1
1026  nextPos = pos - 1;
1027  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1028  }
1029 
1030  if (ijk[2] != (LeafNodeType::DIM - 1)) { // i, j, k + 1
1031  nextPos = pos + 1;
1032  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1033  }
1034  }
1035  }
1036 } // seedFill()
1037 
1038 
1039 template<typename LeafNodeType>
1040 inline bool
1041 scanFill(LeafNodeType& node)
1042 {
1043  bool updatedNode = false;
1044 
1045  using ValueType = typename LeafNodeType::ValueType;
1046  ValueType* data = node.buffer().data();
1047 
1048  Coord ijk(0, 0, 0);
1049 
1050  bool updatedSign = true;
1051  while (updatedSign) {
1052 
1053  updatedSign = false;
1054 
1055  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1056 
1057  ValueType& dist = data[pos];
1058 
1059  if (!(dist < ValueType(0.0)) && dist > ValueType(0.75)) {
1060 
1061  ijk = LeafNodeType::offsetToLocalCoord(pos);
1062 
1063  // i, j, k - 1
1064  if (ijk[2] != 0 && data[pos - 1] < ValueType(0.0)) {
1065  updatedSign = true;
1066  dist = ValueType(-dist);
1067 
1068  // i, j, k + 1
1069  } else if (ijk[2] != (LeafNodeType::DIM - 1) && data[pos + 1] < ValueType(0.0)) {
1070  updatedSign = true;
1071  dist = ValueType(-dist);
1072 
1073  // i, j - 1, k
1074  } else if (ijk[1] != 0 && data[pos - LeafNodeType::DIM] < ValueType(0.0)) {
1075  updatedSign = true;
1076  dist = ValueType(-dist);
1077 
1078  // i, j + 1, k
1079  } else if (ijk[1] != (LeafNodeType::DIM - 1)
1080  && data[pos + LeafNodeType::DIM] < ValueType(0.0))
1081  {
1082  updatedSign = true;
1083  dist = ValueType(-dist);
1084 
1085  // i - 1, j, k
1086  } else if (ijk[0] != 0
1087  && data[pos - LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1088  {
1089  updatedSign = true;
1090  dist = ValueType(-dist);
1091 
1092  // i + 1, j, k
1093  } else if (ijk[0] != (LeafNodeType::DIM - 1)
1094  && data[pos + LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1095  {
1096  updatedSign = true;
1097  dist = ValueType(-dist);
1098  }
1099  }
1100  } // end value loop
1101 
1102  updatedNode |= updatedSign;
1103  } // end update loop
1104 
1105  return updatedNode;
1106 } // scanFill()
1107 
1108 
1109 template<typename TreeType>
1111 {
1112 public:
1113  using ValueType = typename TreeType::ValueType;
1114  using LeafNodeType = typename TreeType::LeafNodeType;
1115 
1116  SeedFillExteriorSign(std::vector<LeafNodeType*>& nodes, bool* changedNodeMask)
1117  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1118  , mChangedNodeMask(changedNodeMask)
1119  {
1120  }
1121 
1122  void operator()(const tbb::blocked_range<size_t>& range) const {
1123  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1124  if (mChangedNodeMask[n]) {
1125  //seedFill(*mNodes[n]);
1127  }
1128  }
1129  }
1130 
1132  bool * const mChangedNodeMask;
1133 };
1134 
1135 
1136 template<typename ValueType>
1138 {
1139  FillArray(ValueType* array, const ValueType v) : mArray(array), mValue(v) { }
1140 
1141  void operator()(const tbb::blocked_range<size_t>& range) const {
1142  const ValueType v = mValue;
1143  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1144  mArray[n] = v;
1145  }
1146  }
1147 
1148  ValueType * const mArray;
1149  const ValueType mValue;
1150 };
1151 
1152 
1153 template<typename ValueType>
1154 inline void
1155 fillArray(ValueType* array, const ValueType val, const size_t length)
1156 {
1157  const auto grainSize = std::max<size_t>(
1158  length / tbb::task_scheduler_init::default_num_threads(), 1024);
1159  const tbb::blocked_range<size_t> range(0, length, grainSize);
1160  tbb::parallel_for(range, FillArray<ValueType>(array, val), tbb::simple_partitioner());
1161 }
1162 
1163 
1164 template<typename TreeType>
1166 {
1167 public:
1168  using ValueType = typename TreeType::ValueType;
1169  using LeafNodeType = typename TreeType::LeafNodeType;
1170 
1171  SyncVoxelMask(std::vector<LeafNodeType*>& nodes,
1172  const bool* changedNodeMask, bool* changedVoxelMask)
1173  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1174  , mChangedNodeMask(changedNodeMask)
1175  , mChangedVoxelMask(changedVoxelMask)
1176  {
1177  }
1178 
1179  void operator()(const tbb::blocked_range<size_t>& range) const {
1180  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1181 
1182  if (mChangedNodeMask[n]) {
1184 
1185  ValueType* data = mNodes[n]->buffer().data();
1186 
1187  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1188  if (mask[pos]) {
1189  data[pos] = ValueType(-data[pos]);
1190  mask[pos] = false;
1191  }
1192  }
1193  }
1194  }
1195  }
1196 
1198  bool const * const mChangedNodeMask;
1199  bool * const mChangedVoxelMask;
1200 };
1201 
1202 
1203 template<typename TreeType>
1205 {
1206 public:
1207  using ValueType = typename TreeType::ValueType;
1208  using LeafNodeType = typename TreeType::LeafNodeType;
1210 
1212  bool* changedNodeMask, bool* nodeMask, bool* changedVoxelMask)
1213  : mConnectivity(&connectivity)
1214  , mChangedNodeMask(changedNodeMask)
1215  , mNodeMask(nodeMask)
1216  , mChangedVoxelMask(changedVoxelMask)
1217  {
1218  }
1219 
1220  void operator()(const tbb::blocked_range<size_t>& range) const {
1221 
1222  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1223 
1224  if (!mChangedNodeMask[n]) {
1225 
1226  bool changedValue = false;
1227 
1228  changedValue |= processZ(n, /*firstFace=*/true);
1229  changedValue |= processZ(n, /*firstFace=*/false);
1230 
1231  changedValue |= processY(n, /*firstFace=*/true);
1232  changedValue |= processY(n, /*firstFace=*/false);
1233 
1234  changedValue |= processX(n, /*firstFace=*/true);
1235  changedValue |= processX(n, /*firstFace=*/false);
1236 
1237  mNodeMask[n] = changedValue;
1238  }
1239  }
1240  }
1241 
1242 
1243  bool processZ(const size_t n, bool firstFace) const
1244  {
1245  const size_t offset =
1246  firstFace ? mConnectivity->offsetsPrevZ()[n] : mConnectivity->offsetsNextZ()[n];
1247  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1248 
1250 
1251  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1252  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1253 
1254  const Index lastOffset = LeafNodeType::DIM - 1;
1255  const Index lhsOffset =
1256  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1257 
1258  Index tmpPos(0), pos(0);
1259  bool changedValue = false;
1260 
1261  for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1262  tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1263  for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1264  pos = tmpPos + (y << LeafNodeType::LOG2DIM);
1265 
1266  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1267  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1268  changedValue = true;
1269  mask[pos + lhsOffset] = true;
1270  }
1271  }
1272  }
1273  }
1274 
1275  return changedValue;
1276  }
1277 
1278  return false;
1279  }
1280 
1281  bool processY(const size_t n, bool firstFace) const
1282  {
1283  const size_t offset =
1284  firstFace ? mConnectivity->offsetsPrevY()[n] : mConnectivity->offsetsNextY()[n];
1285  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1286 
1288 
1289  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1290  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1291 
1292  const Index lastOffset = LeafNodeType::DIM * (LeafNodeType::DIM - 1);
1293  const Index lhsOffset =
1294  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1295 
1296  Index tmpPos(0), pos(0);
1297  bool changedValue = false;
1298 
1299  for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1300  tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1301  for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1302  pos = tmpPos + z;
1303 
1304  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1305  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1306  changedValue = true;
1307  mask[pos + lhsOffset] = true;
1308  }
1309  }
1310  }
1311  }
1312 
1313  return changedValue;
1314  }
1315 
1316  return false;
1317  }
1318 
1319  bool processX(const size_t n, bool firstFace) const
1320  {
1321  const size_t offset =
1322  firstFace ? mConnectivity->offsetsPrevX()[n] : mConnectivity->offsetsNextX()[n];
1323  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1324 
1326 
1327  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1328  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1329 
1330  const Index lastOffset = LeafNodeType::DIM * LeafNodeType::DIM * (LeafNodeType::DIM-1);
1331  const Index lhsOffset =
1332  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1333 
1334  Index tmpPos(0), pos(0);
1335  bool changedValue = false;
1336 
1337  for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1338  tmpPos = y << LeafNodeType::LOG2DIM;
1339  for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1340  pos = tmpPos + z;
1341 
1342  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1343  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1344  changedValue = true;
1345  mask[pos + lhsOffset] = true;
1346  }
1347  }
1348  }
1349  }
1350 
1351  return changedValue;
1352  }
1353 
1354  return false;
1355  }
1356 
1358  bool * const mChangedNodeMask;
1359  bool * const mNodeMask;
1360  bool * const mChangedVoxelMask;
1361 };
1362 
1363 
1364 ////////////////////////////////////////
1365 
1366 template<typename TreeType, typename MeshDataAdapter>
1368 {
1369  using ValueType = typename TreeType::ValueType;
1370  using LeafNodeType = typename TreeType::LeafNodeType;
1371  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1372  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
1373 
1374  using PointArray = std::unique_ptr<Vec3d[]>;
1375  using MaskArray = std::unique_ptr<bool[]>;
1376  using LocalData = std::pair<PointArray, MaskArray>;
1377  using LocalDataTable = tbb::enumerable_thread_specific<LocalData>;
1378 
1380  std::vector<LeafNodeType*>& distNodes,
1381  const TreeType& distTree,
1382  const Int32TreeType& indexTree,
1383  const MeshDataAdapter& mesh)
1384  : mDistNodes(distNodes.empty() ? nullptr : &distNodes[0])
1385  , mDistTree(&distTree)
1386  , mIndexTree(&indexTree)
1387  , mMesh(&mesh)
1388  , mLocalDataTable(new LocalDataTable())
1389  {
1390  }
1391 
1392 
1393  void operator()(const tbb::blocked_range<size_t>& range) const {
1394 
1395  tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
1396  tree::ValueAccessor<const Int32TreeType> idxAcc(*mIndexTree);
1397 
1398  ValueType nval;
1399  CoordBBox bbox;
1400  Index xPos(0), yPos(0);
1401  Coord ijk, nijk, nodeMin, nodeMax;
1402  Vec3d cp, xyz, nxyz, dir1, dir2;
1403 
1404  LocalData& localData = mLocalDataTable->local();
1405 
1406  PointArray& points = localData.first;
1407  if (!points) points.reset(new Vec3d[LeafNodeType::SIZE * 2]);
1408 
1409  MaskArray& mask = localData.second;
1410  if (!mask) mask.reset(new bool[LeafNodeType::SIZE]);
1411 
1412 
1413  typename LeafNodeType::ValueOnCIter it;
1414 
1415  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1416 
1417  LeafNodeType& node = *mDistNodes[n];
1418  ValueType* data = node.buffer().data();
1419 
1420  const Int32LeafNodeType* idxNode = idxAcc.probeConstLeaf(node.origin());
1421  const Int32* idxData = idxNode->buffer().data();
1422 
1423  nodeMin = node.origin();
1424  nodeMax = nodeMin.offsetBy(LeafNodeType::DIM - 1);
1425 
1426  // reset computed voxel mask.
1427  memset(mask.get(), 0, sizeof(bool) * LeafNodeType::SIZE);
1428 
1429  for (it = node.cbeginValueOn(); it; ++it) {
1430  Index pos = it.pos();
1431 
1432  ValueType& dist = data[pos];
1433  if (dist < 0.0 || dist > 0.75) continue;
1434 
1435  ijk = node.offsetToGlobalCoord(pos);
1436 
1437  xyz[0] = double(ijk[0]);
1438  xyz[1] = double(ijk[1]);
1439  xyz[2] = double(ijk[2]);
1440 
1441 
1442  bbox.min() = Coord::maxComponent(ijk.offsetBy(-1), nodeMin);
1443  bbox.max() = Coord::minComponent(ijk.offsetBy(1), nodeMax);
1444 
1445  bool flipSign = false;
1446 
1447  for (nijk[0] = bbox.min()[0]; nijk[0] <= bbox.max()[0] && !flipSign; ++nijk[0]) {
1448  xPos = (nijk[0] & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
1449  for (nijk[1]=bbox.min()[1]; nijk[1] <= bbox.max()[1] && !flipSign; ++nijk[1]) {
1450  yPos = xPos + ((nijk[1] & (LeafNodeType::DIM-1u)) << LeafNodeType::LOG2DIM);
1451  for (nijk[2] = bbox.min()[2]; nijk[2] <= bbox.max()[2]; ++nijk[2]) {
1452  pos = yPos + (nijk[2] & (LeafNodeType::DIM - 1u));
1453 
1454  const Int32& polyIdx = idxData[pos];
1455 
1456  if (polyIdx == Int32(util::INVALID_IDX) || !(data[pos] < -0.75))
1457  continue;
1458 
1459  const Index pointIndex = pos * 2;
1460 
1461  if (!mask[pos]) {
1462 
1463  mask[pos] = true;
1464 
1465  nxyz[0] = double(nijk[0]);
1466  nxyz[1] = double(nijk[1]);
1467  nxyz[2] = double(nijk[2]);
1468 
1469  Vec3d& point = points[pointIndex];
1470 
1471  point = closestPoint(nxyz, polyIdx);
1472 
1473  Vec3d& direction = points[pointIndex + 1];
1474  direction = nxyz - point;
1475  direction.normalize();
1476  }
1477 
1478  dir1 = xyz - points[pointIndex];
1479  dir1.normalize();
1480 
1481  if (points[pointIndex + 1].dot(dir1) > 0.0) {
1482  flipSign = true;
1483  break;
1484  }
1485  }
1486  }
1487  }
1488 
1489  if (flipSign) {
1490  dist = -dist;
1491  } else {
1492  for (Int32 m = 0; m < 26; ++m) {
1493  nijk = ijk + util::COORD_OFFSETS[m];
1494 
1495  if (!bbox.isInside(nijk) && distAcc.probeValue(nijk, nval) && nval<-0.75) {
1496  nxyz[0] = double(nijk[0]);
1497  nxyz[1] = double(nijk[1]);
1498  nxyz[2] = double(nijk[2]);
1499 
1500  cp = closestPoint(nxyz, idxAcc.getValue(nijk));
1501 
1502  dir1 = xyz - cp;
1503  dir1.normalize();
1504 
1505  dir2 = nxyz - cp;
1506  dir2.normalize();
1507 
1508  if (dir2.dot(dir1) > 0.0) {
1509  dist = -dist;
1510  break;
1511  }
1512  }
1513  }
1514  }
1515 
1516  } // active voxel loop
1517  } // leaf node loop
1518  }
1519 
1520 private:
1521 
1522  Vec3d closestPoint(const Vec3d& center, Int32 polyIdx) const
1523  {
1524  Vec3d a, b, c, cp, uvw;
1525 
1526  const size_t polygon = size_t(polyIdx);
1527  mMesh->getIndexSpacePoint(polygon, 0, a);
1528  mMesh->getIndexSpacePoint(polygon, 1, b);
1529  mMesh->getIndexSpacePoint(polygon, 2, c);
1530 
1531  cp = closestPointOnTriangleToPoint(a, c, b, center, uvw);
1532 
1533  if (4 == mMesh->vertexCount(polygon)) {
1534 
1535  mMesh->getIndexSpacePoint(polygon, 3, b);
1536 
1537  c = closestPointOnTriangleToPoint(a, b, c, center, uvw);
1538 
1539  if ((center - c).lengthSqr() < (center - cp).lengthSqr()) {
1540  cp = c;
1541  }
1542  }
1543 
1544  return cp;
1545  }
1546 
1547 
1548  LeafNodeType ** const mDistNodes;
1549  TreeType const * const mDistTree;
1550  Int32TreeType const * const mIndexTree;
1551  MeshDataAdapter const * const mMesh;
1552 
1553  SharedPtr<LocalDataTable> mLocalDataTable;
1554 }; // ComputeIntersectingVoxelSign
1555 
1556 
1557 ////////////////////////////////////////
1558 
1559 
1560 template<typename LeafNodeType>
1561 inline void
1562 maskNodeInternalNeighbours(const Index pos, bool (&mask)[26])
1563 {
1564  using NodeT = LeafNodeType;
1565 
1566  const Coord ijk = NodeT::offsetToLocalCoord(pos);
1567 
1568  // Face adjacent neighbours
1569  // i+1, j, k
1570  mask[0] = ijk[0] != (NodeT::DIM - 1);
1571  // i-1, j, k
1572  mask[1] = ijk[0] != 0;
1573  // i, j+1, k
1574  mask[2] = ijk[1] != (NodeT::DIM - 1);
1575  // i, j-1, k
1576  mask[3] = ijk[1] != 0;
1577  // i, j, k+1
1578  mask[4] = ijk[2] != (NodeT::DIM - 1);
1579  // i, j, k-1
1580  mask[5] = ijk[2] != 0;
1581 
1582  // Edge adjacent neighbour
1583  // i+1, j, k-1
1584  mask[6] = mask[0] && mask[5];
1585  // i-1, j, k-1
1586  mask[7] = mask[1] && mask[5];
1587  // i+1, j, k+1
1588  mask[8] = mask[0] && mask[4];
1589  // i-1, j, k+1
1590  mask[9] = mask[1] && mask[4];
1591  // i+1, j+1, k
1592  mask[10] = mask[0] && mask[2];
1593  // i-1, j+1, k
1594  mask[11] = mask[1] && mask[2];
1595  // i+1, j-1, k
1596  mask[12] = mask[0] && mask[3];
1597  // i-1, j-1, k
1598  mask[13] = mask[1] && mask[3];
1599  // i, j-1, k+1
1600  mask[14] = mask[3] && mask[4];
1601  // i, j-1, k-1
1602  mask[15] = mask[3] && mask[5];
1603  // i, j+1, k+1
1604  mask[16] = mask[2] && mask[4];
1605  // i, j+1, k-1
1606  mask[17] = mask[2] && mask[5];
1607 
1608  // Corner adjacent neighbours
1609  // i-1, j-1, k-1
1610  mask[18] = mask[1] && mask[3] && mask[5];
1611  // i-1, j-1, k+1
1612  mask[19] = mask[1] && mask[3] && mask[4];
1613  // i+1, j-1, k+1
1614  mask[20] = mask[0] && mask[3] && mask[4];
1615  // i+1, j-1, k-1
1616  mask[21] = mask[0] && mask[3] && mask[5];
1617  // i-1, j+1, k-1
1618  mask[22] = mask[1] && mask[2] && mask[5];
1619  // i-1, j+1, k+1
1620  mask[23] = mask[1] && mask[2] && mask[4];
1621  // i+1, j+1, k+1
1622  mask[24] = mask[0] && mask[2] && mask[4];
1623  // i+1, j+1, k-1
1624  mask[25] = mask[0] && mask[2] && mask[5];
1625 }
1626 
1627 
1628 template<typename Compare, typename LeafNodeType>
1629 inline bool
1630 checkNeighbours(const Index pos, const typename LeafNodeType::ValueType * data, bool (&mask)[26])
1631 {
1632  using NodeT = LeafNodeType;
1633 
1634  // i, j, k - 1
1635  if (mask[5] && Compare::check(data[pos - 1])) return true;
1636  // i, j, k + 1
1637  if (mask[4] && Compare::check(data[pos + 1])) return true;
1638  // i, j - 1, k
1639  if (mask[3] && Compare::check(data[pos - NodeT::DIM])) return true;
1640  // i, j + 1, k
1641  if (mask[2] && Compare::check(data[pos + NodeT::DIM])) return true;
1642  // i - 1, j, k
1643  if (mask[1] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM])) return true;
1644  // i + 1, j, k
1645  if (mask[0] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1646  // i+1, j, k-1
1647  if (mask[6] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1648  // i-1, j, k-1
1649  if (mask[7] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - 1])) return true;
1650  // i+1, j, k+1
1651  if (mask[8] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + 1])) return true;
1652  // i-1, j, k+1
1653  if (mask[9] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + 1])) return true;
1654  // i+1, j+1, k
1655  if (mask[10] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1656  // i-1, j+1, k
1657  if (mask[11] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1658  // i+1, j-1, k
1659  if (mask[12] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1660  // i-1, j-1, k
1661  if (mask[13] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1662  // i, j-1, k+1
1663  if (mask[14] && Compare::check(data[pos - NodeT::DIM + 1])) return true;
1664  // i, j-1, k-1
1665  if (mask[15] && Compare::check(data[pos - NodeT::DIM - 1])) return true;
1666  // i, j+1, k+1
1667  if (mask[16] && Compare::check(data[pos + NodeT::DIM + 1])) return true;
1668  // i, j+1, k-1
1669  if (mask[17] && Compare::check(data[pos + NodeT::DIM - 1])) return true;
1670  // i-1, j-1, k-1
1671  if (mask[18] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1672  // i-1, j-1, k+1
1673  if (mask[19] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1674  // i+1, j-1, k+1
1675  if (mask[20] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1676  // i+1, j-1, k-1
1677  if (mask[21] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1678  // i-1, j+1, k-1
1679  if (mask[22] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1680  // i-1, j+1, k+1
1681  if (mask[23] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1682  // i+1, j+1, k+1
1683  if (mask[24] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1684  // i+1, j+1, k-1
1685  if (mask[25] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1686 
1687  return false;
1688 }
1689 
1690 
1691 template<typename Compare, typename AccessorType>
1692 inline bool
1693 checkNeighbours(const Coord& ijk, AccessorType& acc, bool (&mask)[26])
1694 {
1695  for (Int32 m = 0; m < 26; ++m) {
1696  if (!mask[m] && Compare::check(acc.getValue(ijk + util::COORD_OFFSETS[m]))) {
1697  return true;
1698  }
1699  }
1700 
1701  return false;
1702 }
1703 
1704 
1705 template<typename TreeType>
1707 {
1708  using ValueType = typename TreeType::ValueType;
1709  using LeafNodeType = typename TreeType::LeafNodeType;
1710 
1711  struct IsNegative { static bool check(const ValueType v) { return v < ValueType(0.0); } };
1712 
1713  ValidateIntersectingVoxels(TreeType& tree, std::vector<LeafNodeType*>& nodes)
1714  : mTree(&tree)
1715  , mNodes(nodes.empty() ? nullptr : &nodes[0])
1716  {
1717  }
1718 
1719  void operator()(const tbb::blocked_range<size_t>& range) const
1720  {
1722  bool neighbourMask[26];
1723 
1724  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1725 
1726  LeafNodeType& node = *mNodes[n];
1727  ValueType* data = node.buffer().data();
1728 
1729  typename LeafNodeType::ValueOnCIter it;
1730  for (it = node.cbeginValueOn(); it; ++it) {
1731 
1732  const Index pos = it.pos();
1733 
1734  ValueType& dist = data[pos];
1735  if (dist < 0.0 || dist > 0.75) continue;
1736 
1737  // Mask node internal neighbours
1738  maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1739 
1740  const bool hasNegativeNeighbour =
1741  checkNeighbours<IsNegative, LeafNodeType>(pos, data, neighbourMask) ||
1742  checkNeighbours<IsNegative>(node.offsetToGlobalCoord(pos), acc, neighbourMask);
1743 
1744  if (!hasNegativeNeighbour) {
1745  // push over boundary voxel distance
1746  dist = ValueType(0.75) + Tolerance<ValueType>::epsilon();
1747  }
1748  }
1749  }
1750  }
1751 
1752  TreeType * const mTree;
1754 }; // ValidateIntersectingVoxels
1755 
1756 
1757 template<typename TreeType>
1759 {
1760  using ValueType = typename TreeType::ValueType;
1761  using LeafNodeType = typename TreeType::LeafNodeType;
1762  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1763 
1764  struct Comp { static bool check(const ValueType v) { return !(v > ValueType(0.75)); } };
1765 
1766  RemoveSelfIntersectingSurface(std::vector<LeafNodeType*>& nodes,
1767  TreeType& distTree, Int32TreeType& indexTree)
1768  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1769  , mDistTree(&distTree)
1770  , mIndexTree(&indexTree)
1771  {
1772  }
1773 
1774  void operator()(const tbb::blocked_range<size_t>& range) const
1775  {
1778  bool neighbourMask[26];
1779 
1780  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1781 
1782  LeafNodeType& distNode = *mNodes[n];
1783  ValueType* data = distNode.buffer().data();
1784 
1785  typename Int32TreeType::LeafNodeType* idxNode =
1786  idxAcc.probeLeaf(distNode.origin());
1787 
1788  typename LeafNodeType::ValueOnCIter it;
1789  for (it = distNode.cbeginValueOn(); it; ++it) {
1790 
1791  const Index pos = it.pos();
1792 
1793  if (!(data[pos] > 0.75)) continue;
1794 
1795  // Mask node internal neighbours
1796  maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1797 
1798  const bool hasBoundaryNeighbour =
1799  checkNeighbours<Comp, LeafNodeType>(pos, data, neighbourMask) ||
1800  checkNeighbours<Comp>(distNode.offsetToGlobalCoord(pos),distAcc,neighbourMask);
1801 
1802  if (!hasBoundaryNeighbour) {
1803  distNode.setValueOff(pos);
1804  idxNode->setValueOff(pos);
1805  }
1806  }
1807  }
1808  }
1809 
1811  TreeType * const mDistTree;
1813 }; // RemoveSelfIntersectingSurface
1814 
1815 
1816 ////////////////////////////////////////
1817 
1818 
1819 template<typename NodeType>
1821 {
1822  ReleaseChildNodes(NodeType ** nodes) : mNodes(nodes) {}
1823 
1824  void operator()(const tbb::blocked_range<size_t>& range) const {
1825 
1826  using NodeMaskType = typename NodeType::NodeMaskType;
1827 
1828  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1829  const_cast<NodeMaskType&>(mNodes[n]->getChildMask()).setOff();
1830  }
1831  }
1832 
1833  NodeType ** const mNodes;
1834 };
1835 
1836 
1837 template<typename TreeType>
1838 inline void
1839 releaseLeafNodes(TreeType& tree)
1840 {
1841  using RootNodeType = typename TreeType::RootNodeType;
1842  using NodeChainType = typename RootNodeType::NodeChainType;
1843  using InternalNodeType = typename hboost::mpl::at<NodeChainType, hboost::mpl::int_<1> >::type;
1844 
1845  std::vector<InternalNodeType*> nodes;
1846  tree.getNodes(nodes);
1847 
1848  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
1849  ReleaseChildNodes<InternalNodeType>(nodes.empty() ? nullptr : &nodes[0]));
1850 }
1851 
1852 
1853 template<typename TreeType>
1855 {
1856  using LeafNodeType = typename TreeType::LeafNodeType;
1857 
1858  StealUniqueLeafNodes(TreeType& lhsTree, TreeType& rhsTree,
1859  std::vector<LeafNodeType*>& overlappingNodes)
1860  : mLhsTree(&lhsTree)
1861  , mRhsTree(&rhsTree)
1862  , mNodes(&overlappingNodes)
1863  {
1864  }
1865 
1866  void operator()() const {
1867 
1868  std::vector<LeafNodeType*> rhsLeafNodes;
1869 
1870  rhsLeafNodes.reserve(mRhsTree->leafCount());
1871  //mRhsTree->getNodes(rhsLeafNodes);
1872  //releaseLeafNodes(*mRhsTree);
1873  mRhsTree->stealNodes(rhsLeafNodes);
1874 
1875  tree::ValueAccessor<TreeType> acc(*mLhsTree);
1876 
1877  for (size_t n = 0, N = rhsLeafNodes.size(); n < N; ++n) {
1878  if (!acc.probeLeaf(rhsLeafNodes[n]->origin())) {
1879  acc.addLeaf(rhsLeafNodes[n]);
1880  } else {
1881  mNodes->push_back(rhsLeafNodes[n]);
1882  }
1883  }
1884  }
1885 
1886 private:
1887  TreeType * const mLhsTree;
1888  TreeType * const mRhsTree;
1889  std::vector<LeafNodeType*> * const mNodes;
1890 };
1891 
1892 
1893 template<typename DistTreeType, typename IndexTreeType>
1894 inline void
1895 combineData(DistTreeType& lhsDist, IndexTreeType& lhsIdx,
1896  DistTreeType& rhsDist, IndexTreeType& rhsIdx)
1897 {
1898  using DistLeafNodeType = typename DistTreeType::LeafNodeType;
1899  using IndexLeafNodeType = typename IndexTreeType::LeafNodeType;
1900 
1901  std::vector<DistLeafNodeType*> overlappingDistNodes;
1902  std::vector<IndexLeafNodeType*> overlappingIdxNodes;
1903 
1904  // Steal unique leafnodes
1905  tbb::task_group tasks;
1906  tasks.run(StealUniqueLeafNodes<DistTreeType>(lhsDist, rhsDist, overlappingDistNodes));
1907  tasks.run(StealUniqueLeafNodes<IndexTreeType>(lhsIdx, rhsIdx, overlappingIdxNodes));
1908  tasks.wait();
1909 
1910  // Combine overlapping leaf nodes
1911  if (!overlappingDistNodes.empty() && !overlappingIdxNodes.empty()) {
1912  tbb::parallel_for(tbb::blocked_range<size_t>(0, overlappingDistNodes.size()),
1913  CombineLeafNodes<DistTreeType>(lhsDist, lhsIdx,
1914  &overlappingDistNodes[0], &overlappingIdxNodes[0]));
1915  }
1916 }
1917 
1918 /// @brief TBB body object to voxelize a mesh of triangles and/or quads into a collection
1919 /// of VDB grids, namely a squared distance grid, a closest primitive grid and an
1920 /// intersecting voxels grid (masks the mesh intersecting voxels)
1921 /// @note Only the leaf nodes that intersect the mesh are allocated, and only voxels in
1922 /// a narrow band (of two to three voxels in proximity to the mesh's surface) are activated.
1923 /// They are populated with distance values and primitive indices.
1924 template<typename TreeType>
1926 
1927  using Ptr = std::unique_ptr<VoxelizationData>;
1928  using ValueType = typename TreeType::ValueType;
1929 
1930  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1931  using UCharTreeType = typename TreeType::template ValueConverter<unsigned char>::Type;
1932 
1936 
1937 
1939  : distTree(std::numeric_limits<ValueType>::max())
1940  , distAcc(distTree)
1941  , indexTree(Int32(util::INVALID_IDX))
1942  , indexAcc(indexTree)
1943  , primIdTree(MaxPrimId)
1945  , mPrimCount(0)
1946  {
1947  }
1948 
1949  TreeType distTree;
1951 
1954 
1957 
1958  unsigned char getNewPrimId() {
1959 
1960  if (mPrimCount == MaxPrimId || primIdTree.leafCount() > 1000) {
1961  mPrimCount = 0;
1962  primIdTree.clear();
1963  }
1964 
1965  return mPrimCount++;
1966  }
1967 
1968 private:
1969 
1970  enum { MaxPrimId = 100 };
1971 
1972  unsigned char mPrimCount;
1973 };
1974 
1975 
1976 template<typename TreeType, typename MeshDataAdapter, typename Interrupter = util::NullInterrupter>
1978 {
1979 public:
1980 
1982  using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
1983 
1985  const MeshDataAdapter& mesh,
1986  Interrupter* interrupter = nullptr)
1987  : mDataTable(&dataTable)
1988  , mMesh(&mesh)
1989  , mInterrupter(interrupter)
1990  {
1991  }
1992 
1993  void operator()(const tbb::blocked_range<size_t>& range) const {
1994 
1995  typename VoxelizationDataType::Ptr& dataPtr = mDataTable->local();
1996  if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
1997 
1998  Triangle prim;
1999 
2000  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2001 
2002  if (this->wasInterrupted()) {
2003  tbb::task::self().cancel_group_execution();
2004  break;
2005  }
2006 
2007  const size_t numVerts = mMesh->vertexCount(n);
2008 
2009  // rasterize triangles and quads.
2010  if (numVerts == 3 || numVerts == 4) {
2011 
2012  prim.index = Int32(n);
2013 
2014  mMesh->getIndexSpacePoint(n, 0, prim.a);
2015  mMesh->getIndexSpacePoint(n, 1, prim.b);
2016  mMesh->getIndexSpacePoint(n, 2, prim.c);
2017 
2018  evalTriangle(prim, *dataPtr);
2019 
2020  if (numVerts == 4) {
2021  mMesh->getIndexSpacePoint(n, 3, prim.b);
2022  evalTriangle(prim, *dataPtr);
2023  }
2024  }
2025  }
2026  }
2027 
2028 private:
2029 
2030  bool wasInterrupted() const { return mInterrupter && mInterrupter->wasInterrupted(); }
2031 
2032  struct Triangle { Vec3d a, b, c; Int32 index; };
2033 
2034  struct SubTask
2035  {
2036  enum { POLYGON_LIMIT = 1000 };
2037 
2038  SubTask(const Triangle& prim, DataTable& dataTable,
2039  int subdivisionCount, size_t polygonCount)
2040  : mLocalDataTable(&dataTable)
2041  , mPrim(prim)
2042  , mSubdivisionCount(subdivisionCount)
2043  , mPolygonCount(polygonCount)
2044  {
2045  }
2046 
2047  void operator()() const
2048  {
2049  if (mSubdivisionCount <= 0 || mPolygonCount >= POLYGON_LIMIT) {
2050 
2051  typename VoxelizationDataType::Ptr& dataPtr = mLocalDataTable->local();
2052  if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
2053 
2054  voxelizeTriangle(mPrim, *dataPtr);
2055 
2056  } else {
2057  spawnTasks(mPrim, *mLocalDataTable, mSubdivisionCount, mPolygonCount);
2058  }
2059  }
2060 
2061  DataTable * const mLocalDataTable;
2062  Triangle const mPrim;
2063  int const mSubdivisionCount;
2064  size_t const mPolygonCount;
2065  }; // struct SubTask
2066 
2067  inline static int evalSubdivisionCount(const Triangle& prim)
2068  {
2069  const double ax = prim.a[0], bx = prim.b[0], cx = prim.c[0];
2070  const double dx = std::max(ax, std::max(bx, cx)) - std::min(ax, std::min(bx, cx));
2071 
2072  const double ay = prim.a[1], by = prim.b[1], cy = prim.c[1];
2073  const double dy = std::max(ay, std::max(by, cy)) - std::min(ay, std::min(by, cy));
2074 
2075  const double az = prim.a[2], bz = prim.b[2], cz = prim.c[2];
2076  const double dz = std::max(az, std::max(bz, cz)) - std::min(az, std::min(bz, cz));
2077 
2078  return int(std::max(dx, std::max(dy, dz)) / double(TreeType::LeafNodeType::DIM * 2));
2079  }
2080 
2081  void evalTriangle(const Triangle& prim, VoxelizationDataType& data) const
2082  {
2083  const size_t polygonCount = mMesh->polygonCount();
2084  const int subdivisionCount =
2085  polygonCount < SubTask::POLYGON_LIMIT ? evalSubdivisionCount(prim) : 0;
2086 
2087  if (subdivisionCount <= 0) {
2088  voxelizeTriangle(prim, data);
2089  } else {
2090  spawnTasks(prim, *mDataTable, subdivisionCount, polygonCount);
2091  }
2092  }
2093 
2094  static void spawnTasks(
2095  const Triangle& mainPrim, DataTable& dataTable, int subdivisionCount, size_t polygonCount)
2096  {
2097  subdivisionCount -= 1;
2098  polygonCount *= 4;
2099 
2100  tbb::task_group tasks;
2101 
2102  const Vec3d ac = (mainPrim.a + mainPrim.c) * 0.5;
2103  const Vec3d bc = (mainPrim.b + mainPrim.c) * 0.5;
2104  const Vec3d ab = (mainPrim.a + mainPrim.b) * 0.5;
2105 
2106  Triangle prim;
2107  prim.index = mainPrim.index;
2108 
2109  prim.a = mainPrim.a;
2110  prim.b = ab;
2111  prim.c = ac;
2112  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
2113 
2114  prim.a = ab;
2115  prim.b = bc;
2116  prim.c = ac;
2117  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
2118 
2119  prim.a = ab;
2120  prim.b = mainPrim.b;
2121  prim.c = bc;
2122  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
2123 
2124  prim.a = ac;
2125  prim.b = bc;
2126  prim.c = mainPrim.c;
2127  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
2128 
2129  tasks.wait();
2130  }
2131 
2132  static void voxelizeTriangle(const Triangle& prim, VoxelizationDataType& data)
2133  {
2134  std::deque<Coord> coordList;
2135  Coord ijk, nijk;
2136 
2137  ijk = Coord::floor(prim.a);
2138  coordList.push_back(ijk);
2139 
2140  computeDistance(ijk, prim, data);
2141 
2142  unsigned char primId = data.getNewPrimId();
2143  data.primIdAcc.setValueOnly(ijk, primId);
2144 
2145  while (!coordList.empty()) {
2146  ijk = coordList.back();
2147  coordList.pop_back();
2148 
2149  for (Int32 i = 0; i < 26; ++i) {
2150  nijk = ijk + util::COORD_OFFSETS[i];
2151  if (primId != data.primIdAcc.getValue(nijk)) {
2152  data.primIdAcc.setValueOnly(nijk, primId);
2153  if(computeDistance(nijk, prim, data)) coordList.push_back(nijk);
2154  }
2155  }
2156  }
2157  }
2158 
2159  static bool computeDistance(const Coord& ijk, const Triangle& prim, VoxelizationDataType& data)
2160  {
2161  Vec3d uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2162 
2163  using ValueType = typename TreeType::ValueType;
2164 
2165  const ValueType dist = ValueType((voxelCenter -
2166  closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, voxelCenter, uvw)).lengthSqr());
2167 
2168  const ValueType oldDist = data.distAcc.getValue(ijk);
2169 
2170  if (dist < oldDist) {
2171  data.distAcc.setValue(ijk, dist);
2172  data.indexAcc.setValue(ijk, prim.index);
2173  } else if (math::isExactlyEqual(dist, oldDist)) {
2174  // makes reduction deterministic when different polygons
2175  // produce the same distance value.
2176  data.indexAcc.setValueOnly(ijk, std::min(prim.index, data.indexAcc.getValue(ijk)));
2177  }
2178 
2179  return !(dist > 0.75); // true if the primitive intersects the voxel.
2180  }
2181 
2182  DataTable * const mDataTable;
2183  MeshDataAdapter const * const mMesh;
2184  Interrupter * const mInterrupter;
2185 }; // VoxelizePolygons
2186 
2187 
2188 ////////////////////////////////////////
2189 
2190 
2191 template<typename TreeType>
2193 {
2195  using LeafNodeType = typename TreeType::LeafNodeType;
2196 
2197  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2198  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2199 
2200  DiffLeafNodeMask(const TreeType& rhsTree,
2201  std::vector<BoolLeafNodeType*>& lhsNodes)
2202  : mRhsTree(&rhsTree), mLhsNodes(lhsNodes.empty() ? nullptr : &lhsNodes[0])
2203  {
2204  }
2205 
2206  void operator()(const tbb::blocked_range<size_t>& range) const {
2207 
2208  tree::ValueAccessor<const TreeType> acc(*mRhsTree);
2209 
2210  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2211 
2212  BoolLeafNodeType* lhsNode = mLhsNodes[n];
2213  const LeafNodeType* rhsNode = acc.probeConstLeaf(lhsNode->origin());
2214 
2215  if (rhsNode) lhsNode->topologyDifference(*rhsNode, false);
2216  }
2217  }
2218 
2219 private:
2220  TreeType const * const mRhsTree;
2221  BoolLeafNodeType ** const mLhsNodes;
2222 };
2223 
2224 
2225 template<typename LeafNodeTypeA, typename LeafNodeTypeB>
2227 {
2228  UnionValueMasks(std::vector<LeafNodeTypeA*>& nodesA, std::vector<LeafNodeTypeB*>& nodesB)
2229  : mNodesA(nodesA.empty() ? nullptr : &nodesA[0])
2230  , mNodesB(nodesB.empty() ? nullptr : &nodesB[0])
2231  {
2232  }
2233 
2234  void operator()(const tbb::blocked_range<size_t>& range) const {
2235  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2236  mNodesA[n]->topologyUnion(*mNodesB[n]);
2237  }
2238  }
2239 
2240 private:
2241  LeafNodeTypeA ** const mNodesA;
2242  LeafNodeTypeB ** const mNodesB;
2243 };
2244 
2245 
2246 template<typename TreeType>
2248 {
2249  using LeafNodeType = typename TreeType::LeafNodeType;
2250 
2251  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2252  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2253 
2254  ConstructVoxelMask(BoolTreeType& maskTree, const TreeType& tree,
2255  std::vector<LeafNodeType*>& nodes)
2256  : mTree(&tree)
2257  , mNodes(nodes.empty() ? nullptr : &nodes[0])
2258  , mLocalMaskTree(false)
2259  , mMaskTree(&maskTree)
2260  {
2261  }
2262 
2264  : mTree(rhs.mTree)
2265  , mNodes(rhs.mNodes)
2266  , mLocalMaskTree(false)
2267  , mMaskTree(&mLocalMaskTree)
2268  {
2269  }
2270 
2271  void operator()(const tbb::blocked_range<size_t>& range)
2272  {
2273  using Iterator = typename LeafNodeType::ValueOnCIter;
2274 
2276  tree::ValueAccessor<BoolTreeType> maskAcc(*mMaskTree);
2277 
2278  Coord ijk, nijk, localCorod;
2279  Index pos, npos;
2280 
2281  for (size_t n = range.begin(); n != range.end(); ++n) {
2282 
2283  LeafNodeType& node = *mNodes[n];
2284 
2285  CoordBBox bbox = node.getNodeBoundingBox();
2286  bbox.expand(-1);
2287 
2288  BoolLeafNodeType& maskNode = *maskAcc.touchLeaf(node.origin());
2289 
2290  for (Iterator it = node.cbeginValueOn(); it; ++it) {
2291  ijk = it.getCoord();
2292  pos = it.pos();
2293 
2294  localCorod = LeafNodeType::offsetToLocalCoord(pos);
2295 
2296  if (localCorod[2] < int(LeafNodeType::DIM - 1)) {
2297  npos = pos + 1;
2298  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2299  } else {
2300  nijk = ijk.offsetBy(0, 0, 1);
2301  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2302  }
2303 
2304  if (localCorod[2] > 0) {
2305  npos = pos - 1;
2306  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2307  } else {
2308  nijk = ijk.offsetBy(0, 0, -1);
2309  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2310  }
2311 
2312  if (localCorod[1] < int(LeafNodeType::DIM - 1)) {
2313  npos = pos + LeafNodeType::DIM;
2314  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2315  } else {
2316  nijk = ijk.offsetBy(0, 1, 0);
2317  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2318  }
2319 
2320  if (localCorod[1] > 0) {
2321  npos = pos - LeafNodeType::DIM;
2322  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2323  } else {
2324  nijk = ijk.offsetBy(0, -1, 0);
2325  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2326  }
2327 
2328  if (localCorod[0] < int(LeafNodeType::DIM - 1)) {
2329  npos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
2330  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2331  } else {
2332  nijk = ijk.offsetBy(1, 0, 0);
2333  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2334  }
2335 
2336  if (localCorod[0] > 0) {
2337  npos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
2338  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2339  } else {
2340  nijk = ijk.offsetBy(-1, 0, 0);
2341  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2342  }
2343  }
2344  }
2345  }
2346 
2347  void join(ConstructVoxelMask& rhs) { mMaskTree->merge(*rhs.mMaskTree); }
2348 
2349 private:
2350  TreeType const * const mTree;
2351  LeafNodeType ** const mNodes;
2352 
2353  BoolTreeType mLocalMaskTree;
2354  BoolTreeType * const mMaskTree;
2355 };
2356 
2357 
2358 /// @note The interior and exterior widths should be in world space units and squared.
2359 template<typename TreeType, typename MeshDataAdapter>
2361 {
2362  using ValueType = typename TreeType::ValueType;
2363  using LeafNodeType = typename TreeType::LeafNodeType;
2364  using NodeMaskType = typename LeafNodeType::NodeMaskType;
2365  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
2366  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
2367  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2368  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2369 
2370  struct Fragment
2371  {
2372  Int32 idx, x, y, z;
2374 
2375  Fragment() : idx(0), x(0), y(0), z(0), dist(0.0) {}
2376 
2377  Fragment(Int32 idx_, Int32 x_, Int32 y_, Int32 z_, ValueType dist_)
2378  : idx(idx_), x(x_), y(y_), z(z_), dist(dist_)
2379  {
2380  }
2381 
2382  bool operator<(const Fragment& rhs) const { return idx < rhs.idx; }
2383  }; // struct Fragment
2384 
2385  ////////////////////
2386 
2388  std::vector<BoolLeafNodeType*>& maskNodes,
2389  BoolTreeType& maskTree,
2390  TreeType& distTree,
2391  Int32TreeType& indexTree,
2392  const MeshDataAdapter& mesh,
2393  ValueType exteriorBandWidth,
2394  ValueType interiorBandWidth,
2395  ValueType voxelSize)
2396  : mMaskNodes(maskNodes.empty() ? nullptr : &maskNodes[0])
2397  , mMaskTree(&maskTree)
2398  , mDistTree(&distTree)
2399  , mIndexTree(&indexTree)
2400  , mMesh(&mesh)
2401  , mNewMaskTree(false)
2402  , mDistNodes()
2403  , mUpdatedDistNodes()
2404  , mIndexNodes()
2405  , mUpdatedIndexNodes()
2406  , mExteriorBandWidth(exteriorBandWidth)
2407  , mInteriorBandWidth(interiorBandWidth)
2408  , mVoxelSize(voxelSize)
2409  {
2410  }
2411 
2412  ExpandNarrowband(const ExpandNarrowband& rhs, tbb::split)
2413  : mMaskNodes(rhs.mMaskNodes)
2414  , mMaskTree(rhs.mMaskTree)
2415  , mDistTree(rhs.mDistTree)
2416  , mIndexTree(rhs.mIndexTree)
2417  , mMesh(rhs.mMesh)
2418  , mNewMaskTree(false)
2419  , mDistNodes()
2420  , mUpdatedDistNodes()
2421  , mIndexNodes()
2422  , mUpdatedIndexNodes()
2423  , mExteriorBandWidth(rhs.mExteriorBandWidth)
2424  , mInteriorBandWidth(rhs.mInteriorBandWidth)
2425  , mVoxelSize(rhs.mVoxelSize)
2426  {
2427  }
2428 
2430  {
2431  mDistNodes.insert(mDistNodes.end(), rhs.mDistNodes.begin(), rhs.mDistNodes.end());
2432  mIndexNodes.insert(mIndexNodes.end(), rhs.mIndexNodes.begin(), rhs.mIndexNodes.end());
2433 
2434  mUpdatedDistNodes.insert(mUpdatedDistNodes.end(),
2435  rhs.mUpdatedDistNodes.begin(), rhs.mUpdatedDistNodes.end());
2436 
2437  mUpdatedIndexNodes.insert(mUpdatedIndexNodes.end(),
2438  rhs.mUpdatedIndexNodes.begin(), rhs.mUpdatedIndexNodes.end());
2439 
2440  mNewMaskTree.merge(rhs.mNewMaskTree);
2441  }
2442 
2443  void operator()(const tbb::blocked_range<size_t>& range)
2444  {
2445  tree::ValueAccessor<BoolTreeType> newMaskAcc(mNewMaskTree);
2446  tree::ValueAccessor<TreeType> distAcc(*mDistTree);
2447  tree::ValueAccessor<Int32TreeType> indexAcc(*mIndexTree);
2448 
2449  std::vector<Fragment> fragments;
2450  fragments.reserve(256);
2451 
2452  std::unique_ptr<LeafNodeType> newDistNodePt;
2453  std::unique_ptr<Int32LeafNodeType> newIndexNodePt;
2454 
2455  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2456 
2457  BoolLeafNodeType& maskNode = *mMaskNodes[n];
2458  if (maskNode.isEmpty()) continue;
2459 
2460  // Setup local caches
2461 
2462  const Coord& origin = maskNode.origin();
2463 
2464  LeafNodeType * distNodePt = distAcc.probeLeaf(origin);
2465  Int32LeafNodeType * indexNodePt = indexAcc.probeLeaf(origin);
2466 
2467  assert(!distNodePt == !indexNodePt);
2468 
2469  bool usingNewNodes = false;
2470 
2471  if (!distNodePt && !indexNodePt) {
2472 
2473  const ValueType backgroundDist = distAcc.getValue(origin);
2474 
2475  if (!newDistNodePt.get() && !newIndexNodePt.get()) {
2476  newDistNodePt.reset(new LeafNodeType(origin, backgroundDist));
2477  newIndexNodePt.reset(new Int32LeafNodeType(origin, indexAcc.getValue(origin)));
2478  } else {
2479 
2480  if ((backgroundDist < ValueType(0.0)) !=
2481  (newDistNodePt->getValue(0) < ValueType(0.0))) {
2482  newDistNodePt->buffer().fill(backgroundDist);
2483  }
2484 
2485  newDistNodePt->setOrigin(origin);
2486  newIndexNodePt->setOrigin(origin);
2487  }
2488 
2489  distNodePt = newDistNodePt.get();
2490  indexNodePt = newIndexNodePt.get();
2491 
2492  usingNewNodes = true;
2493  }
2494 
2495 
2496  // Gather neighbour information
2497 
2498  CoordBBox bbox(Coord::max(), Coord::min());
2499  for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2500  bbox.expand(it.getCoord());
2501  }
2502 
2503  bbox.expand(1);
2504 
2505  gatherFragments(fragments, bbox, distAcc, indexAcc);
2506 
2507 
2508  // Compute first voxel layer
2509 
2510  bbox = maskNode.getNodeBoundingBox();
2512  bool updatedLeafNodes = false;
2513 
2514  for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2515 
2516  const Coord ijk = it.getCoord();
2517 
2518  if (updateVoxel(ijk, 5, fragments, *distNodePt, *indexNodePt, &updatedLeafNodes)) {
2519 
2520  for (Int32 i = 0; i < 6; ++i) {
2521  const Coord nijk = ijk + util::COORD_OFFSETS[i];
2522  if (bbox.isInside(nijk)) {
2523  mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2524  } else {
2525  newMaskAcc.setValueOn(nijk);
2526  }
2527  }
2528 
2529  for (Int32 i = 6; i < 26; ++i) {
2530  const Coord nijk = ijk + util::COORD_OFFSETS[i];
2531  if (bbox.isInside(nijk)) {
2532  mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2533  }
2534  }
2535  }
2536  }
2537 
2538  if (updatedLeafNodes) {
2539 
2540  // Compute second voxel layer
2541  mask -= indexNodePt->getValueMask();
2542 
2543  for (typename NodeMaskType::OnIterator it = mask.beginOn(); it; ++it) {
2544 
2545  const Index pos = it.pos();
2546  const Coord ijk = maskNode.origin() + LeafNodeType::offsetToLocalCoord(pos);
2547 
2548  if (updateVoxel(ijk, 6, fragments, *distNodePt, *indexNodePt)) {
2549  for (Int32 i = 0; i < 6; ++i) {
2550  newMaskAcc.setValueOn(ijk + util::COORD_OFFSETS[i]);
2551  }
2552  }
2553  }
2554 
2555  // Export new distance values
2556  if (usingNewNodes) {
2557  newDistNodePt->topologyUnion(*newIndexNodePt);
2558  mDistNodes.push_back(newDistNodePt.release());
2559  mIndexNodes.push_back(newIndexNodePt.release());
2560  } else {
2561  mUpdatedDistNodes.push_back(distNodePt);
2562  mUpdatedIndexNodes.push_back(indexNodePt);
2563  }
2564  }
2565  } // end leafnode loop
2566  }
2567 
2568  //////////
2569 
2570  BoolTreeType& newMaskTree() { return mNewMaskTree; }
2571 
2572  std::vector<LeafNodeType*>& newDistNodes() { return mDistNodes; }
2573  std::vector<LeafNodeType*>& updatedDistNodes() { return mUpdatedDistNodes; }
2574 
2575  std::vector<Int32LeafNodeType*>& newIndexNodes() { return mIndexNodes; }
2576  std::vector<Int32LeafNodeType*>& updatedIndexNodes() { return mUpdatedIndexNodes; }
2577 
2578 private:
2579 
2580  /// @note The output fragment list is ordered by the primitive index
2581  void
2582  gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2584  {
2585  fragments.clear();
2586  const Coord nodeMin = bbox.min() & ~(LeafNodeType::DIM - 1);
2587  const Coord nodeMax = bbox.max() & ~(LeafNodeType::DIM - 1);
2588 
2589  CoordBBox region;
2590  Coord ijk;
2591 
2592  for (ijk[0] = nodeMin[0]; ijk[0] <= nodeMax[0]; ijk[0] += LeafNodeType::DIM) {
2593  for (ijk[1] = nodeMin[1]; ijk[1] <= nodeMax[1]; ijk[1] += LeafNodeType::DIM) {
2594  for (ijk[2] = nodeMin[2]; ijk[2] <= nodeMax[2]; ijk[2] += LeafNodeType::DIM) {
2595  if (LeafNodeType* distleaf = distAcc.probeLeaf(ijk)) {
2596  region.min() = Coord::maxComponent(bbox.min(), ijk);
2597  region.max() = Coord::minComponent(bbox.max(),
2598  ijk.offsetBy(LeafNodeType::DIM - 1));
2599  gatherFragments(fragments, region, *distleaf, *indexAcc.probeLeaf(ijk));
2600  }
2601  }
2602  }
2603  }
2604 
2605  std::sort(fragments.begin(), fragments.end());
2606  }
2607 
2608  void
2609  gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2610  const LeafNodeType& distLeaf, const Int32LeafNodeType& idxLeaf) const
2611  {
2612  const typename LeafNodeType::NodeMaskType& mask = distLeaf.getValueMask();
2613  const ValueType* distData = distLeaf.buffer().data();
2614  const Int32* idxData = idxLeaf.buffer().data();
2615 
2616  for (int x = bbox.min()[0]; x <= bbox.max()[0]; ++x) {
2617  const Index xPos = (x & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
2618  for (int y = bbox.min()[1]; y <= bbox.max()[1]; ++y) {
2619  const Index yPos = xPos + ((y & (LeafNodeType::DIM - 1u)) << LeafNodeType::LOG2DIM);
2620  for (int z = bbox.min()[2]; z <= bbox.max()[2]; ++z) {
2621  const Index pos = yPos + (z & (LeafNodeType::DIM - 1u));
2622  if (mask.isOn(pos)) {
2623  fragments.push_back(Fragment(idxData[pos],x,y,z, std::abs(distData[pos])));
2624  }
2625  }
2626  }
2627  }
2628  }
2629 
2630  /// @note This method expects the fragment list to be ordered by the primitive index
2631  /// to avoid redundant distance computations.
2632  ValueType
2633  computeDistance(const Coord& ijk, const Int32 manhattanLimit,
2634  const std::vector<Fragment>& fragments, Int32& closestPrimIdx) const
2635  {
2636  Vec3d a, b, c, uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2637  double primDist, tmpDist, dist = std::numeric_limits<double>::max();
2638  Int32 lastIdx = Int32(util::INVALID_IDX);
2639 
2640  for (size_t n = 0, N = fragments.size(); n < N; ++n) {
2641 
2642  const Fragment& fragment = fragments[n];
2643  if (lastIdx == fragment.idx) continue;
2644 
2645  const Int32 dx = std::abs(fragment.x - ijk[0]);
2646  const Int32 dy = std::abs(fragment.y - ijk[1]);
2647  const Int32 dz = std::abs(fragment.z - ijk[2]);
2648 
2649  const Int32 manhattan = dx + dy + dz;
2650  if (manhattan > manhattanLimit) continue;
2651 
2652  lastIdx = fragment.idx;
2653 
2654  const size_t polygon = size_t(lastIdx);
2655 
2656  mMesh->getIndexSpacePoint(polygon, 0, a);
2657  mMesh->getIndexSpacePoint(polygon, 1, b);
2658  mMesh->getIndexSpacePoint(polygon, 2, c);
2659 
2660  primDist = (voxelCenter -
2661  closestPointOnTriangleToPoint(a, c, b, voxelCenter, uvw)).lengthSqr();
2662 
2663  // Split quad into a second triangle
2664  if (4 == mMesh->vertexCount(polygon)) {
2665 
2666  mMesh->getIndexSpacePoint(polygon, 3, b);
2667 
2668  tmpDist = (voxelCenter - closestPointOnTriangleToPoint(
2669  a, b, c, voxelCenter, uvw)).lengthSqr();
2670 
2671  if (tmpDist < primDist) primDist = tmpDist;
2672  }
2673 
2674  if (primDist < dist) {
2675  dist = primDist;
2676  closestPrimIdx = lastIdx;
2677  }
2678  }
2679 
2680  return ValueType(std::sqrt(dist)) * mVoxelSize;
2681  }
2682 
2683  /// @note Returns true if the current voxel was updated and neighbouring
2684  /// voxels need to be evaluated.
2685  bool
2686  updateVoxel(const Coord& ijk, const Int32 manhattanLimit,
2687  const std::vector<Fragment>& fragments,
2688  LeafNodeType& distLeaf, Int32LeafNodeType& idxLeaf, bool* updatedLeafNodes = nullptr)
2689  {
2690  Int32 closestPrimIdx = 0;
2691  const ValueType distance = computeDistance(ijk, manhattanLimit, fragments, closestPrimIdx);
2692 
2693  const Index pos = LeafNodeType::coordToOffset(ijk);
2694  const bool inside = distLeaf.getValue(pos) < ValueType(0.0);
2695 
2696  bool activateNeighbourVoxels = false;
2697 
2698  if (!inside && distance < mExteriorBandWidth) {
2699  if (updatedLeafNodes) *updatedLeafNodes = true;
2700  activateNeighbourVoxels = (distance + mVoxelSize) < mExteriorBandWidth;
2701  distLeaf.setValueOnly(pos, distance);
2702  idxLeaf.setValueOn(pos, closestPrimIdx);
2703  } else if (inside && distance < mInteriorBandWidth) {
2704  if (updatedLeafNodes) *updatedLeafNodes = true;
2705  activateNeighbourVoxels = (distance + mVoxelSize) < mInteriorBandWidth;
2706  distLeaf.setValueOnly(pos, -distance);
2707  idxLeaf.setValueOn(pos, closestPrimIdx);
2708  }
2709 
2710  return activateNeighbourVoxels;
2711  }
2712 
2713  //////////
2714 
2715  BoolLeafNodeType ** const mMaskNodes;
2716  BoolTreeType * const mMaskTree;
2717  TreeType * const mDistTree;
2718  Int32TreeType * const mIndexTree;
2719 
2720  MeshDataAdapter const * const mMesh;
2721 
2722  BoolTreeType mNewMaskTree;
2723 
2724  std::vector<LeafNodeType*> mDistNodes, mUpdatedDistNodes;
2725  std::vector<Int32LeafNodeType*> mIndexNodes, mUpdatedIndexNodes;
2726 
2727  const ValueType mExteriorBandWidth, mInteriorBandWidth, mVoxelSize;
2728 }; // struct ExpandNarrowband
2729 
2730 
2731 template<typename TreeType>
2732 struct AddNodes {
2733  using LeafNodeType = typename TreeType::LeafNodeType;
2734 
2735  AddNodes(TreeType& tree, std::vector<LeafNodeType*>& nodes)
2736  : mTree(&tree) , mNodes(&nodes)
2737  {
2738  }
2739 
2740  void operator()() const {
2742  std::vector<LeafNodeType*>& nodes = *mNodes;
2743  for (size_t n = 0, N = nodes.size(); n < N; ++n) {
2744  acc.addLeaf(nodes[n]);
2745  }
2746  }
2747 
2748  TreeType * const mTree;
2749  std::vector<LeafNodeType*> * const mNodes;
2750 }; // AddNodes
2751 
2752 
2753 template<typename TreeType, typename Int32TreeType, typename BoolTreeType, typename MeshDataAdapter>
2754 inline void
2756  TreeType& distTree,
2757  Int32TreeType& indexTree,
2758  BoolTreeType& maskTree,
2759  std::vector<typename BoolTreeType::LeafNodeType*>& maskNodes,
2760  const MeshDataAdapter& mesh,
2761  typename TreeType::ValueType exteriorBandWidth,
2762  typename TreeType::ValueType interiorBandWidth,
2763  typename TreeType::ValueType voxelSize)
2764 {
2765  ExpandNarrowband<TreeType, MeshDataAdapter> expandOp(maskNodes, maskTree,
2766  distTree, indexTree, mesh, exteriorBandWidth, interiorBandWidth, voxelSize);
2767 
2768  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, maskNodes.size()), expandOp);
2769 
2770  tbb::parallel_for(tbb::blocked_range<size_t>(0, expandOp.updatedIndexNodes().size()),
2772  expandOp.updatedDistNodes(), expandOp.updatedIndexNodes()));
2773 
2774  tbb::task_group tasks;
2775  tasks.run(AddNodes<TreeType>(distTree, expandOp.newDistNodes()));
2776  tasks.run(AddNodes<Int32TreeType>(indexTree, expandOp.newIndexNodes()));
2777  tasks.wait();
2778 
2779  maskTree.clear();
2780  maskTree.merge(expandOp.newMaskTree());
2781 }
2782 
2783 
2784 ////////////////////////////////////////
2785 
2786 
2787 // Transform values (sqrt, world space scaling and sign flip if sdf)
2788 template<typename TreeType>
2790 {
2791  using LeafNodeType = typename TreeType::LeafNodeType;
2792  using ValueType = typename TreeType::ValueType;
2793 
2794  TransformValues(std::vector<LeafNodeType*>& nodes,
2795  ValueType voxelSize, bool unsignedDist)
2796  : mNodes(&nodes[0])
2797  , mVoxelSize(voxelSize)
2798  , mUnsigned(unsignedDist)
2799  {
2800  }
2801 
2802  void operator()(const tbb::blocked_range<size_t>& range) const {
2803 
2804  typename LeafNodeType::ValueOnIter iter;
2805 
2806  const bool udf = mUnsigned;
2807  const ValueType w[2] = { -mVoxelSize, mVoxelSize };
2808 
2809  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2810 
2811  for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2812  ValueType& val = const_cast<ValueType&>(iter.getValue());
2813  val = w[udf || (val < ValueType(0.0))] * std::sqrt(std::abs(val));
2814  }
2815  }
2816  }
2817 
2818 private:
2819  LeafNodeType * * const mNodes;
2820  const ValueType mVoxelSize;
2821  const bool mUnsigned;
2822 };
2823 
2824 
2825 // Inactivate values outside the (exBandWidth, inBandWidth) range.
2826 template<typename TreeType>
2828 {
2829  using LeafNodeType = typename TreeType::LeafNodeType;
2830  using ValueType = typename TreeType::ValueType;
2831 
2832  InactivateValues(std::vector<LeafNodeType*>& nodes,
2833  ValueType exBandWidth, ValueType inBandWidth)
2834  : mNodes(nodes.empty() ? nullptr : &nodes[0])
2835  , mExBandWidth(exBandWidth)
2836  , mInBandWidth(inBandWidth)
2837  {
2838  }
2839 
2840  void operator()(const tbb::blocked_range<size_t>& range) const {
2841 
2842  typename LeafNodeType::ValueOnIter iter;
2843  const ValueType exVal = mExBandWidth;
2844  const ValueType inVal = -mInBandWidth;
2845 
2846  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2847 
2848  for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2849 
2850  ValueType& val = const_cast<ValueType&>(iter.getValue());
2851 
2852  const bool inside = val < ValueType(0.0);
2853 
2854  if (inside && !(val > inVal)) {
2855  val = inVal;
2856  iter.setValueOff();
2857  } else if (!inside && !(val < exVal)) {
2858  val = exVal;
2859  iter.setValueOff();
2860  }
2861  }
2862  }
2863  }
2864 
2865 private:
2866  LeafNodeType * * const mNodes;
2867  const ValueType mExBandWidth, mInBandWidth;
2868 };
2869 
2870 
2871 template<typename TreeType>
2873 {
2874  using LeafNodeType = typename TreeType::LeafNodeType;
2875  using ValueType = typename TreeType::ValueType;
2876 
2877  OffsetValues(std::vector<LeafNodeType*>& nodes, ValueType offset)
2878  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mOffset(offset)
2879  {
2880  }
2881 
2882  void operator()(const tbb::blocked_range<size_t>& range) const {
2883 
2884  const ValueType offset = mOffset;
2885 
2886  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2887 
2888  typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
2889 
2890  for (; iter; ++iter) {
2891  ValueType& val = const_cast<ValueType&>(iter.getValue());
2892  val += offset;
2893  }
2894  }
2895  }
2896 
2897 private:
2898  LeafNodeType * * const mNodes;
2899  const ValueType mOffset;
2900 };
2901 
2902 
2903 template<typename TreeType>
2905 {
2906  using LeafNodeType = typename TreeType::LeafNodeType;
2907  using ValueType = typename TreeType::ValueType;
2908 
2909  Renormalize(const TreeType& tree, const std::vector<LeafNodeType*>& nodes,
2910  ValueType* buffer, ValueType voxelSize)
2911  : mTree(&tree)
2912  , mNodes(nodes.empty() ? nullptr : &nodes[0])
2913  , mBuffer(buffer)
2914  , mVoxelSize(voxelSize)
2915  {
2916  }
2917 
2918  void operator()(const tbb::blocked_range<size_t>& range) const
2919  {
2920  using Vec3Type = math::Vec3<ValueType>;
2921 
2923 
2924  Coord ijk;
2925  Vec3Type up, down;
2926 
2927  const ValueType dx = mVoxelSize, invDx = ValueType(1.0) / mVoxelSize;
2928 
2929  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2930 
2931  ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
2932 
2933  typename LeafNodeType::ValueOnCIter iter = mNodes[n]->cbeginValueOn();
2934  for (; iter; ++iter) {
2935 
2936  const ValueType phi0 = *iter;
2937 
2938  ijk = iter.getCoord();
2939 
2940  up[0] = acc.getValue(ijk.offsetBy(1, 0, 0)) - phi0;
2941  up[1] = acc.getValue(ijk.offsetBy(0, 1, 0)) - phi0;
2942  up[2] = acc.getValue(ijk.offsetBy(0, 0, 1)) - phi0;
2943 
2944  down[0] = phi0 - acc.getValue(ijk.offsetBy(-1, 0, 0));
2945  down[1] = phi0 - acc.getValue(ijk.offsetBy(0, -1, 0));
2946  down[2] = phi0 - acc.getValue(ijk.offsetBy(0, 0, -1));
2947 
2948  const ValueType normSqGradPhi = math::GodunovsNormSqrd(phi0 > 0.0, down, up);
2949 
2950  const ValueType diff = math::Sqrt(normSqGradPhi) * invDx - ValueType(1.0);
2951  const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
2952 
2953  bufferData[iter.pos()] = phi0 - dx * S * diff;
2954  }
2955  }
2956  }
2957 
2958 private:
2959  TreeType const * const mTree;
2960  LeafNodeType const * const * const mNodes;
2961  ValueType * const mBuffer;
2962 
2963  const ValueType mVoxelSize;
2964 };
2965 
2966 
2967 template<typename TreeType>
2969 {
2970  using LeafNodeType = typename TreeType::LeafNodeType;
2971  using ValueType = typename TreeType::ValueType;
2972 
2973  MinCombine(std::vector<LeafNodeType*>& nodes, const ValueType* buffer)
2974  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mBuffer(buffer)
2975  {
2976  }
2977 
2978  void operator()(const tbb::blocked_range<size_t>& range) const {
2979 
2980  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2981 
2982  const ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
2983 
2984  typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
2985 
2986  for (; iter; ++iter) {
2987  ValueType& val = const_cast<ValueType&>(iter.getValue());
2988  val = std::min(val, bufferData[iter.pos()]);
2989  }
2990  }
2991  }
2992 
2993 private:
2994  LeafNodeType * * const mNodes;
2995  ValueType const * const mBuffer;
2996 };
2997 
2998 
2999 } // mesh_to_volume_internal namespace
3000 
3001 
3002 ////////////////////////////////////////
3003 
3004 // Utility method implementation
3005 
3006 
3007 template <typename FloatTreeT>
3008 inline void
3009 traceExteriorBoundaries(FloatTreeT& tree)
3010 {
3012 
3013  ConnectivityTable nodeConnectivity(tree);
3014 
3015  std::vector<size_t> zStartNodes, yStartNodes, xStartNodes;
3016 
3017  for (size_t n = 0; n < nodeConnectivity.size(); ++n) {
3018  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevX()[n]) {
3019  xStartNodes.push_back(n);
3020  }
3021 
3022  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevY()[n]) {
3023  yStartNodes.push_back(n);
3024  }
3025 
3026  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevZ()[n]) {
3027  zStartNodes.push_back(n);
3028  }
3029  }
3030 
3032 
3033  tbb::parallel_for(tbb::blocked_range<size_t>(0, zStartNodes.size()),
3034  SweepingOp(SweepingOp::Z_AXIS, zStartNodes, nodeConnectivity));
3035 
3036  tbb::parallel_for(tbb::blocked_range<size_t>(0, yStartNodes.size()),
3037  SweepingOp(SweepingOp::Y_AXIS, yStartNodes, nodeConnectivity));
3038 
3039  tbb::parallel_for(tbb::blocked_range<size_t>(0, xStartNodes.size()),
3040  SweepingOp(SweepingOp::X_AXIS, xStartNodes, nodeConnectivity));
3041 
3042  const size_t numLeafNodes = nodeConnectivity.size();
3043  const size_t numVoxels = numLeafNodes * FloatTreeT::LeafNodeType::SIZE;
3044 
3045  std::unique_ptr<bool[]> changedNodeMaskA{new bool[numLeafNodes]};
3046  std::unique_ptr<bool[]> changedNodeMaskB{new bool[numLeafNodes]};
3047  std::unique_ptr<bool[]> changedVoxelMask{new bool[numVoxels]};
3048 
3049  mesh_to_volume_internal::fillArray(changedNodeMaskA.get(), true, numLeafNodes);
3050  mesh_to_volume_internal::fillArray(changedNodeMaskB.get(), false, numLeafNodes);
3051  mesh_to_volume_internal::fillArray(changedVoxelMask.get(), false, numVoxels);
3052 
3053  const tbb::blocked_range<size_t> nodeRange(0, numLeafNodes);
3054 
3055  bool nodesUpdated = false;
3056  do {
3057  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedFillExteriorSign<FloatTreeT>(
3058  nodeConnectivity.nodes(), changedNodeMaskA.get()));
3059 
3060  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedPoints<FloatTreeT>(
3061  nodeConnectivity, changedNodeMaskA.get(), changedNodeMaskB.get(),
3062  changedVoxelMask.get()));
3063 
3064  changedNodeMaskA.swap(changedNodeMaskB);
3065 
3066  nodesUpdated = false;
3067  for (size_t n = 0; n < numLeafNodes; ++n) {
3068  nodesUpdated |= changedNodeMaskA[n];
3069  if (nodesUpdated) break;
3070  }
3071 
3072  if (nodesUpdated) {
3073  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SyncVoxelMask<FloatTreeT>(
3074  nodeConnectivity.nodes(), changedNodeMaskA.get(), changedVoxelMask.get()));
3075  }
3076  } while (nodesUpdated);
3077 
3078 } // void traceExteriorBoundaries()
3079 
3080 
3081 ////////////////////////////////////////
3082 
3083 
3084 template <typename GridType, typename MeshDataAdapter, typename Interrupter>
3085 inline typename GridType::Ptr
3087  Interrupter& interrupter,
3088  const MeshDataAdapter& mesh,
3089  const math::Transform& transform,
3090  float exteriorBandWidth,
3091  float interiorBandWidth,
3092  int flags,
3093  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
3094 {
3095  using GridTypePtr = typename GridType::Ptr;
3096  using TreeType = typename GridType::TreeType;
3097  using LeafNodeType = typename TreeType::LeafNodeType;
3098  using ValueType = typename GridType::ValueType;
3099 
3100  using Int32GridType = typename GridType::template ValueConverter<Int32>::Type;
3101  using Int32TreeType = typename Int32GridType::TreeType;
3102 
3103  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
3104 
3105  //////////
3106 
3107  // Setup
3108 
3109  GridTypePtr distGrid(new GridType(std::numeric_limits<ValueType>::max()));
3110  distGrid->setTransform(transform.copy());
3111 
3112  ValueType exteriorWidth = ValueType(exteriorBandWidth);
3113  ValueType interiorWidth = ValueType(interiorBandWidth);
3114 
3115  // Note: inf interior width is all right, this value makes the converter fill
3116  // interior regions with distance values.
3117  if (!std::isfinite(exteriorWidth) || std::isnan(interiorWidth)) {
3118  std::stringstream msg;
3119  msg << "Illegal narrow band width: exterior = " << exteriorWidth
3120  << ", interior = " << interiorWidth;
3121  OPENVDB_LOG_DEBUG(msg.str());
3122  return distGrid;
3123  }
3124 
3125  const ValueType voxelSize = ValueType(transform.voxelSize()[0]);
3126 
3127  if (!std::isfinite(voxelSize) || math::isZero(voxelSize)) {
3128  std::stringstream msg;
3129  msg << "Illegal transform, voxel size = " << voxelSize;
3130  OPENVDB_LOG_DEBUG(msg.str());
3131  return distGrid;
3132  }
3133 
3134  // Convert narrow band width from voxel units to world space units.
3135  exteriorWidth *= voxelSize;
3136  // Avoid the unit conversion if the interior band width is set to
3137  // inf or std::numeric_limits<float>::max().
3138  if (interiorWidth < std::numeric_limits<ValueType>::max()) {
3139  interiorWidth *= voxelSize;
3140  }
3141 
3142  const bool computeSignedDistanceField = (flags & UNSIGNED_DISTANCE_FIELD) == 0;
3143  const bool removeIntersectingVoxels = (flags & DISABLE_INTERSECTING_VOXEL_REMOVAL) == 0;
3144  const bool renormalizeValues = (flags & DISABLE_RENORMALIZATION) == 0;
3145  const bool trimNarrowBand = (flags & DISABLE_NARROW_BAND_TRIMMING) == 0;
3146 
3147  Int32GridType* indexGrid = nullptr;
3148 
3149  typename Int32GridType::Ptr temporaryIndexGrid;
3150 
3151  if (polygonIndexGrid) {
3152  indexGrid = polygonIndexGrid;
3153  } else {
3154  temporaryIndexGrid.reset(new Int32GridType(Int32(util::INVALID_IDX)));
3155  indexGrid = temporaryIndexGrid.get();
3156  }
3157 
3158  indexGrid->newTree();
3159  indexGrid->setTransform(transform.copy());
3160 
3161  if (computeSignedDistanceField) {
3162  distGrid->setGridClass(GRID_LEVEL_SET);
3163  } else {
3164  distGrid->setGridClass(GRID_UNKNOWN);
3165  interiorWidth = ValueType(0.0);
3166  }
3167 
3168  TreeType& distTree = distGrid->tree();
3169  Int32TreeType& indexTree = indexGrid->tree();
3170 
3171 
3172  //////////
3173 
3174  // Voxelize mesh
3175 
3176  {
3177  using VoxelizationDataType = mesh_to_volume_internal::VoxelizationData<TreeType>;
3178  using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
3179 
3180  DataTable data;
3181  using Voxelizer =
3183 
3184  const tbb::blocked_range<size_t> polygonRange(0, mesh.polygonCount());
3185 
3186  tbb::parallel_for(polygonRange, Voxelizer(data, mesh, &interrupter));
3187 
3188  for (typename DataTable::iterator i = data.begin(); i != data.end(); ++i) {
3189  VoxelizationDataType& dataItem = **i;
3191  distTree, indexTree, dataItem.distTree, dataItem.indexTree);
3192  }
3193  }
3194 
3195  // The progress estimates are based on the observed average time for a few different
3196  // test cases and is only intended to provide some rough progression feedback to the user.
3197  if (interrupter.wasInterrupted(30)) return distGrid;
3198 
3199 
3200  //////////
3201 
3202  // Classify interior and exterior regions
3203 
3204  if (computeSignedDistanceField) {
3205 
3206  // Determines the inside/outside state for the narrow band of voxels.
3207  traceExteriorBoundaries(distTree);
3208 
3209  std::vector<LeafNodeType*> nodes;
3210  nodes.reserve(distTree.leafCount());
3211  distTree.getNodes(nodes);
3212 
3213  const tbb::blocked_range<size_t> nodeRange(0, nodes.size());
3214 
3215  using SignOp =
3217 
3218  tbb::parallel_for(nodeRange, SignOp(nodes, distTree, indexTree, mesh));
3219 
3220  if (interrupter.wasInterrupted(45)) return distGrid;
3221 
3222  // Remove voxels created by self intersecting portions of the mesh.
3223  if (removeIntersectingVoxels) {
3224 
3225  tbb::parallel_for(nodeRange,
3227 
3228  tbb::parallel_for(nodeRange,
3230  nodes, distTree, indexTree));
3231 
3232  tools::pruneInactive(distTree, /*threading=*/true);
3233  tools::pruneInactive(indexTree, /*threading=*/true);
3234  }
3235  }
3236 
3237  if (interrupter.wasInterrupted(50)) return distGrid;
3238 
3239  if (distTree.activeVoxelCount() == 0) {
3240  distTree.clear();
3241  distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3242  return distGrid;
3243  }
3244 
3245  // Transform values (world space scaling etc.).
3246  {
3247  std::vector<LeafNodeType*> nodes;
3248  nodes.reserve(distTree.leafCount());
3249  distTree.getNodes(nodes);
3250 
3251  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3253  nodes, voxelSize, !computeSignedDistanceField));
3254  }
3255 
3256  // Propagate sign information into tile regions.
3257  if (computeSignedDistanceField) {
3258  distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3259  tools::signedFloodFillWithValues(distTree, exteriorWidth, -interiorWidth);
3260  } else {
3261  tools::changeBackground(distTree, exteriorWidth);
3262  }
3263 
3264  if (interrupter.wasInterrupted(54)) return distGrid;
3265 
3266 
3267  //////////
3268 
3269  // Expand the narrow band region
3270 
3271  const ValueType minBandWidth = voxelSize * ValueType(2.0);
3272 
3273  if (interiorWidth > minBandWidth || exteriorWidth > minBandWidth) {
3274 
3275  // Create the initial voxel mask.
3276  BoolTreeType maskTree(false);
3277 
3278  {
3279  std::vector<LeafNodeType*> nodes;
3280  nodes.reserve(distTree.leafCount());
3281  distTree.getNodes(nodes);
3282 
3283  mesh_to_volume_internal::ConstructVoxelMask<TreeType> op(maskTree, distTree, nodes);
3284  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, nodes.size()), op);
3285  }
3286 
3287  // Progress estimation
3288  unsigned maxIterations = std::numeric_limits<unsigned>::max();
3289 
3290  float progress = 54.0f, step = 0.0f;
3291  double estimated =
3292  2.0 * std::ceil((std::max(interiorWidth, exteriorWidth) - minBandWidth) / voxelSize);
3293 
3294  if (estimated < double(maxIterations)) {
3295  maxIterations = unsigned(estimated);
3296  step = 40.0f / float(maxIterations);
3297  }
3298 
3299  std::vector<typename BoolTreeType::LeafNodeType*> maskNodes;
3300 
3301  unsigned count = 0;
3302  while (true) {
3303 
3304  if (interrupter.wasInterrupted(int(progress))) return distGrid;
3305 
3306  const size_t maskNodeCount = maskTree.leafCount();
3307  if (maskNodeCount == 0) break;
3308 
3309  maskNodes.clear();
3310  maskNodes.reserve(maskNodeCount);
3311  maskTree.getNodes(maskNodes);
3312 
3313  const tbb::blocked_range<size_t> range(0, maskNodes.size());
3314 
3315  tbb::parallel_for(range,
3317 
3318  mesh_to_volume_internal::expandNarrowband(distTree, indexTree, maskTree, maskNodes,
3319  mesh, exteriorWidth, interiorWidth, voxelSize);
3320 
3321  if ((++count) >= maxIterations) break;
3322  progress += step;
3323  }
3324  }
3325 
3326  if (interrupter.wasInterrupted(94)) return distGrid;
3327 
3328  if (!polygonIndexGrid) indexGrid->clear();
3329 
3330 
3331  /////////
3332 
3333  // Renormalize distances to smooth out bumps caused by self intersecting
3334  // and overlapping portions of the mesh and renormalize the level set.
3335 
3336  if (computeSignedDistanceField && renormalizeValues) {
3337 
3338  std::vector<LeafNodeType*> nodes;
3339  nodes.reserve(distTree.leafCount());
3340  distTree.getNodes(nodes);
3341 
3342  std::unique_ptr<ValueType[]> buffer{new ValueType[LeafNodeType::SIZE * nodes.size()]};
3343 
3344  const ValueType offset = ValueType(0.8 * voxelSize);
3345 
3346  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3348 
3349  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3351  distTree, nodes, buffer.get(), voxelSize));
3352 
3353  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3355 
3356  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3359  }
3360 
3361  if (interrupter.wasInterrupted(99)) return distGrid;
3362 
3363 
3364  /////////
3365 
3366  // Remove active voxels that exceed the narrow band limits
3367 
3368  if (trimNarrowBand && std::min(interiorWidth, exteriorWidth) < voxelSize * ValueType(4.0)) {
3369 
3370  std::vector<LeafNodeType*> nodes;
3371  nodes.reserve(distTree.leafCount());
3372  distTree.getNodes(nodes);
3373 
3374  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3376  nodes, exteriorWidth, computeSignedDistanceField ? interiorWidth : exteriorWidth));
3377 
3379  distTree, exteriorWidth, computeSignedDistanceField ? -interiorWidth : -exteriorWidth);
3380  }
3381 
3382  return distGrid;
3383 }
3384 
3385 
3386 template <typename GridType, typename MeshDataAdapter>
3387 inline typename GridType::Ptr
3389  const MeshDataAdapter& mesh,
3390  const math::Transform& transform,
3391  float exteriorBandWidth,
3392  float interiorBandWidth,
3393  int flags,
3394  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
3395 {
3396  util::NullInterrupter nullInterrupter;
3397  return meshToVolume<GridType>(nullInterrupter, mesh, transform,
3398  exteriorBandWidth, interiorBandWidth, flags, polygonIndexGrid);
3399 }
3400 
3401 
3402 ////////////////////////////////////////
3403 
3404 
3405 //{
3406 /// @cond OPENVDB_MESH_TO_VOLUME_INTERNAL
3407 
3408 /// @internal This overload is enabled only for grids with a scalar, floating-point ValueType.
3409 template<typename GridType, typename Interrupter>
3411  typename GridType::Ptr>::type
3412 doMeshConversion(
3413  Interrupter& interrupter,
3414  const openvdb::math::Transform& xform,
3415  const std::vector<Vec3s>& points,
3416  const std::vector<Vec3I>& triangles,
3417  const std::vector<Vec4I>& quads,
3418  float exBandWidth,
3419  float inBandWidth,
3420  bool unsignedDistanceField = false)
3421 {
3422  if (points.empty()) {
3423  return typename GridType::Ptr(new GridType(typename GridType::ValueType(exBandWidth)));
3424  }
3425 
3426  const size_t numPoints = points.size();
3427  std::unique_ptr<Vec3s[]> indexSpacePoints{new Vec3s[numPoints]};
3428 
3429  // transform points to local grid index space
3430  tbb::parallel_for(tbb::blocked_range<size_t>(0, numPoints),
3431  mesh_to_volume_internal::TransformPoints<Vec3s>(
3432  &points[0], indexSpacePoints.get(), xform));
3433 
3434  const int conversionFlags = unsignedDistanceField ? UNSIGNED_DISTANCE_FIELD : 0;
3435 
3436  if (quads.empty()) {
3437 
3438  QuadAndTriangleDataAdapter<Vec3s, Vec3I>
3439  mesh(indexSpacePoints.get(), numPoints, &triangles[0], triangles.size());
3440 
3441  return meshToVolume<GridType>(
3442  interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3443 
3444  } else if (triangles.empty()) {
3445 
3446  QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3447  mesh(indexSpacePoints.get(), numPoints, &quads[0], quads.size());
3448 
3449  return meshToVolume<GridType>(
3450  interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3451  }
3452 
3453  // pack primitives
3454 
3455  const size_t numPrimitives = triangles.size() + quads.size();
3456  std::unique_ptr<Vec4I[]> prims{new Vec4I[numPrimitives]};
3457 
3458  for (size_t n = 0, N = triangles.size(); n < N; ++n) {
3459  const Vec3I& triangle = triangles[n];
3460  Vec4I& prim = prims[n];
3461  prim[0] = triangle[0];
3462  prim[1] = triangle[1];
3463  prim[2] = triangle[2];
3464  prim[3] = util::INVALID_IDX;
3465  }
3466 
3467  const size_t offset = triangles.size();
3468  for (size_t n = 0, N = quads.size(); n < N; ++n) {
3469  prims[offset + n] = quads[n];
3470  }
3471 
3472  QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3473  mesh(indexSpacePoints.get(), numPoints, prims.get(), numPrimitives);
3474 
3475  return meshToVolume<GridType>(interrupter, mesh, xform,
3476  exBandWidth, inBandWidth, conversionFlags);
3477 }
3478 
3479 
3480 /// @internal This overload is enabled only for grids that do not have a scalar,
3481 /// floating-point ValueType.
3482 template<typename GridType, typename Interrupter>
3484  typename GridType::Ptr>::type
3485 doMeshConversion(
3486  Interrupter&,
3487  const math::Transform& /*xform*/,
3488  const std::vector<Vec3s>& /*points*/,
3489  const std::vector<Vec3I>& /*triangles*/,
3490  const std::vector<Vec4I>& /*quads*/,
3491  float /*exBandWidth*/,
3492  float /*inBandWidth*/,
3493  bool /*unsignedDistanceField*/ = false)
3494 {
3495  OPENVDB_THROW(TypeError,
3496  "mesh to volume conversion is supported only for scalar floating-point grids");
3497 }
3498 
3499 /// @endcond
3500 //}
3501 
3502 
3503 ////////////////////////////////////////
3504 
3505 
3506 template<typename GridType>
3507 inline typename GridType::Ptr
3509  const openvdb::math::Transform& xform,
3510  const std::vector<Vec3s>& points,
3511  const std::vector<Vec3I>& triangles,
3512  float halfWidth)
3513 {
3514  util::NullInterrupter nullInterrupter;
3515  std::vector<Vec4I> quads(0);
3516  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3517  halfWidth, halfWidth);
3518 }
3519 
3520 
3521 template<typename GridType, typename Interrupter>
3522 inline typename GridType::Ptr
3524  Interrupter& interrupter,
3525  const openvdb::math::Transform& xform,
3526  const std::vector<Vec3s>& points,
3527  const std::vector<Vec3I>& triangles,
3528  float halfWidth)
3529 {
3530  std::vector<Vec4I> quads(0);
3531  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3532  halfWidth, halfWidth);
3533 }
3534 
3535 
3536 template<typename GridType>
3537 inline typename GridType::Ptr
3539  const openvdb::math::Transform& xform,
3540  const std::vector<Vec3s>& points,
3541  const std::vector<Vec4I>& quads,
3542  float halfWidth)
3543 {
3544  util::NullInterrupter nullInterrupter;
3545  std::vector<Vec3I> triangles(0);
3546  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3547  halfWidth, halfWidth);
3548 }
3549 
3550 
3551 template<typename GridType, typename Interrupter>
3552 inline typename GridType::Ptr
3554  Interrupter& interrupter,
3555  const openvdb::math::Transform& xform,
3556  const std::vector<Vec3s>& points,
3557  const std::vector<Vec4I>& quads,
3558  float halfWidth)
3559 {
3560  std::vector<Vec3I> triangles(0);
3561  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3562  halfWidth, halfWidth);
3563 }
3564 
3565 
3566 template<typename GridType>
3567 inline typename GridType::Ptr
3569  const openvdb::math::Transform& xform,
3570  const std::vector<Vec3s>& points,
3571  const std::vector<Vec3I>& triangles,
3572  const std::vector<Vec4I>& quads,
3573  float halfWidth)
3574 {
3575  util::NullInterrupter nullInterrupter;
3576  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3577  halfWidth, halfWidth);
3578 }
3579 
3580 
3581 template<typename GridType, typename Interrupter>
3582 inline typename GridType::Ptr
3584  Interrupter& interrupter,
3585  const openvdb::math::Transform& xform,
3586  const std::vector<Vec3s>& points,
3587  const std::vector<Vec3I>& triangles,
3588  const std::vector<Vec4I>& quads,
3589  float halfWidth)
3590 {
3591  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3592  halfWidth, halfWidth);
3593 }
3594 
3595 
3596 template<typename GridType>
3597 inline typename GridType::Ptr
3599  const openvdb::math::Transform& xform,
3600  const std::vector<Vec3s>& points,
3601  const std::vector<Vec3I>& triangles,
3602  const std::vector<Vec4I>& quads,
3603  float exBandWidth,
3604  float inBandWidth)
3605 {
3606  util::NullInterrupter nullInterrupter;
3607  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles,
3608  quads, exBandWidth, inBandWidth);
3609 }
3610 
3611 
3612 template<typename GridType, typename Interrupter>
3613 inline typename GridType::Ptr
3615  Interrupter& interrupter,
3616  const openvdb::math::Transform& xform,
3617  const std::vector<Vec3s>& points,
3618  const std::vector<Vec3I>& triangles,
3619  const std::vector<Vec4I>& quads,
3620  float exBandWidth,
3621  float inBandWidth)
3622 {
3623  return doMeshConversion<GridType>(interrupter, xform, points, triangles,
3624  quads, exBandWidth, inBandWidth);
3625 }
3626 
3627 
3628 template<typename GridType>
3629 inline typename GridType::Ptr
3631  const openvdb::math::Transform& xform,
3632  const std::vector<Vec3s>& points,
3633  const std::vector<Vec3I>& triangles,
3634  const std::vector<Vec4I>& quads,
3635  float bandWidth)
3636 {
3637  util::NullInterrupter nullInterrupter;
3638  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3639  bandWidth, bandWidth, true);
3640 }
3641 
3642 
3643 template<typename GridType, typename Interrupter>
3644 inline typename GridType::Ptr
3646  Interrupter& interrupter,
3647  const openvdb::math::Transform& xform,
3648  const std::vector<Vec3s>& points,
3649  const std::vector<Vec3I>& triangles,
3650  const std::vector<Vec4I>& quads,
3651  float bandWidth)
3652 {
3653  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3654  bandWidth, bandWidth, true);
3655 }
3656 
3657 
3658 ////////////////////////////////////////////////////////////////////////////////
3659 
3660 
3661 // Required by several of the tree nodes
3662 inline std::ostream&
3663 operator<<(std::ostream& ostr, const MeshToVoxelEdgeData::EdgeData& rhs)
3664 {
3665  ostr << "{[ " << rhs.mXPrim << ", " << rhs.mXDist << "]";
3666  ostr << " [ " << rhs.mYPrim << ", " << rhs.mYDist << "]";
3667  ostr << " [ " << rhs.mZPrim << ", " << rhs.mZDist << "]}";
3668  return ostr;
3669 }
3670 
3671 // Required by math::Abs
3672 inline MeshToVoxelEdgeData::EdgeData
3674 {
3675  return x;
3676 }
3677 
3678 
3679 ////////////////////////////////////////
3680 
3681 
3683 {
3684 public:
3685 
3686  GenEdgeData(
3687  const std::vector<Vec3s>& pointList,
3688  const std::vector<Vec4I>& polygonList);
3689 
3690  void run(bool threaded = true);
3691 
3692  GenEdgeData(GenEdgeData& rhs, tbb::split);
3693  inline void operator() (const tbb::blocked_range<size_t> &range);
3694  inline void join(GenEdgeData& rhs);
3695 
3696  inline TreeType& tree() { return mTree; }
3697 
3698 private:
3699  void operator=(const GenEdgeData&) {}
3700 
3701  struct Primitive { Vec3d a, b, c, d; Int32 index; };
3702 
3703  template<bool IsQuad>
3704  inline void voxelize(const Primitive&);
3705 
3706  template<bool IsQuad>
3707  inline bool evalPrimitive(const Coord&, const Primitive&);
3708 
3709  inline bool rayTriangleIntersection( const Vec3d& origin, const Vec3d& dir,
3710  const Vec3d& a, const Vec3d& b, const Vec3d& c, double& t);
3711 
3712 
3713  TreeType mTree;
3714  Accessor mAccessor;
3715 
3716  const std::vector<Vec3s>& mPointList;
3717  const std::vector<Vec4I>& mPolygonList;
3718 
3719  // Used internally for acceleration
3720  using IntTreeT = TreeType::ValueConverter<Int32>::Type;
3721  IntTreeT mLastPrimTree;
3722  tree::ValueAccessor<IntTreeT> mLastPrimAccessor;
3723 }; // class MeshToVoxelEdgeData::GenEdgeData
3724 
3725 
3726 inline
3728  const std::vector<Vec3s>& pointList,
3729  const std::vector<Vec4I>& polygonList)
3730  : mTree(EdgeData())
3731  , mAccessor(mTree)
3732  , mPointList(pointList)
3733  , mPolygonList(polygonList)
3734  , mLastPrimTree(Int32(util::INVALID_IDX))
3735  , mLastPrimAccessor(mLastPrimTree)
3736 {
3737 }
3738 
3739 
3740 inline
3742  : mTree(EdgeData())
3743  , mAccessor(mTree)
3744  , mPointList(rhs.mPointList)
3745  , mPolygonList(rhs.mPolygonList)
3746  , mLastPrimTree(Int32(util::INVALID_IDX))
3747  , mLastPrimAccessor(mLastPrimTree)
3748 {
3749 }
3750 
3751 
3752 inline void
3754 {
3755  if (threaded) {
3756  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mPolygonList.size()), *this);
3757  } else {
3758  (*this)(tbb::blocked_range<size_t>(0, mPolygonList.size()));
3759  }
3760 }
3761 
3762 
3763 inline void
3765 {
3766  using RootNodeType = TreeType::RootNodeType;
3767  using NodeChainType = RootNodeType::NodeChainType;
3768  static_assert(hboost::mpl::size<NodeChainType>::value > 1, "expected tree height > 1");
3769  using InternalNodeType = hboost::mpl::at<NodeChainType, hboost::mpl::int_<1> >::type;
3770 
3771  Coord ijk;
3772  Index offset;
3773 
3774  rhs.mTree.clearAllAccessors();
3775 
3776  TreeType::LeafIter leafIt = rhs.mTree.beginLeaf();
3777  for ( ; leafIt; ++leafIt) {
3778  ijk = leafIt->origin();
3779 
3780  TreeType::LeafNodeType* lhsLeafPt = mTree.probeLeaf(ijk);
3781 
3782  if (!lhsLeafPt) {
3783 
3784  mAccessor.addLeaf(rhs.mAccessor.probeLeaf(ijk));
3785  InternalNodeType* node = rhs.mAccessor.getNode<InternalNodeType>();
3786  node->stealNode<TreeType::LeafNodeType>(ijk, EdgeData(), false);
3787  rhs.mAccessor.clear();
3788 
3789  } else {
3790 
3791  TreeType::LeafNodeType::ValueOnCIter it = leafIt->cbeginValueOn();
3792  for ( ; it; ++it) {
3793 
3794  offset = it.pos();
3795  const EdgeData& rhsValue = it.getValue();
3796 
3797  if (!lhsLeafPt->isValueOn(offset)) {
3798  lhsLeafPt->setValueOn(offset, rhsValue);
3799  } else {
3800 
3801  EdgeData& lhsValue = const_cast<EdgeData&>(lhsLeafPt->getValue(offset));
3802 
3803  if (rhsValue.mXDist < lhsValue.mXDist) {
3804  lhsValue.mXDist = rhsValue.mXDist;
3805  lhsValue.mXPrim = rhsValue.mXPrim;
3806  }
3807 
3808  if (rhsValue.mYDist < lhsValue.mYDist) {
3809  lhsValue.mYDist = rhsValue.mYDist;
3810  lhsValue.mYPrim = rhsValue.mYPrim;
3811  }
3812 
3813  if (rhsValue.mZDist < lhsValue.mZDist) {
3814  lhsValue.mZDist = rhsValue.mZDist;
3815  lhsValue.mZPrim = rhsValue.mZPrim;
3816  }
3817 
3818  }
3819  } // end value iteration
3820  }
3821  } // end leaf iteration
3822 }
3823 
3824 
3825 inline void
3826 MeshToVoxelEdgeData::GenEdgeData::operator()(const tbb::blocked_range<size_t> &range)
3827 {
3828  Primitive prim;
3829 
3830  for (size_t n = range.begin(); n < range.end(); ++n) {
3831 
3832  const Vec4I& verts = mPolygonList[n];
3833 
3834  prim.index = Int32(n);
3835  prim.a = Vec3d(mPointList[verts[0]]);
3836  prim.b = Vec3d(mPointList[verts[1]]);
3837  prim.c = Vec3d(mPointList[verts[2]]);
3838 
3839  if (util::INVALID_IDX != verts[3]) {
3840  prim.d = Vec3d(mPointList[verts[3]]);
3841  voxelize<true>(prim);
3842  } else {
3843  voxelize<false>(prim);
3844  }
3845  }
3846 }
3847 
3848 
3849 template<bool IsQuad>
3850 inline void
3851 MeshToVoxelEdgeData::GenEdgeData::voxelize(const Primitive& prim)
3852 {
3853  std::deque<Coord> coordList;
3854  Coord ijk, nijk;
3855 
3856  ijk = Coord::floor(prim.a);
3857  coordList.push_back(ijk);
3858 
3859  evalPrimitive<IsQuad>(ijk, prim);
3860 
3861  while (!coordList.empty()) {
3862 
3863  ijk = coordList.back();
3864  coordList.pop_back();
3865 
3866  for (Int32 i = 0; i < 26; ++i) {
3867  nijk = ijk + util::COORD_OFFSETS[i];
3868 
3869  if (prim.index != mLastPrimAccessor.getValue(nijk)) {
3870  mLastPrimAccessor.setValue(nijk, prim.index);
3871  if(evalPrimitive<IsQuad>(nijk, prim)) coordList.push_back(nijk);
3872  }
3873  }
3874  }
3875 }
3876 
3877 
3878 template<bool IsQuad>
3879 inline bool
3880 MeshToVoxelEdgeData::GenEdgeData::evalPrimitive(const Coord& ijk, const Primitive& prim)
3881 {
3882  Vec3d uvw, org(ijk[0], ijk[1], ijk[2]);
3883  bool intersecting = false;
3884  double t;
3885 
3886  EdgeData edgeData;
3887  mAccessor.probeValue(ijk, edgeData);
3888 
3889  // Evaluate first triangle
3890  double dist = (org -
3891  closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, org, uvw)).lengthSqr();
3892 
3893  if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.c, prim.b, t)) {
3894  if (t < edgeData.mXDist) {
3895  edgeData.mXDist = float(t);
3896  edgeData.mXPrim = prim.index;
3897  intersecting = true;
3898  }
3899  }
3900 
3901  if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.c, prim.b, t)) {
3902  if (t < edgeData.mYDist) {
3903  edgeData.mYDist = float(t);
3904  edgeData.mYPrim = prim.index;
3905  intersecting = true;
3906  }
3907  }
3908 
3909  if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.c, prim.b, t)) {
3910  if (t < edgeData.mZDist) {
3911  edgeData.mZDist = float(t);
3912  edgeData.mZPrim = prim.index;
3913  intersecting = true;
3914  }
3915  }
3916 
3917  if (IsQuad) {
3918  // Split quad into a second triangle and calculate distance.
3919  double secondDist = (org -
3920  closestPointOnTriangleToPoint(prim.a, prim.d, prim.c, org, uvw)).lengthSqr();
3921 
3922  if (secondDist < dist) dist = secondDist;
3923 
3924  if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.d, prim.c, t)) {
3925  if (t < edgeData.mXDist) {
3926  edgeData.mXDist = float(t);
3927  edgeData.mXPrim = prim.index;
3928  intersecting = true;
3929  }
3930  }
3931 
3932  if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.d, prim.c, t)) {
3933  if (t < edgeData.mYDist) {
3934  edgeData.mYDist = float(t);
3935  edgeData.mYPrim = prim.index;
3936  intersecting = true;
3937  }
3938  }
3939 
3940  if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.d, prim.c, t)) {
3941  if (t < edgeData.mZDist) {
3942  edgeData.mZDist = float(t);
3943  edgeData.mZPrim = prim.index;
3944  intersecting = true;
3945  }
3946  }
3947  }
3948 
3949  if (intersecting) mAccessor.setValue(ijk, edgeData);
3950 
3951  return (dist < 0.86602540378443861);
3952 }
3953 
3954 
3955 inline bool
3956 MeshToVoxelEdgeData::GenEdgeData::rayTriangleIntersection(
3957  const Vec3d& origin, const Vec3d& dir,
3958  const Vec3d& a, const Vec3d& b, const Vec3d& c,
3959  double& t)
3960 {
3961  // Check if ray is parallel with triangle
3962 
3963  Vec3d e1 = b - a;
3964  Vec3d e2 = c - a;
3965  Vec3d s1 = dir.cross(e2);
3966 
3967  double divisor = s1.dot(e1);
3968  if (!(std::abs(divisor) > 0.0)) return false;
3969 
3970  // Compute barycentric coordinates
3971 
3972  double inv_divisor = 1.0 / divisor;
3973  Vec3d d = origin - a;
3974  double b1 = d.dot(s1) * inv_divisor;
3975 
3976  if (b1 < 0.0 || b1 > 1.0) return false;
3977 
3978  Vec3d s2 = d.cross(e1);
3979  double b2 = dir.dot(s2) * inv_divisor;
3980 
3981  if (b2 < 0.0 || (b1 + b2) > 1.0) return false;
3982 
3983  // Compute distance to intersection point
3984 
3985  t = e2.dot(s2) * inv_divisor;
3986  return (t < 0.0) ? false : true;
3987 }
3988 
3989 
3990 ////////////////////////////////////////
3991 
3992 
3993 inline
3995  : mTree(EdgeData())
3996 {
3997 }
3998 
3999 
4000 inline void
4002  const std::vector<Vec3s>& pointList,
4003  const std::vector<Vec4I>& polygonList)
4004 {
4005  GenEdgeData converter(pointList, polygonList);
4006  converter.run();
4007 
4008  mTree.clear();
4009  mTree.merge(converter.tree());
4010 }
4011 
4012 
4013 inline void
4015  Accessor& acc,
4016  const Coord& ijk,
4017  std::vector<Vec3d>& points,
4018  std::vector<Index32>& primitives)
4019 {
4020  EdgeData data;
4021  Vec3d point;
4022 
4023  Coord coord = ijk;
4024 
4025  if (acc.probeValue(coord, data)) {
4026 
4027  if (data.mXPrim != util::INVALID_IDX) {
4028  point[0] = double(coord[0]) + data.mXDist;
4029  point[1] = double(coord[1]);
4030  point[2] = double(coord[2]);
4031 
4032  points.push_back(point);
4033  primitives.push_back(data.mXPrim);
4034  }
4035 
4036  if (data.mYPrim != util::INVALID_IDX) {
4037  point[0] = double(coord[0]);
4038  point[1] = double(coord[1]) + data.mYDist;
4039  point[2] = double(coord[2]);
4040 
4041  points.push_back(point);
4042  primitives.push_back(data.mYPrim);
4043  }
4044 
4045  if (data.mZPrim != util::INVALID_IDX) {
4046  point[0] = double(coord[0]);
4047  point[1] = double(coord[1]);
4048  point[2] = double(coord[2]) + data.mZDist;
4049 
4050  points.push_back(point);
4051  primitives.push_back(data.mZPrim);
4052  }
4053 
4054  }
4055 
4056  coord[0] += 1;
4057 
4058  if (acc.probeValue(coord, data)) {
4059 
4060  if (data.mYPrim != util::INVALID_IDX) {
4061  point[0] = double(coord[0]);
4062  point[1] = double(coord[1]) + data.mYDist;
4063  point[2] = double(coord[2]);
4064 
4065  points.push_back(point);
4066  primitives.push_back(data.mYPrim);
4067  }
4068 
4069  if (data.mZPrim != util::INVALID_IDX) {
4070  point[0] = double(coord[0]);
4071  point[1] = double(coord[1]);
4072  point[2] = double(coord[2]) + data.mZDist;
4073 
4074  points.push_back(point);
4075  primitives.push_back(data.mZPrim);
4076  }
4077  }
4078 
4079  coord[2] += 1;
4080 
4081  if (acc.probeValue(coord, data)) {
4082  if (data.mYPrim != util::INVALID_IDX) {
4083  point[0] = double(coord[0]);
4084  point[1] = double(coord[1]) + data.mYDist;
4085  point[2] = double(coord[2]);
4086 
4087  points.push_back(point);
4088  primitives.push_back(data.mYPrim);
4089  }
4090  }
4091 
4092  coord[0] -= 1;
4093 
4094  if (acc.probeValue(coord, data)) {
4095 
4096  if (data.mXPrim != util::INVALID_IDX) {
4097  point[0] = double(coord[0]) + data.mXDist;
4098  point[1] = double(coord[1]);
4099  point[2] = double(coord[2]);
4100 
4101  points.push_back(point);
4102  primitives.push_back(data.mXPrim);
4103  }
4104 
4105  if (data.mYPrim != util::INVALID_IDX) {
4106  point[0] = double(coord[0]);
4107  point[1] = double(coord[1]) + data.mYDist;
4108  point[2] = double(coord[2]);
4109 
4110  points.push_back(point);
4111  primitives.push_back(data.mYPrim);
4112  }
4113  }
4114 
4115 
4116  coord[1] += 1;
4117 
4118  if (acc.probeValue(coord, data)) {
4119 
4120  if (data.mXPrim != util::INVALID_IDX) {
4121  point[0] = double(coord[0]) + data.mXDist;
4122  point[1] = double(coord[1]);
4123  point[2] = double(coord[2]);
4124 
4125  points.push_back(point);
4126  primitives.push_back(data.mXPrim);
4127  }
4128  }
4129 
4130  coord[2] -= 1;
4131 
4132  if (acc.probeValue(coord, data)) {
4133 
4134  if (data.mXPrim != util::INVALID_IDX) {
4135  point[0] = double(coord[0]) + data.mXDist;
4136  point[1] = double(coord[1]);
4137  point[2] = double(coord[2]);
4138 
4139  points.push_back(point);
4140  primitives.push_back(data.mXPrim);
4141  }
4142 
4143  if (data.mZPrim != util::INVALID_IDX) {
4144  point[0] = double(coord[0]);
4145  point[1] = double(coord[1]);
4146  point[2] = double(coord[2]) + data.mZDist;
4147 
4148  points.push_back(point);
4149  primitives.push_back(data.mZPrim);
4150  }
4151  }
4152 
4153  coord[0] += 1;
4154 
4155  if (acc.probeValue(coord, data)) {
4156 
4157  if (data.mZPrim != util::INVALID_IDX) {
4158  point[0] = double(coord[0]);
4159  point[1] = double(coord[1]);
4160  point[2] = double(coord[2]) + data.mZDist;
4161 
4162  points.push_back(point);
4163  primitives.push_back(data.mZPrim);
4164  }
4165  }
4166 }
4167 
4168 
4169 template<typename GridType, typename VecType>
4170 inline typename GridType::Ptr
4172  const openvdb::math::Transform& xform,
4173  typename VecType::ValueType halfWidth)
4174 {
4175  const Vec3s pmin = Vec3s(xform.worldToIndex(bbox.min()));
4176  const Vec3s pmax = Vec3s(xform.worldToIndex(bbox.max()));
4177 
4178  Vec3s points[8];
4179  points[0] = Vec3s(pmin[0], pmin[1], pmin[2]);
4180  points[1] = Vec3s(pmin[0], pmin[1], pmax[2]);
4181  points[2] = Vec3s(pmax[0], pmin[1], pmax[2]);
4182  points[3] = Vec3s(pmax[0], pmin[1], pmin[2]);
4183  points[4] = Vec3s(pmin[0], pmax[1], pmin[2]);
4184  points[5] = Vec3s(pmin[0], pmax[1], pmax[2]);
4185  points[6] = Vec3s(pmax[0], pmax[1], pmax[2]);
4186  points[7] = Vec3s(pmax[0], pmax[1], pmin[2]);
4187 
4188  Vec4I faces[6];
4189  faces[0] = Vec4I(0, 1, 2, 3); // bottom
4190  faces[1] = Vec4I(7, 6, 5, 4); // top
4191  faces[2] = Vec4I(4, 5, 1, 0); // front
4192  faces[3] = Vec4I(6, 7, 3, 2); // back
4193  faces[4] = Vec4I(0, 3, 7, 4); // left
4194  faces[5] = Vec4I(1, 5, 6, 2); // right
4195 
4196  QuadAndTriangleDataAdapter<Vec3s, Vec4I> mesh(points, 8, faces, 6);
4197 
4198  return meshToVolume<GridType>(mesh, xform, halfWidth, halfWidth);
4199 }
4200 
4201 
4202 } // namespace tools
4203 } // namespace OPENVDB_VERSION_NAME
4204 } // namespace openvdb
4205 
4206 #endif // OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
4207 
4208 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4209 // All rights reserved. This software is distributed under the
4210 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
bool checkNeighbours(const Index pos, const typename LeafNodeType::ValueType *data, bool(&mask)[26])
Vec2< T > minComponent(const Vec2< T > &v1, const Vec2< T > &v2)
Return component-wise minimum of the two vectors.
Definition: Vec2.h:530
size_t findNeighbourNode(tree::ValueAccessor< const TreeType > &acc, const Coord &start, const Coord &step) const
Definition: MeshToVolume.h:751
UnionValueMasks(std::vector< LeafNodeTypeA * > &nodesA, std::vector< LeafNodeTypeB * > &nodesB)
GU_API exint quads(GU_Detail *gdp, UT_Array< GA_OffsetArray > &rings, UT_Array< GA_OffsetArray > &originalRings, GA_PrimitiveGroup *patchgroup, GA_PrimitiveGroup *loopgroup, bool smooth, fpreal smoothstrength, bool edgeloop, fpreal edgeloopPercentage)
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
GA_API const UT_StringHolder dist
OffsetValues(std::vector< LeafNodeType * > &nodes, ValueType offset)
GridType::Ptr meshToSignedDistanceField(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float exBandWidth, float inBandWidth)
Convert a triangle and quad mesh to a signed distance field with an asymmetrical narrow band...
VoxelizePolygons(DataTable &dataTable, const MeshDataAdapter &mesh, Interrupter *interrupter=nullptr)
void operator()(const tbb::blocked_range< size_t > &range) const
GridType::Ptr createLevelSetBox(const math::BBox< VecType > &bbox, const openvdb::math::Transform &xform, typename VecType::ValueType halfWidth=LEVEL_SET_HALF_WIDTH)
Return a grid of type GridType containing a narrow-band level set representation of a box...
GLenum GLint * range
Definition: glcorearb.h:1924
void convert(const std::vector< Vec3s > &pointList, const std::vector< Vec4I > &polygonList)
Threaded method to extract voxel edge data, the closest intersection point and corresponding primitiv...
MeshToVoxelEdgeData::EdgeData Abs(const MeshToVoxelEdgeData::EdgeData &x)
void clear() override
Remove all nodes from this cache, then reinsert the root node.
png_voidp s1
Definition: png.h:2193
TransformPoints(const PointType *pointsIn, PointType *pointsOut, const math::Transform &xform)
Definition: MeshToVolume.h:543
bool isExactlyEqual(const T0 &a, const T1 &b)
Return true if a is exactly equal to b.
Definition: Math.h:395
Type Pow2(Type x)
Return x2.
Definition: Math.h:502
GenEdgeData(const std::vector< Vec3s > &pointList, const std::vector< Vec4I > &polygonList)
NodeType * getNode()
Return the cached node of type NodeType. [Mainly for internal use].
CombineLeafNodes(TreeType &lhsDistTree, Int32TreeType &lhsIdxTree, LeafNodeType **rhsDistNodes, Int32LeafNodeType **rhsIdxNodes)
Definition: MeshToVolume.h:596
const GLdouble * v
Definition: glcorearb.h:836
IMF_EXPORT IMATH_NAMESPACE::V3f direction(const IMATH_NAMESPACE::Box2i &dataWindow, const IMATH_NAMESPACE::V2f &pixelPosition)
GLuint start
Definition: glcorearb.h:474
DiffLeafNodeMask(const TreeType &rhsTree, std::vector< BoolLeafNodeType * > &lhsNodes)
OPENVDB_API const Coord COORD_OFFSETS[26]
coordinate offset table for neighboring voxels
ComputeNodeConnectivity(const TreeType &tree, const Coord *coordinates, size_t *offsets, size_t numNodes, const CoordBBox &bbox)
Definition: MeshToVolume.h:713
ExpandNarrowband(std::vector< BoolLeafNodeType * > &maskNodes, BoolTreeType &maskTree, TreeType &distTree, Int32TreeType &indexTree, const MeshDataAdapter &mesh, ValueType exteriorBandWidth, ValueType interiorBandWidth, ValueType voxelSize)
GLdouble GLdouble GLdouble z
Definition: glcorearb.h:847
ValidateIntersectingVoxels(TreeType &tree, std::vector< LeafNodeType * > &nodes)
void changeBackground(TreeOrLeafManagerT &tree, const typename TreeOrLeafManagerT::ValueType &background, bool threaded=true, size_t grainSize=32)
Replace the background value in all the nodes of a tree.
MeshToVolumeFlags
Mesh to volume conversion flags.
Definition: MeshToVolume.h:88
QuadAndTriangleDataAdapter(const PointType *pointArray, size_t pointArraySize, const PolygonType *polygonArray, size_t polygonArraySize)
Definition: MeshToVolume.h:203
GLboolean GLboolean GLboolean GLboolean a
Definition: glcorearb.h:1221
GLint GLuint mask
Definition: glcorearb.h:123
GLbitfield flags
Definition: glcorearb.h:1595
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:189
MinCombine(std::vector< LeafNodeType * > &nodes, const ValueType *buffer)
RestoreOrigin(std::vector< LeafNodeType * > &nodes, const Coord *coordinates)
Definition: MeshToVolume.h:690
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:695
GLint y
Definition: glcorearb.h:102
#define OPENVDB_LOG_DEBUG(mesg)
Definition: logging.h:304
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
InactivateValues(std::vector< LeafNodeType * > &nodes, ValueType exBandWidth, ValueType inBandWidth)
Dummy NOOP interrupter class defining interface.
void operator()(const tbb::blocked_range< size_t > &range) const
GLuint buffer
Definition: glcorearb.h:659
void operator()(const tbb::blocked_range< size_t > &range) const
png_uint_32 i
Definition: png.h:2877
uint64 value_type
Definition: GA_PrimCompat.h:29
OPENVDB_API Vec3d closestPointOnTriangleToPoint(const Vec3d &a, const Vec3d &b, const Vec3d &c, const Vec3d &p, Vec3d &uvw)
Closest Point on Triangle to Point. Given a triangle abc and a point p, return the point on abc close...
GLsizeiptr size
Definition: glcorearb.h:663
void signedFloodFillWithValues(TreeOrLeafManagerT &tree, const typename TreeOrLeafManagerT::ValueType &outsideWidth, const typename TreeOrLeafManagerT::ValueType &insideWidth, bool threaded=true, size_t grainSize=1, Index minLevel=0)
Set the values of all inactive voxels and tiles of a narrow-band level set from the signs of the acti...
void addLeaf(LeafNodeT *leaf)
Add the specified leaf to this tree, possibly creating a child branch in the process. If the leaf node already exists, replace it.
void traceExteriorBoundaries(FloatTreeT &tree)
Traces the exterior voxel boundary of closed objects in the input volume tree. Exterior voxels are ma...
GLuint GLsizei const GLuint const GLintptr * offsets
Definition: glcorearb.h:2620
void clear()
Remove all tiles from this tree and all nodes other than the root node.
Definition: Tree.h:1488
SYS_FORCE_INLINE const_iterator end() const
void operator()(const tbb::blocked_range< size_t > &range) const
StealUniqueLeafNodes(TreeType &lhsTree, TreeType &rhsTree, std::vector< LeafNodeType * > &overlappingNodes)
GLdouble n
Definition: glcorearb.h:2007
GLfloat f
Definition: glcorearb.h:1925
Vec3d voxelSize() const
Return the size of a voxel using the linear component of the map.
Definition: Transform.h:120
const LeafNodeT * probeConstLeaf(const Coord &xyz) const
Return a pointer to the leaf node that contains voxel (x, y, z), or nullptr if no such node exists...
size_t vertexCount(size_t n) const
Vertex count for polygon n.
Definition: MeshToVolume.h:216
IMATH_INTERNAL_NAMESPACE_HEADER_ENTER T abs(T a)
Definition: ImathFun.h:55
math::Vec4< Index32 > Vec4I
Definition: Types.h:95
const Vec3T & min() const
Return a const reference to the minimum point of this bounding box.
Definition: BBox.h:89
Extracts and stores voxel edge intersection data from a mesh.
Definition: MeshToVolume.h:461
const ValueT & getValue() const
Return the tile or voxel value to which this iterator is currently pointing.
Definition: TreeIterator.h:741
const ValueType & getValue(const Coord &xyz) const
Return the value of the voxel at the given coordinates.
void maskNodeInternalNeighbours(const Index pos, bool(&mask)[26])
T distance(const UT_Vector4T< T > &v1, const UT_Vector4T< T > &v2)
Definition: UT_Vector4.h:698
void merge(Tree &other, MergePolicy=MERGE_ACTIVE_STATES)
Efficiently merge another tree into this tree using one of several schemes.
Definition: Tree.h:1864
const std::enable_if<!VecTraits< T >::IsVec, T >::type & max(const T &a, const T &b)
Definition: Composite.h:133
LeafIter beginLeaf()
Return an iterator over all leaf nodes in this tree.
Definition: Tree.h:1179
void operator()(const tbb::blocked_range< size_t > &range) const
fpreal64 dot(const CE_VectorT< T > &a, const CE_VectorT< T > &b)
Definition: CE_Vector.h:218
TBB body object to voxelize a mesh of triangles and/or quads into a collection of VDB grids...
Efficient multi-threaded replacement of the background values in tree.
ConstructVoxelMask(BoolTreeType &maskTree, const TreeType &tree, std::vector< LeafNodeType * > &nodes)
GLintptr offset
Definition: glcorearb.h:664
float Sqrt(float x)
Return the square root of a floating-point value.
Definition: Math.h:715
Defined various multi-threaded utility functions for trees.
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:853
LeafNodeT * touchLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, create one, but preserve the values and active states of all voxels.
Tree< typename RootNodeType::template ValueConverter< Int32 >::Type > Type
Definition: Tree.h:224
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:591
void operator()(const tbb::blocked_range< size_t > &range) const
void fillArray(ValueType *array, const ValueType val, const size_t length)
void operator()(const tbb::blocked_range< size_t > &range) const
OPENVDB_API const Index32 INVALID_IDX
GLboolean * data
Definition: glcorearb.h:130
tree::Tree4< EdgeData, 5, 4, 3 >::Type TreeType
Definition: MeshToVolume.h:496
GridType::Ptr meshToUnsignedDistanceField(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float bandWidth)
Convert a triangle and quad mesh to an unsigned distance field.
LeafNodeT * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z), or nullptr if no such node exists...
GLboolean GLboolean GLboolean b
Definition: glcorearb.h:1221
GA_API const UT_StringHolder transform
SweepExteriorSign(Axis axis, const std::vector< size_t > &startNodeIndices, ConnectivityTable &connectivity)
Definition: MeshToVolume.h:845
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:605
GridType::Ptr meshToLevelSet(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, float halfWidth=float(LEVEL_SET_HALF_WIDTH))
Convert a triangle mesh to a level set volume.
const Vec3T & max() const
Return a const reference to the maximum point of this bounding box.
Definition: BBox.h:91
GLint GLsizei count
Definition: glcorearb.h:404
int floor(T x)
Definition: ImathFun.h:150
Propagate the signs of distance values from the active voxels in the narrow band to the inactive valu...
void operator()(const tbb::blocked_range< size_t > &range)
ComputeIntersectingVoxelSign(std::vector< LeafNodeType * > &distNodes, const TreeType &distTree, const Int32TreeType &indexTree, const MeshDataAdapter &mesh)
Renormalize(const TreeType &tree, const std::vector< LeafNodeType * > &nodes, ValueType *buffer, ValueType voxelSize)
SeedPoints(ConnectivityTable &connectivity, bool *changedNodeMask, bool *nodeMask, bool *changedVoxelMask)
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:549
GridType::Ptr meshToVolume(const MeshDataAdapter &mesh, const math::Transform &transform, float exteriorBandWidth=3.0f, float interiorBandWidth=3.0f, int flags=0, typename GridType::template ValueConverter< Int32 >::Type *polygonIndexGrid=nullptr)
bool isValueOn(const Coord &xyz) const
Return the active state of the voxel at the given coordinates.
bool traceVoxelLine(LeafNodeType &node, Index pos, Index step) const
Definition: MeshToVolume.h:929
GLsizei const GLfloat * value
Definition: glcorearb.h:823
Axis-aligned bounding box.
Definition: BBox.h:50
png_voidp png_voidp s2
Definition: png.h:2193
void combineData(DistTreeType &lhsDist, IndexTreeType &lhsIdx, DistTreeType &rhsDist, IndexTreeType &rhsIdx)
typename RootNodeType::LeafNodeType LeafNodeType
Definition: Tree.h:212
typedef int
Definition: png.h:1175
void getIndexSpacePoint(size_t n, size_t v, Vec3d &pos) const
Returns position pos in local grid index space for polygon n and vertex v.
Definition: MeshToVolume.h:222
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
GA_API const UT_StringHolder up
QuadAndTriangleDataAdapter(const std::vector< PointType > &points, const std::vector< PolygonType > &polygons)
Definition: MeshToVolume.h:194
GLuint index
Definition: glcorearb.h:785
math::Vec3< Index32 > Vec3I
Definition: Types.h:80
Base class for tree-traversal iterators over tile and voxel values.
Definition: TreeIterator.h:665
GLint GLenum GLint x
Definition: glcorearb.h:408
GLuint GLfloat * val
Definition: glcorearb.h:1607
Vec2< T > maxComponent(const Vec2< T > &v1, const Vec2< T > &v2)
Return component-wise maximum of the two vectors.
Definition: Vec2.h:539
std::ostream & operator<<(std::ostream &ostr, const MeshToVoxelEdgeData::EdgeData &rhs)
AddNodes(TreeType &tree, std::vector< LeafNodeType * > &nodes)
void setValueOn(const Coord &xyz, const ValueType &value)
Set the value of the voxel at the given coordinates and mark the voxel as active. ...
GA_API const UT_StringHolder N