OpenVDB  0.104.0
LevelSetTracker.h
Go to the documentation of this file.
1 
2 //
3 // Copyright (c) 2012 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 //
30 //
38 
39 #ifndef OPENVDB_TOOLS_LEVEL_SET_TRACKER_HAS_BEEN_INCLUDED
40 #define OPENVDB_TOOLS_LEVEL_SET_TRACKER_HAS_BEEN_INCLUDED
41 
42 #include <tbb/parallel_reduce.h>
43 #include <tbb/parallel_for.h>
44 #include <boost/bind.hpp>
45 #include <boost/function.hpp>
46 #include <boost/type_traits/is_floating_point.hpp>
47 #include <openvdb/openvdb.h>
48 #include <openvdb/Types.h>
49 #include <openvdb/math/Math.h>
50 #include <openvdb/math/FiniteDifference.h>
51 #include <openvdb/math/Operators.h>
52 #include <openvdb/math/Stencils.h>
53 #include <openvdb/math/Transform.h>
54 #include <openvdb/Grid.h>
55 #include <openvdb/util/NullInterrupter.h>
56 #include "Morphology.h"//for tools::dilateVoxels
57 
58 namespace openvdb {
60 namespace OPENVDB_VERSION_NAME {
61 namespace tools {
62 
64 template<typename GridT, typename InterruptT = util::NullInterrupter>
66 {
67 public:
68  typedef GridT GridType;
69  typedef typename GridT::TreeType TreeType;
70  typedef typename TreeType::LeafNodeType LeafType;
71  typedef typename TreeType::ValueType ValueType;
72  typedef typename tree::LeafManager<TreeType> LeafManagerType; // leafs + buffers
75  BOOST_STATIC_ASSERT(boost::is_floating_point<ValueType>::value);
76 
78  LevelSetTracker(GridT& grid, InterruptT* interrupt = NULL);
79 
81  LevelSetTracker(const LevelSetTracker& other);
82 
83  virtual ~LevelSetTracker() { if (mIsMaster) delete mLeafs; }
84 
86  void normalize();
87 
90  void track();
91 
93  void prune();
94 
96  math::BiasedGradientScheme getSpatialScheme() const { return mSpatialScheme; }
98  void setSpatialScheme(math::BiasedGradientScheme scheme) { mSpatialScheme = scheme; }
99 
101  math::TemporalIntegrationScheme getTemporalScheme() const { return mTemporalScheme; }
103  void setTemporalScheme(math::TemporalIntegrationScheme scheme) { mTemporalScheme = scheme; }
104 
107  int getNormCount() const { return mNormCount; }
110  void setNormCount(int n) { mNormCount = n; }
111 
113  int getGrainSize() const { return mGrainSize; }
116  void setGrainSize(int grainsize) { mGrainSize = grainsize; }
117 
118  ValueType voxelSize() const { return mDx; }
119 
120  void startInterrupter(const char* msg);
121  void endInterrupter();
123  bool checkInterrupter();
124 
125  const GridType& grid() const { return mGrid; }
126 
129  void operator()(const RangeType& r) const
130  {
131  if (mTask) mTask(const_cast<LevelSetTracker*>(this), r);
132  else OPENVDB_THROW(ValueError, "task is undefined - call track(), etc");
133  }
134 
135 protected:
136 
137  template<math::BiasedGradientScheme SpatialScheme,
138  math::TemporalIntegrationScheme TemporalScheme>
139  struct Normalizer
140  {
141  Normalizer(LevelSetTracker& tracker): mTracker(tracker), mTask(0) {}
142  void normalize();
143  void operator()(const RangeType& r) const {mTask(const_cast<Normalizer*>(this), r);}
144  typedef typename boost::function<void (Normalizer*, const RangeType&)> FuncType;
147  void cook(int swapBuffer=0);
148  void euler1(const RangeType& range, ValueType dt, Index resultBuffer);
149  void euler2(const RangeType& range, ValueType dt, ValueType alpha,
150  Index phiBuffer, Index resultBuffer);
151  }; // end of protected Normalizer class
152 
153  // required to access mLeafs
154  template<typename, typename, typename>
155  friend class LevelSetAdvection;
156 
158  // Throughout the methods below mLeafs is always assumed to contain
159  // a list of the current LeafNodes! The auxiliary buffers on the
160  // other hand always have to be allocated locally, since some
161  // methods need them and others don't!
163  InterruptT* mInterrupter;
164  const ValueType mDx;
165 
166 private:
167  typedef typename boost::function<void (LevelSetTracker*, const RangeType&)> FuncType;
168 
169  void trim(const RangeType& r);
170 
171  template<math::BiasedGradientScheme SpatialScheme>
172  void normalize1();
173 
174  template<math::BiasedGradientScheme SpatialScheme,
175  math::TemporalIntegrationScheme TemporalScheme>
176  void normalize2();
177 
178  math::BiasedGradientScheme mSpatialScheme;
179  math::TemporalIntegrationScheme mTemporalScheme;
180  int mNormCount;// Number of iteratations of normalization
181  int mGrainSize;
182  FuncType mTask;
183  const bool mIsMaster;
184 
185  // disallow copy by assignment
186  void operator=(const LevelSetTracker& other) {}
187 
188 }; // end of LevelSetTracker class
189 
190 template<typename GridT, typename InterruptT>
191 LevelSetTracker<GridT, InterruptT>::LevelSetTracker(GridT& grid, InterruptT* interrupt):
192  mGrid(grid),
193  mLeafs(new LeafManagerType(grid.tree())),
194  mInterrupter(interrupt),
195  mDx(grid.voxelSize()[0]),
196  mSpatialScheme(math::HJWENO5_BIAS),
197  mTemporalScheme(math::TVD_RK1),
198  mNormCount(static_cast<int>(LEVEL_SET_HALF_WIDTH)),
199  mGrainSize(1),
200  mTask(0),
201  mIsMaster(true)// N.B.
202 {
203  if ( !grid.hasUniformVoxels() ) {
205  "The transform must have uniform scale for the LevelSetTracker to function");
206  }
207  if ( grid.getGridClass() != GRID_LEVEL_SET) {
209  "LevelSetTracker only supports level sets!\n"
210  "However, only level sets are guaranteed to work!\n"
211  "Hint: Grid::setGridClass(openvdb::GRID_LEVEL_SET)");
212  }
213 }
214 
215 template<typename GridT, typename InterruptT>
217  mGrid(other.mGrid),
218  mLeafs(other.mLeafs),
219  mInterrupter(other.mInterrupter),
220  mDx(other.mDx),
221  mSpatialScheme(other.mSpatialScheme),
222  mTemporalScheme(other.mTemporalScheme),
223  mNormCount(other.mNormCount),
224  mGrainSize(other.mGrainSize),
225  mTask(other.mTask),
226  mIsMaster(false)// N.B.
227 {
228 }
229 
230 template<typename GridT, typename InterruptT>
231 inline void
233 {
234  this->startInterrupter("Pruning Level Set");
235  // Prune voxels that are too far away from the zero-crossing
236  mTask = boost::bind(&LevelSetTracker::trim, _1, _2);
237  if (mGrainSize>0) {
238  tbb::parallel_for(mLeafs->getRange(mGrainSize), *this);
239  } else {
240  (*this)(mLeafs->getRange());
241  }
242 
243  // Remove inactive nodes from tree
244  mGrid.tree().pruneLevelSet();
245 
246  // The tree topology has changes so rebuild the list of leafs
247  mLeafs->rebuildLeafs();
248  this->endInterrupter();
249 }
250 
251 template<typename GridT, typename InterruptT>
252 inline void
254 {
255  // Dilate narrow-band
257  // The tree topology has changes so rebuild the list of leafs
258  mLeafs->rebuildLeafs();
259 
260  // Compute signed distances in dilated narrow-band
261  this->normalize();
262 
263  // Remove voxels that are outside the narrow band
264  this->prune();
265 }
266 
267 template<typename GridT, typename InterruptT>
268 inline void
270 {
271  if (mInterrupter) mInterrupter->start(msg);
272 }
273 
274 template<typename GridT, typename InterruptT>
275 inline void
277 {
278  if (mInterrupter) mInterrupter->end();
279 }
280 
281 template<typename GridT, typename InterruptT>
282 inline bool
284 {
285  if (util::wasInterrupted(mInterrupter)) {
286  tbb::task::self().cancel_group_execution();
287  return false;
288  }
289  return true;
290 }
291 
293 template<typename GridT, typename InterruptT>
294 inline void
295 LevelSetTracker<GridT, InterruptT>::trim(const RangeType& range)
296 {
297  typedef typename LeafType::ValueOnIter VoxelIterT;
298  const_cast<LevelSetTracker*>(this)->checkInterrupter();
299  const ValueType gamma = mGrid.background();
300  for (size_t n=range.begin(), e=range.end(); n != e; ++n) {
301  LeafType &leaf = mLeafs->leaf(n);
302  for (VoxelIterT iter = leaf.beginValueOn(); iter; ++iter) {
303  const ValueType val = *iter;
304  if (val < -gamma)
305  leaf.setValueOff(iter.pos(), -gamma);
306  else if (val > gamma)
307  leaf.setValueOff(iter.pos(), gamma);
308  }
309  }
310 }
311 
312 template<typename GridT, typename InterruptT>
313 inline void
315 {
316  switch (mSpatialScheme) {
317  case math::FIRST_BIAS:
318  this->normalize1<math::FIRST_BIAS >(); break;
319  case math::SECOND_BIAS:
320  this->normalize1<math::SECOND_BIAS >(); break;
321  case math::THIRD_BIAS:
322  this->normalize1<math::THIRD_BIAS >(); break;
323  case math::WENO5_BIAS:
324  this->normalize1<math::WENO5_BIAS >(); break;
325  case math::HJWENO5_BIAS:
326  this->normalize1<math::HJWENO5_BIAS>(); break;
327  default:
328  OPENVDB_THROW(ValueError, "Spatial difference scheme not supported!");
329  }
330 }
331 
332 template<typename GridT, typename InterruptT>
333 template<math::BiasedGradientScheme SpatialScheme>
334 inline void
336 {
337  switch (mTemporalScheme) {
338  case math::TVD_RK1:
339  this->normalize2<SpatialScheme, math::TVD_RK1>(); break;
340  case math::TVD_RK2:
341  this->normalize2<SpatialScheme, math::TVD_RK2>(); break;
342  case math::TVD_RK3:
343  this->normalize2<SpatialScheme, math::TVD_RK3>(); break;
344  default:
345  OPENVDB_THROW(ValueError, "Temporal integration scheme not supported!");
346  }
347 }
348 
349 template<typename GridT, typename InterruptT>
350 template<math::BiasedGradientScheme SpatialScheme,
351  math::TemporalIntegrationScheme TemporalScheme>
352 inline void
353 LevelSetTracker<GridT, InterruptT>::normalize2()
354 {
355  Normalizer<SpatialScheme, TemporalScheme> tmp(*this);
356  tmp.normalize();
357 }
358 
359 template<typename GridT, typename InterruptT>
360 template<math::BiasedGradientScheme SpatialScheme,
361  math::TemporalIntegrationScheme TemporalScheme>
362 inline void
365 {
367  mTracker.mLeafs->rebuildAuxBuffers(TemporalScheme == math::TVD_RK3 ? 2 : 1);
368 
369  const ValueType dt = (TemporalScheme == math::TVD_RK1 ? ValueType(0.3) :
370  TemporalScheme == math::TVD_RK2 ? ValueType(0.9) : ValueType(1.0))
371  * ValueType(mTracker.voxelSize());
372 
373  for (int n=0, e=mTracker.getNormCount(); n < e; ++n) {
374 
375  switch(TemporalScheme) {//switch is resolved at compile-time
376  case math::TVD_RK1:
377  //std::cerr << "1";
378  // Perform one explicit Euler step: t1 = t0 + dt
379  // Phi_t1(0) = Phi_t0(0) - dt * VdotG_t0(1)
380  mTask = boost::bind(&Normalizer::euler1, _1, _2, dt, /*result=*/1);
381  // Cook and swap buffer 0 and 1 such that Phi_t1(0) and Phi_t0(1)
382  this->cook(1);
383  break;
384  case math::TVD_RK2:
385  //std::cerr << "2";
386  // Perform one explicit Euler step: t1 = t0 + dt
387  // Phi_t1(1) = Phi_t0(0) - dt * VdotG_t0(1)
388  mTask = boost::bind(&Normalizer::euler1, _1, _2, dt, /*result=*/1);
389  // Cook and swap buffer 0 and 1 such that Phi_t1(0) and Phi_t0(1)
390  this->cook(1);
391 
392  // Convex combine explict Euler step: t2 = t0 + dt
393  // Phi_t2(1) = 1/2 * Phi_t0(1) + 1/2 * (Phi_t1(0) - dt * V.Grad_t1(0))
394  mTask = boost::bind(&Normalizer::euler2,
395  _1, _2, dt, ValueType(0.5), /*phi=*/1, /*result=*/1);
396  // Cook and swap buffer 0 and 1 such that Phi_t2(0) and Phi_t1(1)
397  this->cook(1);
398  break;
399  case math::TVD_RK3:
400  //std::cerr << "3";
401  // Perform one explicit Euler step: t1 = t0 + dt
402  // Phi_t1(1) = Phi_t0(0) - dt * VdotG_t0(1)
403  mTask = boost::bind(&Normalizer::euler1, _1, _2, dt, /*result=*/1);
404  // Cook and swap buffer 0 and 1 such that Phi_t1(0) and Phi_t0(1)
405  this->cook(1);
406 
407  // Convex combine explict Euler step: t2 = t0 + dt/2
408  // Phi_t2(2) = 3/4 * Phi_t0(1) + 1/4 * (Phi_t1(0) - dt * V.Grad_t1(0))
409  mTask = boost::bind(&Normalizer::euler2,
410  _1, _2, dt, ValueType(0.75), /*phi=*/1, /*result=*/2);
411  // Cook and swap buffer 0 and 2 such that Phi_t2(0) and Phi_t1(2)
412  this->cook(2);
413 
414  // Convex combine explict Euler step: t3 = t0 + dt
415  // Phi_t3(2) = 1/3 * Phi_t0(1) + 2/3 * (Phi_t2(0) - dt * V.Grad_t2(0)
416  mTask = boost::bind(&Normalizer::euler2,
417  _1, _2, dt, ValueType(1.0/3.0), /*phi=*/1, /*result=*/2);
418  // Cook and swap buffer 0 and 2 such that Phi_t3(0) and Phi_t2(2)
419  this->cook(2);
420  break;
421  default:
422  OPENVDB_THROW(ValueError, "Temporal integration scheme not supported!");
423  }
424  }
425  mTracker.mLeafs->removeAuxBuffers();
426 }
427 
430 template<typename GridT, typename InterruptT>
431 template<math::BiasedGradientScheme SpatialScheme,
432  math::TemporalIntegrationScheme TemporalScheme>
433 inline void
435 cook(int swapBuffer)
436 {
437  mTracker.startInterrupter("Normalizing Level Set");
438 
439  if (mTracker.getGrainSize()>0) {
440  tbb::parallel_for(mTracker.mLeafs->getRange(mTracker.getGrainSize()), *this);
441  } else {
442  (*this)(mTracker.mLeafs->getRange());
443  }
444 
445  mTracker.mLeafs->swapLeafBuffer(swapBuffer, mTracker.getGrainSize()==0);
446 
447  mTracker.endInterrupter();
448 }
449 
450 
454 template<typename GridT, typename InterruptT>
455 template<math::BiasedGradientScheme SpatialScheme,
456  math::TemporalIntegrationScheme TemporalScheme>
457 inline void
459 euler1(const RangeType &range, ValueType dt, Index resultBuffer)
460 {
461  typedef math::BIAS_SCHEME<SpatialScheme> Scheme;
462  typedef typename Scheme::template ISStencil<GridType>::StencilType Stencil;
463  typedef typename LeafType::ValueOnCIter VoxelIterT;
464  mTracker.checkInterrupter();
465  const ValueType one(1.0), invDx = one/mTracker.voxelSize();
466  Stencil stencil(mTracker.grid());
467  for (size_t n=range.begin(), e=range.end(); n != e; ++n) {
468  BufferType& result = mTracker.mLeafs->getBuffer(n, resultBuffer);
469  const LeafType& leaf = mTracker.mLeafs->leaf(n);
470  for (VoxelIterT iter = leaf.cbeginValueOn(); iter; ++iter) {
471  stencil.moveTo(iter);
472  const ValueType normSqGradPhi =
474  const ValueType phi0 = stencil.getValue();
475  const ValueType diff = math::Sqrt(normSqGradPhi)*invDx - one;
476  const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
477  result.setValue(iter.pos(), phi0 - dt * S * diff);
478  }
479  }
480 }
481 
482 template<typename GridT, typename InterruptT>
483 template<math::BiasedGradientScheme SpatialScheme,
484  math::TemporalIntegrationScheme TemporalScheme>
485 inline void
487 euler2(const RangeType& range, ValueType dt, ValueType alpha, Index phiBuffer, Index resultBuffer)
488 {
489  typedef math::BIAS_SCHEME<SpatialScheme> Scheme;
490  typedef typename Scheme::template ISStencil<GridType>::StencilType Stencil;
491  typedef typename LeafType::ValueOnCIter VoxelIterT;
492  mTracker.checkInterrupter();
493  const ValueType one(1.0), beta = one - alpha, invDx = one/mTracker.voxelSize();
494  Stencil stencil(mTracker.grid());
495  for (size_t n=range.begin(), e=range.end(); n != e; ++n) {
496  const BufferType& phi = mTracker.mLeafs->getBuffer(n, phiBuffer);
497  BufferType& result = mTracker.mLeafs->getBuffer(n, resultBuffer);
498  const LeafType& leaf = mTracker.mLeafs->leaf(n);
499  for (VoxelIterT iter = leaf.cbeginValueOn(); iter; ++iter) {
500  stencil.moveTo(iter);
501  const ValueType normSqGradPhi =
503  const ValueType phi0 = stencil.getValue();
504  const ValueType diff = math::Sqrt(normSqGradPhi)*invDx - one;
505  const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
506  result.setValue(iter.pos(), alpha*phi[iter.pos()] + beta*(phi0 - dt * S * diff));
507  }
508  }
509 }
511 
512 } // namespace tools
513 } // namespace OPENVDB_VERSION_NAME
514 } // namespace openvdb
515 
516 #endif // OPENVDB_TOOLS_LEVEL_SET_TRACKER_HAS_BEEN_INCLUDED
517 
518 // Copyright (c) 2012 DreamWorks Animation LLC
519 // All rights reserved. This software is distributed under the
520 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )