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