<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: itkGaussianInterpolateImageFunction.hxx,v $
  Language:  C++
  Date:      $Date: $
  Version:   $Revision: $

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or https://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef itkGaussianInterpolateImageFunction_hxx
#define itkGaussianInterpolateImageFunction_hxx

#include "itkGaussianInterpolateImageFunction.h"

#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{

template<typename TImageType, typename TCoordRep>
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::GaussianInterpolateImageFunction() :
  m_Alpha( 1.0 )
{
  this->m_Sigma.Fill( 1.0 );
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::ComputeBoundingBox()
{
  if( !this->GetInputImage() )
    {
    return;
    }

  typename InputImageType::ConstPointer input = this->GetInputImage();
  typename InputImageType::SpacingType spacing = input->GetSpacing();
  typename InputImageType::SizeType size = input->GetBufferedRegion().GetSize();

  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    this->m_BoundingBoxStart[d] = -0.5;
    this->m_BoundingBoxEnd[d] = static_cast<RealType>( size[d] ) - 0.5;
    this->m_ScalingFactor[d] = 1.0 / ( itk::Math::sqrt2 * this->m_Sigma[d] / spacing[d] );
    this->m_CutOffDistance[d] = this->m_Sigma[d] * this->m_Alpha / spacing[d];
    }
}

template<typename TImageType, typename TCoordRep>
typename GaussianInterpolateImageFunction<TImageType, TCoordRep>
::OutputType
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::EvaluateAtContinuousIndex( const ContinuousIndexType & cindex, OutputType *grad ) const
{
  vnl_vector<RealType> erfArray[ImageDimension];
  vnl_vector<RealType> gerfArray[ImageDimension];

  // Compute the ERF difference arrays
  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    bool evaluateGradient = false;
    if( grad )
      {
      evaluateGradient = true;
      }
    this->ComputeErrorFunctionArray( d, cindex[d], erfArray[d],
      gerfArray[d], evaluateGradient );
    }

  RealType sum_me = 0.0;
  RealType sum_m = 0.0;
  ArrayType dsum_me;
  ArrayType dsum_m;
  ArrayType dw;

  dsum_m.Fill( 0.0 );
  dsum_me.Fill( 0.0 );
  dw.Fill( 0.0 );

  // Loop over the voxels in the region identified
  ImageRegion<ImageDimension> region;
  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    int boundingBoxSize = static_cast<int>(
      this->m_BoundingBoxEnd[d] - this->m_BoundingBoxStart[d] + 0.5 );
    int begin = std::max( 0, static_cast<int>( std::floor( cindex[d] -
      this->m_BoundingBoxStart[d] - this->m_CutOffDistance[d] ) ) );
    int end = std::min( boundingBoxSize, static_cast<int>( std::ceil(
      cindex[d] - this->m_BoundingBoxStart[d] + this->m_CutOffDistance[d] ) ) );
    region.SetIndex( d, begin );
    region.SetSize( d, end - begin );
    }

  ImageRegionConstIteratorWithIndex<InputImageType> It(
    this->GetInputImage(), region );
  for( It.GoToBegin(); !It.IsAtEnd(); ++It )
    {
    unsigned int j = It.GetIndex()[0];
    RealType w = erfArray[0][j];
    if( grad )
      {
      dw[0] = gerfArray[0][j];
      for( unsigned int d = 1; d < ImageDimension; d++ )
        {
        dw[d] = erfArray[0][j];
        }
      }
    for( unsigned int d = 1; d < ImageDimension; d++)
      {
      j = It.GetIndex()[d];
      w *= erfArray[d][j];
      if( grad )
        {
        for( unsigned int q = 0; q < ImageDimension; q++ )
          {
          if( d == q )
            {
            dw[q] *= gerfArray[d][j];
            }
          else
            {
            dw[q] *= erfArray[d][j];
            }
          }
        }
      }
    RealType V = It.Get();
    sum_me += V * w;
    sum_m += w;
    if( grad )
      {
      for( unsigned int q = 0; q < ImageDimension; q++ )
        {
        dsum_me[q] += V * dw[q];
        dsum_m[q] += dw[q];
        }
      }
    }
  RealType rc = sum_me / sum_m;

  if( grad )
    {
    for( unsigned int q = 0; q < ImageDimension; q++ )
      {
      grad[q] = ( dsum_me[q] - rc * dsum_m[q] ) / sum_m;
      grad[q] /= -itk::Math::sqrt2 * this->m_Sigma[q];
      }
    }

  return rc;
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::ComputeErrorFunctionArray( unsigned int dimension, RealType cindex,
  vnl_vector<RealType> &erfArray, vnl_vector<RealType> &gerfArray,
  bool evaluateGradient ) const
{
  // Determine the range of voxels along the line where to evaluate erf
  int boundingBoxSize = static_cast<int>(
    this->m_BoundingBoxEnd[dimension] - this->m_BoundingBoxStart[dimension] +
    0.5 );
  int begin = std::max( 0, static_cast<int>( std::floor( cindex -
    this->m_BoundingBoxStart[dimension] -
    this->m_CutOffDistance[dimension] ) ) );
  int end = std::min( boundingBoxSize, static_cast<int>( std::ceil( cindex -
    this->m_BoundingBoxStart[dimension] +
    this->m_CutOffDistance[dimension] ) ) );

  erfArray.set_size( boundingBoxSize );
  gerfArray.set_size( boundingBoxSize );

  // Start at the first voxel
  RealType t = ( this->m_BoundingBoxStart[dimension] - cindex +
    static_cast<RealType>( begin ) ) * this->m_ScalingFactor[dimension];
  RealType e_last = vnl_erf( t );
  RealType g_last = 0.0;
  if( evaluateGradient )
    {
    g_last = itk::Math::two_over_sqrtpi * std::exp( -itk::Math::sqr( t ) );
    }

  for( int i = begin; i < end; i++ )
    {
    t += this->m_ScalingFactor[dimension];
    RealType e_now = vnl_erf( t );
    erfArray[i] = e_now - e_last;
    if( evaluateGradient )
      {
      RealType g_now = itk::Math::two_over_sqrtpi * std::exp( -itk::Math::sqr( t ) );
      gerfArray[i] = g_now - g_last;
      g_last = g_now;
      }
    e_last = e_now;
    }
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::PrintSelf( std::ostream& os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );
  os << indent << "Alpha: " << this->m_Alpha << std::endl;
  os << indent << "Sigma: " << this->m_Sigma << std::endl;
}
} // namespace itk

#endif
<commit_msg>ENH: Finish itkGaussianInterpolateImageFunction PrintSelf.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: itkGaussianInterpolateImageFunction.hxx,v $
  Language:  C++
  Date:      $Date: $
  Version:   $Revision: $

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or https://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef itkGaussianInterpolateImageFunction_hxx
#define itkGaussianInterpolateImageFunction_hxx

#include "itkGaussianInterpolateImageFunction.h"

#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{

template<typename TImageType, typename TCoordRep>
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::GaussianInterpolateImageFunction() :
  m_Alpha( 1.0 )
{
  this->m_Sigma.Fill( 1.0 );
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::ComputeBoundingBox()
{
  if( !this->GetInputImage() )
    {
    return;
    }

  typename InputImageType::ConstPointer input = this->GetInputImage();
  typename InputImageType::SpacingType spacing = input->GetSpacing();
  typename InputImageType::SizeType size = input->GetBufferedRegion().GetSize();

  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    this->m_BoundingBoxStart[d] = -0.5;
    this->m_BoundingBoxEnd[d] = static_cast<RealType>( size[d] ) - 0.5;
    this->m_ScalingFactor[d] = 1.0 / ( itk::Math::sqrt2 * this->m_Sigma[d] / spacing[d] );
    this->m_CutOffDistance[d] = this->m_Sigma[d] * this->m_Alpha / spacing[d];
    }
}

template<typename TImageType, typename TCoordRep>
typename GaussianInterpolateImageFunction<TImageType, TCoordRep>
::OutputType
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::EvaluateAtContinuousIndex( const ContinuousIndexType & cindex, OutputType *grad ) const
{
  vnl_vector<RealType> erfArray[ImageDimension];
  vnl_vector<RealType> gerfArray[ImageDimension];

  // Compute the ERF difference arrays
  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    bool evaluateGradient = false;
    if( grad )
      {
      evaluateGradient = true;
      }
    this->ComputeErrorFunctionArray( d, cindex[d], erfArray[d],
      gerfArray[d], evaluateGradient );
    }

  RealType sum_me = 0.0;
  RealType sum_m = 0.0;
  ArrayType dsum_me;
  ArrayType dsum_m;
  ArrayType dw;

  dsum_m.Fill( 0.0 );
  dsum_me.Fill( 0.0 );
  dw.Fill( 0.0 );

  // Loop over the voxels in the region identified
  ImageRegion<ImageDimension> region;
  for( unsigned int d = 0; d < ImageDimension; d++ )
    {
    int boundingBoxSize = static_cast<int>(
      this->m_BoundingBoxEnd[d] - this->m_BoundingBoxStart[d] + 0.5 );
    int begin = std::max( 0, static_cast<int>( std::floor( cindex[d] -
      this->m_BoundingBoxStart[d] - this->m_CutOffDistance[d] ) ) );
    int end = std::min( boundingBoxSize, static_cast<int>( std::ceil(
      cindex[d] - this->m_BoundingBoxStart[d] + this->m_CutOffDistance[d] ) ) );
    region.SetIndex( d, begin );
    region.SetSize( d, end - begin );
    }

  ImageRegionConstIteratorWithIndex<InputImageType> It(
    this->GetInputImage(), region );
  for( It.GoToBegin(); !It.IsAtEnd(); ++It )
    {
    unsigned int j = It.GetIndex()[0];
    RealType w = erfArray[0][j];
    if( grad )
      {
      dw[0] = gerfArray[0][j];
      for( unsigned int d = 1; d < ImageDimension; d++ )
        {
        dw[d] = erfArray[0][j];
        }
      }
    for( unsigned int d = 1; d < ImageDimension; d++)
      {
      j = It.GetIndex()[d];
      w *= erfArray[d][j];
      if( grad )
        {
        for( unsigned int q = 0; q < ImageDimension; q++ )
          {
          if( d == q )
            {
            dw[q] *= gerfArray[d][j];
            }
          else
            {
            dw[q] *= erfArray[d][j];
            }
          }
        }
      }
    RealType V = It.Get();
    sum_me += V * w;
    sum_m += w;
    if( grad )
      {
      for( unsigned int q = 0; q < ImageDimension; q++ )
        {
        dsum_me[q] += V * dw[q];
        dsum_m[q] += dw[q];
        }
      }
    }
  RealType rc = sum_me / sum_m;

  if( grad )
    {
    for( unsigned int q = 0; q < ImageDimension; q++ )
      {
      grad[q] = ( dsum_me[q] - rc * dsum_m[q] ) / sum_m;
      grad[q] /= -itk::Math::sqrt2 * this->m_Sigma[q];
      }
    }

  return rc;
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::ComputeErrorFunctionArray( unsigned int dimension, RealType cindex,
  vnl_vector<RealType> &erfArray, vnl_vector<RealType> &gerfArray,
  bool evaluateGradient ) const
{
  // Determine the range of voxels along the line where to evaluate erf
  int boundingBoxSize = static_cast<int>(
    this->m_BoundingBoxEnd[dimension] - this->m_BoundingBoxStart[dimension] +
    0.5 );
  int begin = std::max( 0, static_cast<int>( std::floor( cindex -
    this->m_BoundingBoxStart[dimension] -
    this->m_CutOffDistance[dimension] ) ) );
  int end = std::min( boundingBoxSize, static_cast<int>( std::ceil( cindex -
    this->m_BoundingBoxStart[dimension] +
    this->m_CutOffDistance[dimension] ) ) );

  erfArray.set_size( boundingBoxSize );
  gerfArray.set_size( boundingBoxSize );

  // Start at the first voxel
  RealType t = ( this->m_BoundingBoxStart[dimension] - cindex +
    static_cast<RealType>( begin ) ) * this->m_ScalingFactor[dimension];
  RealType e_last = vnl_erf( t );
  RealType g_last = 0.0;
  if( evaluateGradient )
    {
    g_last = itk::Math::two_over_sqrtpi * std::exp( -itk::Math::sqr( t ) );
    }

  for( int i = begin; i < end; i++ )
    {
    t += this->m_ScalingFactor[dimension];
    RealType e_now = vnl_erf( t );
    erfArray[i] = e_now - e_last;
    if( evaluateGradient )
      {
      RealType g_now = itk::Math::two_over_sqrtpi * std::exp( -itk::Math::sqr( t ) );
      gerfArray[i] = g_now - g_last;
      g_last = g_now;
      }
    e_last = e_now;
    }
}

template<typename TImageType, typename TCoordRep>
void
GaussianInterpolateImageFunction<TImageType, TCoordRep>
::PrintSelf( std::ostream& os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  os << indent << "Alpha: " << this->m_Alpha << std::endl;
  os << indent << "Sigma: " << this->m_Sigma << std::endl;

  os << indent << "Bounding box start: " << this->m_BoundingBoxStart << std::endl;
  os << indent << "Bounding box end: " << this->m_BoundingBoxEnd << std::endl;
  os << indent << "Scaling factor: " << this->m_ScalingFactor << std::endl;
  os << indent << "Cut-off distance: " << this->m_CutOffDistance << std::endl;
}
} // namespace itk

#endif
<|endoftext|>


<commit_before>/*
 * DataSetTimeRewriteModule.cpp
 *
 * Copyright (C) 2014 by CGV TU Dresden
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "DataSetTimeRewriteModule.h"
#include "mmcore/AbstractGetData3DCall.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/factories/CallDescriptionManager.h"
#include "mmcore/param/IntParam.h"
#include <algorithm>

using namespace megamol;
using namespace megamol::stdplugin;

/*
 * datatools::DataSetTimeRewriteModule::DataSetTimeRewriteModule
 */
datatools::DataSetTimeRewriteModule::DataSetTimeRewriteModule(void) : core::Module(),
        outDataSlot("outData", "The slot for publishing data to the writer"),
        inDataSlot("inData", "The slot for requesting data from the source"),
        firstFrameSlot("firstFrame", "The number of the first frame"),
        lastFrameSlot("lastFrame", "The number of the last frame"),
        frameStepSlot("frameStep", "The step length between two frames") {

    //core::CallDescriptionManager::DescriptionIterator iter(core::CallDescriptionManager::Instance()->GetIterator());
    //const core::CallDescription *cd = NULL;
    //while ((cd = this->moveToNextCompatibleCall(iter)) != NULL) {
    //    this->outDataSlot.SetCallback(cd->ClassName(), "GetData", &DataSetTimeRewriteModule::getDataCallback);
    //    this->outDataSlot.SetCallback(cd->ClassName(), "GetExtent", &DataSetTimeRewriteModule::getExtentCallback);
    //    this->inDataSlot.SetCompatibleCall(*cd);
    //}

    this->MakeSlotAvailable(&this->outDataSlot);
    this->MakeSlotAvailable(&this->inDataSlot);

    this->firstFrameSlot.SetParameter(new core::param::IntParam(0, 0));
    this->MakeSlotAvailable(&this->firstFrameSlot);

    this->lastFrameSlot.SetParameter(new core::param::IntParam(1000000, 0));
    this->MakeSlotAvailable(&this->lastFrameSlot);

    this->frameStepSlot.SetParameter(new core::param::IntParam(1, 1));
    this->MakeSlotAvailable(&this->frameStepSlot);
}

/*
 * datatools::DataSetTimeRewriteModule::~DataSetTimeRewriteModule
 */
datatools::DataSetTimeRewriteModule::~DataSetTimeRewriteModule(void) {
    this->Release(); // implicitly calls 'release'
}

/*
 * datatools::DataSetTimeRewriteModule::create
 */
bool datatools::DataSetTimeRewriteModule::create(void) {
    for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) {
        if (IsCallDescriptionCompatible(cd)) {
            this->outDataSlot.SetCallback(cd->ClassName(), "GetData", &DataSetTimeRewriteModule::getDataCallback);
            this->outDataSlot.SetCallback(cd->ClassName(), "GetExtent", &DataSetTimeRewriteModule::getExtentCallback);
            this->inDataSlot.SetCompatibleCall(cd);
        }
    }
    this->MakeSlotAvailable(&this->outDataSlot);
    this->MakeSlotAvailable(&this->inDataSlot);
    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::release
 */
void datatools::DataSetTimeRewriteModule::release(void) {
}

/*
 * datatools::DataSetTimeRewriteModule::IsCallDescriptionCompatible
 */
bool datatools::DataSetTimeRewriteModule::IsCallDescriptionCompatible(core::factories::CallDescription::ptr desc) {
    return (desc->FunctionCount() == 2)
        && vislib::StringA("GetData").Equals(desc->FunctionName(0), false)
        && vislib::StringA("GetExtent").Equals(desc->FunctionName(1), false);
}

/*
 * datatools::DataSetTimeRewriteModule::getDataCallback
 */
bool datatools::DataSetTimeRewriteModule::getDataCallback(core::Call& caller) {
    using megamol::core::AbstractGetData3DCall;
    if (!this->checkConnections(&caller)) return false;

    AbstractGetData3DCall *pgdc = dynamic_cast<AbstractGetData3DCall*>(&caller);
    if (pgdc == NULL) return false;

    AbstractGetData3DCall *ggdc = this->inDataSlot.CallAs<AbstractGetData3DCall>();
    if (ggdc == NULL) return false;

    int minF = this->firstFrameSlot.Param<core::param::IntParam>()->Value();
    int maxF = this->lastFrameSlot.Param<core::param::IntParam>()->Value();
    int lenF = this->frameStepSlot.Param<core::param::IntParam>()->Value();

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(ggdc, pgdc);
    // Change time code
    ggdc->SetFrameID(minF + pgdc->FrameID() * lenF);

    if (!(*ggdc)(0)) return false;

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(pgdc, ggdc);
    ggdc->SetUnlocker(nullptr, false);
    // Change time code
    unsigned int fid = ggdc->FrameID();
    unsigned int fc = ggdc->FrameCount();
    unsigned int nfc = (std::min<unsigned int>(maxF, fc) - minF) / lenF;
    unsigned int nfid = (std::min<unsigned int>(maxF, fid) - minF) / lenF;
    pgdc->SetFrameCount(nfc);
    pgdc->SetFrameID(nfid);

    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::getExtentCallback
 */
bool datatools::DataSetTimeRewriteModule::getExtentCallback(core::Call& caller) {
    using megamol::core::AbstractGetData3DCall;
    if (!this->checkConnections(&caller)) return false;

    AbstractGetData3DCall *pgdc = dynamic_cast<AbstractGetData3DCall*>(&caller);
    if (pgdc == NULL) return false;

    AbstractGetData3DCall *ggdc = this->inDataSlot.CallAs<AbstractGetData3DCall>();
    if (ggdc == NULL) return false;

    int minF = this->firstFrameSlot.Param<core::param::IntParam>()->Value();
    int maxF = this->lastFrameSlot.Param<core::param::IntParam>()->Value();
    int lenF = this->frameStepSlot.Param<core::param::IntParam>()->Value();

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(ggdc, pgdc);
    // Change time code
    ggdc->SetFrameID(minF + pgdc->FrameID() * lenF);

    if (!(*ggdc)(1)) return false;

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(pgdc, ggdc);
    ggdc->SetUnlocker(nullptr, false);
    // Change time code
    unsigned int fid = ggdc->FrameID();
    unsigned int fc = ggdc->FrameCount();
    unsigned int nfc = (std::min<unsigned int>(maxF, fc) - minF) / lenF;
    unsigned int nfid = (std::min<unsigned int>(maxF, fid) - minF) / lenF;
    pgdc->SetFrameCount(nfc);
    pgdc->SetFrameID(nfid);

    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::checkConnections
 */
bool datatools::DataSetTimeRewriteModule::checkConnections(core::Call *outCall) {
    if (this->inDataSlot.GetStatus() != core::AbstractSlot::STATUS_CONNECTED) return false;
    if (this->outDataSlot.GetStatus() != core::AbstractSlot::STATUS_CONNECTED) return false;
    core::Call *inCall = this->inDataSlot.CallAs<core::Call>();
    if ((inCall == NULL) || (outCall == NULL)) return false;
    for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) {
        if (IsCallDescriptionCompatible(cd)) {
            if (cd->IsDescribing(inCall) && cd->IsDescribing(outCall)) return true;
        }
    }
    return false;
}
<commit_msg>fix. breaks configurator compatibility<commit_after>/*
 * DataSetTimeRewriteModule.cpp
 *
 * Copyright (C) 2014 by CGV TU Dresden
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "DataSetTimeRewriteModule.h"
#include "mmcore/AbstractGetData3DCall.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/factories/CallDescriptionManager.h"
#include "mmcore/param/IntParam.h"
#include <algorithm>

using namespace megamol;
using namespace megamol::stdplugin;

/*
 * datatools::DataSetTimeRewriteModule::DataSetTimeRewriteModule
 */
datatools::DataSetTimeRewriteModule::DataSetTimeRewriteModule(void) : core::Module(),
        outDataSlot("outData", "The slot for publishing data to the writer"),
        inDataSlot("inData", "The slot for requesting data from the source"),
        firstFrameSlot("firstFrame", "The number of the first frame"),
        lastFrameSlot("lastFrame", "The number of the last frame"),
        frameStepSlot("frameStep", "The step length between two frames") {

    //core::CallDescriptionManager::DescriptionIterator iter(core::CallDescriptionManager::Instance()->GetIterator());
    //const core::CallDescription *cd = NULL;
    //while ((cd = this->moveToNextCompatibleCall(iter)) != NULL) {
    //    this->outDataSlot.SetCallback(cd->ClassName(), "GetData", &DataSetTimeRewriteModule::getDataCallback);
    //    this->outDataSlot.SetCallback(cd->ClassName(), "GetExtent", &DataSetTimeRewriteModule::getExtentCallback);
    //    this->inDataSlot.SetCompatibleCall(*cd);
    //}

    //this->MakeSlotAvailable(&this->outDataSlot);
    //this->MakeSlotAvailable(&this->inDataSlot);

    this->firstFrameSlot.SetParameter(new core::param::IntParam(0, 0));
    this->MakeSlotAvailable(&this->firstFrameSlot);

    this->lastFrameSlot.SetParameter(new core::param::IntParam(1000000, 0));
    this->MakeSlotAvailable(&this->lastFrameSlot);

    this->frameStepSlot.SetParameter(new core::param::IntParam(1, 1));
    this->MakeSlotAvailable(&this->frameStepSlot);
}

/*
 * datatools::DataSetTimeRewriteModule::~DataSetTimeRewriteModule
 */
datatools::DataSetTimeRewriteModule::~DataSetTimeRewriteModule(void) {
    this->Release(); // implicitly calls 'release'
}

/*
 * datatools::DataSetTimeRewriteModule::create
 */
bool datatools::DataSetTimeRewriteModule::create(void) {
    for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) {
        if (IsCallDescriptionCompatible(cd)) {
            this->outDataSlot.SetCallback(cd->ClassName(), "GetData", &DataSetTimeRewriteModule::getDataCallback);
            this->outDataSlot.SetCallback(cd->ClassName(), "GetExtent", &DataSetTimeRewriteModule::getExtentCallback);
            this->inDataSlot.SetCompatibleCall(cd);
        }
    }
    this->MakeSlotAvailable(&this->outDataSlot);
    this->MakeSlotAvailable(&this->inDataSlot);
    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::release
 */
void datatools::DataSetTimeRewriteModule::release(void) {
}

/*
 * datatools::DataSetTimeRewriteModule::IsCallDescriptionCompatible
 */
bool datatools::DataSetTimeRewriteModule::IsCallDescriptionCompatible(core::factories::CallDescription::ptr desc) {
    return (desc->FunctionCount() == 2)
        && vislib::StringA("GetData").Equals(desc->FunctionName(0), false)
        && vislib::StringA("GetExtent").Equals(desc->FunctionName(1), false);
}

/*
 * datatools::DataSetTimeRewriteModule::getDataCallback
 */
bool datatools::DataSetTimeRewriteModule::getDataCallback(core::Call& caller) {
    using megamol::core::AbstractGetData3DCall;
    if (!this->checkConnections(&caller)) return false;

    AbstractGetData3DCall *pgdc = dynamic_cast<AbstractGetData3DCall*>(&caller);
    if (pgdc == NULL) return false;

    AbstractGetData3DCall *ggdc = this->inDataSlot.CallAs<AbstractGetData3DCall>();
    if (ggdc == NULL) return false;

    int minF = this->firstFrameSlot.Param<core::param::IntParam>()->Value();
    int maxF = this->lastFrameSlot.Param<core::param::IntParam>()->Value();
    int lenF = this->frameStepSlot.Param<core::param::IntParam>()->Value();

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(ggdc, pgdc);
    // Change time code
    ggdc->SetFrameID(minF + pgdc->FrameID() * lenF);

    if (!(*ggdc)(0)) return false;

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(pgdc, ggdc);
    ggdc->SetUnlocker(nullptr, false);
    // Change time code
    unsigned int fid = ggdc->FrameID();
    unsigned int fc = ggdc->FrameCount();
    unsigned int nfc = (std::min<unsigned int>(maxF, fc) - minF) / lenF;
    unsigned int nfid = (std::min<unsigned int>(maxF, fid) - minF) / lenF;
    pgdc->SetFrameCount(nfc);
    pgdc->SetFrameID(nfid);

    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::getExtentCallback
 */
bool datatools::DataSetTimeRewriteModule::getExtentCallback(core::Call& caller) {
    using megamol::core::AbstractGetData3DCall;
    if (!this->checkConnections(&caller)) return false;

    AbstractGetData3DCall *pgdc = dynamic_cast<AbstractGetData3DCall*>(&caller);
    if (pgdc == NULL) return false;

    AbstractGetData3DCall *ggdc = this->inDataSlot.CallAs<AbstractGetData3DCall>();
    if (ggdc == NULL) return false;

    int minF = this->firstFrameSlot.Param<core::param::IntParam>()->Value();
    int maxF = this->lastFrameSlot.Param<core::param::IntParam>()->Value();
    int lenF = this->frameStepSlot.Param<core::param::IntParam>()->Value();

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(ggdc, pgdc);
    // Change time code
    ggdc->SetFrameID(minF + pgdc->FrameID() * lenF);

    if (!(*ggdc)(1)) return false;

    this->GetCoreInstance()->GetCallDescriptionManager().AssignmentCrowbar(pgdc, ggdc);
    ggdc->SetUnlocker(nullptr, false);
    // Change time code
    unsigned int fid = ggdc->FrameID();
    unsigned int fc = ggdc->FrameCount();
    unsigned int nfc = (std::min<unsigned int>(maxF, fc) - minF) / lenF;
    unsigned int nfid = (std::min<unsigned int>(maxF, fid) - minF) / lenF;
    pgdc->SetFrameCount(nfc);
    pgdc->SetFrameID(nfid);

    return true;
}

/*
 * datatools::DataSetTimeRewriteModule::checkConnections
 */
bool datatools::DataSetTimeRewriteModule::checkConnections(core::Call *outCall) {
    if (this->inDataSlot.GetStatus() != core::AbstractSlot::STATUS_CONNECTED) return false;
    if (this->outDataSlot.GetStatus() != core::AbstractSlot::STATUS_CONNECTED) return false;
    core::Call *inCall = this->inDataSlot.CallAs<core::Call>();
    if ((inCall == NULL) || (outCall == NULL)) return false;
    for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) {
        if (IsCallDescriptionCompatible(cd)) {
            if (cd->IsDescribing(inCall) && cd->IsDescribing(outCall)) return true;
        }
    }
    return false;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2017, John Haddon. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferVDB/LevelSetToMesh.h"

#include "IECoreVDB/VDBObject.h"

#include "Gaffer/StringPlug.h"

#include "IECoreScene/MeshPrimitive.h"

#include "openvdb/openvdb.h"
#include "openvdb/tools/VolumeToMesh.h"

#include "boost/mpl/for_each.hpp"
#include "boost/mpl/list.hpp"

using namespace std;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace IECoreVDB;
using namespace Gaffer;
using namespace GafferVDB;

//////////////////////////////////////////////////////////////////////////
// Utilities. Perhaps these belong in Cortex one day?
//////////////////////////////////////////////////////////////////////////

namespace
{

struct MesherDispatch
{
	MesherDispatch( openvdb::GridBase::ConstPtr grid, openvdb::tools::VolumeToMesh &mesher ) : m_grid( grid ), m_mesher( mesher )
	{
	}

	template<typename GridType>
	void execute()
	{
		if( typename GridType::ConstPtr t = openvdb::GridBase::constGrid<GridType>( m_grid ) )
		{
			m_mesher( *t );
		}
	}

	openvdb::GridBase::ConstPtr m_grid;
	openvdb::tools::VolumeToMesh &m_mesher;
};

static std::map<std::string, std::function<void( MesherDispatch& dispatch )> > meshers =
{
	{ openvdb::typeNameAsString<bool>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::BoolGrid>(); } },
	{ openvdb::typeNameAsString<double>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::DoubleGrid>(); } },
	{ openvdb::typeNameAsString<float>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::FloatGrid>(); } },
	{ openvdb::typeNameAsString<int32_t>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::Int32Grid>(); } },
	{ openvdb::typeNameAsString<int64_t>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::Int64Grid>(); } }
};

IECoreScene::MeshPrimitivePtr volumeToMesh( openvdb::GridBase::ConstPtr grid, double isoValue, double adaptivity )
{
	openvdb::tools::VolumeToMesh mesher( isoValue, adaptivity );
	MesherDispatch dispatch( grid, mesher );

	const auto it = meshers.find( grid->valueType() );
	if( it != meshers.end() )
	{
		it->second( dispatch );
	}
	else
	{
		throw IECore::InvalidArgumentException( boost::str( boost::format( "Incompatible Grid found name: '%1%' type: '%2' " ) % grid->valueType() % grid->getName() ) );
	}

	// Copy out topology
	IntVectorDataPtr verticesPerFaceData = new IntVectorData;
	vector<int> &verticesPerFace = verticesPerFaceData->writable();

	IntVectorDataPtr vertexIdsData = new IntVectorData;
	vector<int> &vertexIds = vertexIdsData->writable();

	size_t numPolygons = 0;
	size_t numVerts = 0;
	for( size_t i = 0, n = mesher.polygonPoolListSize(); i < n; ++i )
	{
		const openvdb::tools::PolygonPool &polygonPool = mesher.polygonPoolList()[i];
		numPolygons += polygonPool.numQuads() + polygonPool.numTriangles();
		numVerts += polygonPool.numQuads() * 4 + polygonPool.numTriangles() * 3;
	}

	verticesPerFace.reserve( numPolygons );
	vertexIds.reserve( numVerts );

	for( size_t i = 0, n = mesher.polygonPoolListSize(); i < n; ++i )
	{
		const openvdb::tools::PolygonPool &polygonPool = mesher.polygonPoolList()[i];
		for( size_t qi = 0, qn = polygonPool.numQuads(); qi < qn; ++qi )
		{
			openvdb::math::Vec4ui quad = polygonPool.quad( qi );
			verticesPerFace.push_back( 4 );
			vertexIds.push_back( quad[0] );
			vertexIds.push_back( quad[1] );
			vertexIds.push_back( quad[2] );
			vertexIds.push_back( quad[3] );
		}

		for( size_t ti = 0, tn = polygonPool.numTriangles(); ti < tn; ++ti )
		{
			openvdb::math::Vec3ui triangle = polygonPool.triangle( ti );
			verticesPerFace.push_back( 3 );
			vertexIds.push_back( triangle[0] );
			vertexIds.push_back( triangle[1] );
			vertexIds.push_back( triangle[2] );
		}
	}

	// Copy out points
	V3fVectorDataPtr pointsData = new V3fVectorData;
	vector<V3f> &points = pointsData->writable();

	points.reserve( mesher.pointListSize() );
	for( size_t i = 0, n = mesher.pointListSize(); i < n; ++i )
	{
		const openvdb::math::Vec3s v = mesher.pointList()[i];
		points.push_back( V3f( v.x(), v.y(), v.z() ) );
	}

	return new MeshPrimitive( verticesPerFaceData, vertexIdsData, "linear", pointsData );
}

} // namespace

//////////////////////////////////////////////////////////////////////////
// VolumeToMesh implementation
//////////////////////////////////////////////////////////////////////////

GAFFER_NODE_DEFINE_TYPE( LevelSetToMesh );

size_t LevelSetToMesh::g_firstPlugIndex = 0;

LevelSetToMesh::LevelSetToMesh( const std::string &name )
	:	Deformer( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );

	addChild( new StringPlug( "grid", Plug::In, "surface" ) );
	addChild( new FloatPlug( "isoValue", Plug::In, 0.0f ) );
	addChild( new FloatPlug( "adaptivity", Plug::In, 0.0f, 0.0f, 1.0f ) );

}

LevelSetToMesh::~LevelSetToMesh()
{
}

Gaffer::StringPlug *LevelSetToMesh::gridPlug()
{
	return  getChild<StringPlug>( g_firstPlugIndex );
}

const Gaffer::StringPlug *LevelSetToMesh::gridPlug() const
{
	return  getChild<StringPlug>( g_firstPlugIndex );
}

Gaffer::FloatPlug *LevelSetToMesh::isoValuePlug()
{
	return getChild<FloatPlug>( g_firstPlugIndex + 1);
}

const Gaffer::FloatPlug *LevelSetToMesh::isoValuePlug() const
{
	return getChild<FloatPlug>( g_firstPlugIndex + 1);
}

Gaffer::FloatPlug *LevelSetToMesh::adaptivityPlug()
{
	return getChild<FloatPlug>( g_firstPlugIndex + 2 );
}

const Gaffer::FloatPlug *LevelSetToMesh::adaptivityPlug() const
{
	return getChild<FloatPlug>( g_firstPlugIndex + 2 );
}

bool LevelSetToMesh::affectsProcessedObject( const Gaffer::Plug *input ) const
{
	return
		input == isoValuePlug() ||
		input == adaptivityPlug() ||
		input == gridPlug()
	;
}

void LevelSetToMesh::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	Deformer::hashProcessedObject( path, context, h );

	gridPlug()->hash( h );
	isoValuePlug()->hash( h );
	adaptivityPlug()->hash( h );
}

IECore::ConstObjectPtr LevelSetToMesh::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, const IECore::Object *inputObject ) const
{
	const VDBObject *vdbObject = runTimeCast<const VDBObject>( inputObject );
	if( !vdbObject )
	{
		return inputObject;
	}

	openvdb::GridBase::ConstPtr grid = vdbObject->findGrid( gridPlug()->getValue() );

	if (!grid)
	{
		return inputObject;
	}

	return volumeToMesh( grid, isoValuePlug()->getValue(), adaptivityPlug()->getValue() );
}

bool LevelSetToMesh::affectsProcessedObjectBound( const Gaffer::Plug *input ) const
{
	return input == inPlug()->boundPlug() || input == isoValuePlug();
}

void LevelSetToMesh::hashProcessedObjectBound( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	inPlug()->boundPlug()->hash( h );
	isoValuePlug()->hash( h );
}

Imath::Box3f LevelSetToMesh::computeProcessedObjectBound( const ScenePath &path, const Gaffer::Context *context ) const
{
	/// \todo `in.bound` includes the child bounds. Ideally we
	/// would have a separate `in.objectBound` with just the bounds
	/// of the input object.
	const Box3f inputBound = inPlug()->boundPlug()->getValue();
	const V3f offset( isoValuePlug()->getValue() );
	return Box3f( inputBound.min - offset, inputBound.max + offset );
}
<commit_msg>LevelSetToMesh : Remove unused includes<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2017, John Haddon. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferVDB/LevelSetToMesh.h"

#include "Gaffer/StringPlug.h"

#include "IECoreVDB/VDBObject.h"

#include "IECoreScene/MeshPrimitive.h"

#include "openvdb/openvdb.h"
#include "openvdb/tools/VolumeToMesh.h"

using namespace std;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace IECoreVDB;
using namespace Gaffer;
using namespace GafferVDB;

//////////////////////////////////////////////////////////////////////////
// Utilities. Perhaps these belong in Cortex one day?
//////////////////////////////////////////////////////////////////////////

namespace
{

struct MesherDispatch
{
	MesherDispatch( openvdb::GridBase::ConstPtr grid, openvdb::tools::VolumeToMesh &mesher ) : m_grid( grid ), m_mesher( mesher )
	{
	}

	template<typename GridType>
	void execute()
	{
		if( typename GridType::ConstPtr t = openvdb::GridBase::constGrid<GridType>( m_grid ) )
		{
			m_mesher( *t );
		}
	}

	openvdb::GridBase::ConstPtr m_grid;
	openvdb::tools::VolumeToMesh &m_mesher;
};

static std::map<std::string, std::function<void( MesherDispatch& dispatch )> > meshers =
{
	{ openvdb::typeNameAsString<bool>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::BoolGrid>(); } },
	{ openvdb::typeNameAsString<double>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::DoubleGrid>(); } },
	{ openvdb::typeNameAsString<float>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::FloatGrid>(); } },
	{ openvdb::typeNameAsString<int32_t>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::Int32Grid>(); } },
	{ openvdb::typeNameAsString<int64_t>(), []( MesherDispatch& dispatch ) { dispatch.execute<openvdb::Int64Grid>(); } }
};

IECoreScene::MeshPrimitivePtr volumeToMesh( openvdb::GridBase::ConstPtr grid, double isoValue, double adaptivity )
{
	openvdb::tools::VolumeToMesh mesher( isoValue, adaptivity );
	MesherDispatch dispatch( grid, mesher );

	const auto it = meshers.find( grid->valueType() );
	if( it != meshers.end() )
	{
		it->second( dispatch );
	}
	else
	{
		throw IECore::InvalidArgumentException( boost::str( boost::format( "Incompatible Grid found name: '%1%' type: '%2' " ) % grid->valueType() % grid->getName() ) );
	}

	// Copy out topology
	IntVectorDataPtr verticesPerFaceData = new IntVectorData;
	vector<int> &verticesPerFace = verticesPerFaceData->writable();

	IntVectorDataPtr vertexIdsData = new IntVectorData;
	vector<int> &vertexIds = vertexIdsData->writable();

	size_t numPolygons = 0;
	size_t numVerts = 0;
	for( size_t i = 0, n = mesher.polygonPoolListSize(); i < n; ++i )
	{
		const openvdb::tools::PolygonPool &polygonPool = mesher.polygonPoolList()[i];
		numPolygons += polygonPool.numQuads() + polygonPool.numTriangles();
		numVerts += polygonPool.numQuads() * 4 + polygonPool.numTriangles() * 3;
	}

	verticesPerFace.reserve( numPolygons );
	vertexIds.reserve( numVerts );

	for( size_t i = 0, n = mesher.polygonPoolListSize(); i < n; ++i )
	{
		const openvdb::tools::PolygonPool &polygonPool = mesher.polygonPoolList()[i];
		for( size_t qi = 0, qn = polygonPool.numQuads(); qi < qn; ++qi )
		{
			openvdb::math::Vec4ui quad = polygonPool.quad( qi );
			verticesPerFace.push_back( 4 );
			vertexIds.push_back( quad[0] );
			vertexIds.push_back( quad[1] );
			vertexIds.push_back( quad[2] );
			vertexIds.push_back( quad[3] );
		}

		for( size_t ti = 0, tn = polygonPool.numTriangles(); ti < tn; ++ti )
		{
			openvdb::math::Vec3ui triangle = polygonPool.triangle( ti );
			verticesPerFace.push_back( 3 );
			vertexIds.push_back( triangle[0] );
			vertexIds.push_back( triangle[1] );
			vertexIds.push_back( triangle[2] );
		}
	}

	// Copy out points
	V3fVectorDataPtr pointsData = new V3fVectorData;
	vector<V3f> &points = pointsData->writable();

	points.reserve( mesher.pointListSize() );
	for( size_t i = 0, n = mesher.pointListSize(); i < n; ++i )
	{
		const openvdb::math::Vec3s v = mesher.pointList()[i];
		points.push_back( V3f( v.x(), v.y(), v.z() ) );
	}

	return new MeshPrimitive( verticesPerFaceData, vertexIdsData, "linear", pointsData );
}

} // namespace

//////////////////////////////////////////////////////////////////////////
// VolumeToMesh implementation
//////////////////////////////////////////////////////////////////////////

GAFFER_NODE_DEFINE_TYPE( LevelSetToMesh );

size_t LevelSetToMesh::g_firstPlugIndex = 0;

LevelSetToMesh::LevelSetToMesh( const std::string &name )
	:	Deformer( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );

	addChild( new StringPlug( "grid", Plug::In, "surface" ) );
	addChild( new FloatPlug( "isoValue", Plug::In, 0.0f ) );
	addChild( new FloatPlug( "adaptivity", Plug::In, 0.0f, 0.0f, 1.0f ) );

}

LevelSetToMesh::~LevelSetToMesh()
{
}

Gaffer::StringPlug *LevelSetToMesh::gridPlug()
{
	return  getChild<StringPlug>( g_firstPlugIndex );
}

const Gaffer::StringPlug *LevelSetToMesh::gridPlug() const
{
	return  getChild<StringPlug>( g_firstPlugIndex );
}

Gaffer::FloatPlug *LevelSetToMesh::isoValuePlug()
{
	return getChild<FloatPlug>( g_firstPlugIndex + 1);
}

const Gaffer::FloatPlug *LevelSetToMesh::isoValuePlug() const
{
	return getChild<FloatPlug>( g_firstPlugIndex + 1);
}

Gaffer::FloatPlug *LevelSetToMesh::adaptivityPlug()
{
	return getChild<FloatPlug>( g_firstPlugIndex + 2 );
}

const Gaffer::FloatPlug *LevelSetToMesh::adaptivityPlug() const
{
	return getChild<FloatPlug>( g_firstPlugIndex + 2 );
}

bool LevelSetToMesh::affectsProcessedObject( const Gaffer::Plug *input ) const
{
	return
		input == isoValuePlug() ||
		input == adaptivityPlug() ||
		input == gridPlug()
	;
}

void LevelSetToMesh::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	Deformer::hashProcessedObject( path, context, h );

	gridPlug()->hash( h );
	isoValuePlug()->hash( h );
	adaptivityPlug()->hash( h );
}

IECore::ConstObjectPtr LevelSetToMesh::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, const IECore::Object *inputObject ) const
{
	const VDBObject *vdbObject = runTimeCast<const VDBObject>( inputObject );
	if( !vdbObject )
	{
		return inputObject;
	}

	openvdb::GridBase::ConstPtr grid = vdbObject->findGrid( gridPlug()->getValue() );

	if (!grid)
	{
		return inputObject;
	}

	return volumeToMesh( grid, isoValuePlug()->getValue(), adaptivityPlug()->getValue() );
}

bool LevelSetToMesh::affectsProcessedObjectBound( const Gaffer::Plug *input ) const
{
	return input == inPlug()->boundPlug() || input == isoValuePlug();
}

void LevelSetToMesh::hashProcessedObjectBound( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	inPlug()->boundPlug()->hash( h );
	isoValuePlug()->hash( h );
}

Imath::Box3f LevelSetToMesh::computeProcessedObjectBound( const ScenePath &path, const Gaffer::Context *context ) const
{
	/// \todo `in.bound` includes the child bounds. Ideally we
	/// would have a separate `in.objectBound` with just the bounds
	/// of the input object.
	const Box3f inputBound = inPlug()->boundPlug()->getValue();
	const V3f offset( isoValuePlug()->getValue() );
	return Box3f( inputBound.min - offset, inputBound.max + offset );
}
<|endoftext|>


<commit_before>#include "Genes/Mutation_Rate_Gene.h"

#include <string>
#include <map>

#include "Genes/Gene.h"
#include "Game/Color.h"

#include "Utility/Random.h"

class Board;

Mutation_Rate_Gene::Mutation_Rate_Gene() noexcept
{
    zero_out_priority();
}

std::string Mutation_Rate_Gene::name() const noexcept
{
    return "Mutation Rate Gene";
}

int Mutation_Rate_Gene::mutation_count() const noexcept
{
    return int(mutated_components_per_mutation);
}

void Mutation_Rate_Gene::gene_specific_mutation() noexcept
{
    mutated_components_per_mutation += Random::random_laplace(1.0);
    mutated_components_per_mutation = std::max(1.0, mutated_components_per_mutation);
}

double Mutation_Rate_Gene::score_board(const Board&, Piece_Color, size_t) const noexcept
{
    return 0.0;
}

void Mutation_Rate_Gene::adjust_properties(std::map<std::string, double>& properties) const noexcept
{
    properties.erase("Priority");
    properties.erase("Active");
    properties["Mutation Rate"] = mutated_components_per_mutation;
}

void Mutation_Rate_Gene::load_gene_properties(const std::map<std::string, double>& properties)
{
    mutated_components_per_mutation = properties.at("Mutation Rate");
}
<commit_msg>Increase minimum mutation rate<commit_after>#include "Genes/Mutation_Rate_Gene.h"

#include <string>
#include <map>

#include "Genes/Gene.h"
#include "Game/Color.h"

#include "Utility/Random.h"

class Board;

Mutation_Rate_Gene::Mutation_Rate_Gene() noexcept
{
    zero_out_priority();
}

std::string Mutation_Rate_Gene::name() const noexcept
{
    return "Mutation Rate Gene";
}

int Mutation_Rate_Gene::mutation_count() const noexcept
{
    return int(mutated_components_per_mutation);
}

void Mutation_Rate_Gene::gene_specific_mutation() noexcept
{
    mutated_components_per_mutation += Random::random_laplace(1.0);
    mutated_components_per_mutation = std::max(3.0, mutated_components_per_mutation);
}

double Mutation_Rate_Gene::score_board(const Board&, Piece_Color, size_t) const noexcept
{
    return 0.0;
}

void Mutation_Rate_Gene::adjust_properties(std::map<std::string, double>& properties) const noexcept
{
    properties.erase("Priority");
    properties.erase("Active");
    properties["Mutation Rate"] = mutated_components_per_mutation;
}

void Mutation_Rate_Gene::load_gene_properties(const std::map<std::string, double>& properties)
{
    mutated_components_per_mutation = properties.at("Mutation Rate");
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(TRU64DEFINITIONS_HEADER_GUARD_1357924680)
#define TRU64DEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

// This next line enables standard IO streams.
#define __USE_STD_IOSTREAM
#define XALAN_RTTI_AVAILABLE
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN
#define XALAN_INLINE_INITIALIZATION
#define XALAN_LSTRSUPPORT

#define XALAN_UNALIGNED __unaligned

#endif  // TRU64DEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>New defines for -std strict_ansi_errors option.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(TRU64DEFINITIONS_HEADER_GUARD_1357924680)
#define TRU64DEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

// This next line enables standard IO streams.
#define __USE_STD_IOSTREAM
#define XALAN_RTTI_AVAILABLE
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN
#define XALAN_INLINE_INITIALIZATION
#define XALAN_LSTRSUPPORT

#if defined(__STD_STRICT_ANSI_ERRORS)
#define XALAN_STRICT_ANSI_HEADERS
#define XALAN_SIZE_T_IN_NAMESPACE_STD
#endif

#define XALAN_UNALIGNED __unaligned

#endif  // TRU64DEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>#pragma once

#include "../ast/point.hpp"
#include "../common/wrdMetaExtension.hpp"
#include "../type/wtype.hpp"
#include <unordered_map>

namespace wrd {

	typedef std::unordered_map<widx, std::string> msgMap;

	struct err : public instance {
		WRD(ME(err, instance),
			TYPE(wtype),
			INIT_META(me))

	public:
		enum type {
			ERR = 0,
			WARN,
			INFO,
		};

	public:
		err(err::type t, wcnt errCode, ...): super(), fType(t), code(errCode) {
            va_list args;
            va_start(args, errCode);

            msg = _format(getErrMsgs().at(code), args);
            va_end(args);
		}
        err(err::type t, wcnt errCode, va_list args): super(), fType(t), code(errCode) {
            msg = _format(getErrMsgs().at(code), args);
        }

	public:
		virtual void log() const {
			switch(fType) {
				case ERR: WRD_E("%s", msg.c_str()); break;
				case WARN: WRD_W("%s", msg.c_str()); break;
				case INFO: WRD_I("%s", msg.c_str()); break;
			}
		}
		static const msgMap& getErrMsgs();
        static err* newErr(wcnt errCode, ...);
        static err* newErr(const area& src, wcnt errCode, ...);
        static err* newWarn(wcnt errCode, ...);
        static err* newWarn(const area& src, wcnt errCode, ...);
        static err* newInfo(wcnt errCode, ...);
        static err* newInfo(const area& src, wcnt errCode, ...);

	public:
		err::type fType;
		wcnt code;
		std::string msg;
		static constexpr wint BASE_TEST_CODE = 99999990; // not to be duplicated.

    private:
        std::string _format(const std::string& fmt, va_list args);
        err* _newRes(type t, wcnt errCode, va_list args) {
            return new err(t, errCode, args);
        }
        err* _newRes(const area& src, type t, wcnt errCode, va_list args);
	};

    struct dummyErr : public err {
        WRD(ME(dummyErr, err),
            TYPE(wtype),
            INIT_META(me))

    public:
        dummyErr(): super(err::ERR, 0) {}

    public:
        void log() const override {}
    };

	struct srcErr : public err {
		WRD(ME(srcErr, err),
			TYPE(wtype),
			INIT_META(me))

	public:
        template <typename... Args>
        srcErr(err::type t, const area& src, wcnt errCode, Args... args): super(t, errCode, args...), srcArea(src) {}

		area srcArea;

    public:
        void log() const override {
            switch(fType) {
                case ERR: WRD_E("%d:%d: err(%d): %s", code, srcArea.start.row, srcArea.start.col, msg.c_str()); break;
                case WARN: WRD_W(":%d:%d: warn(%d): %s", code, srcArea.start.row, srcArea.start.col, msg.c_str()); break;
                case INFO: WRD_I(":%d:%d: info(%d): %s", code, srcArea.start.row, srcArea.start.col, msg.c_str()); break;
            }
        }
	};
}
<commit_msg>wrd: fix: errCode was on wrong place as arg when call log()<commit_after>#pragma once

#include "../ast/point.hpp"
#include "../common/wrdMetaExtension.hpp"
#include "../type/wtype.hpp"
#include <unordered_map>

namespace wrd {

	typedef std::unordered_map<widx, std::string> msgMap;

	struct err : public instance {
		WRD(ME(err, instance),
			TYPE(wtype),
			INIT_META(me))

	public:
		enum type {
			ERR = 0,
			WARN,
			INFO,
		};

	public:
		err(err::type t, wcnt errCode, ...): super(), fType(t), code(errCode) {
            va_list args;
            va_start(args, errCode);

            msg = _format(getErrMsgs().at(code), args);
            va_end(args);
		}
        err(err::type t, wcnt errCode, va_list args): super(), fType(t), code(errCode) {
            msg = _format(getErrMsgs().at(code), args);
        }

	public:
		virtual void log() const {
			switch(fType) {
				case ERR: WRD_E("%s", msg.c_str()); break;
				case WARN: WRD_W("%s", msg.c_str()); break;
				case INFO: WRD_I("%s", msg.c_str()); break;
			}
		}
		static const msgMap& getErrMsgs();
        static err* newErr(wcnt errCode, ...);
        static err* newErr(const area& src, wcnt errCode, ...);
        static err* newWarn(wcnt errCode, ...);
        static err* newWarn(const area& src, wcnt errCode, ...);
        static err* newInfo(wcnt errCode, ...);
        static err* newInfo(const area& src, wcnt errCode, ...);

	public:
		err::type fType;
		wcnt code;
		std::string msg;
		static constexpr wint BASE_TEST_CODE = 99999990; // not to be duplicated.

    private:
        std::string _format(const std::string& fmt, va_list args);
        err* _newRes(type t, wcnt errCode, va_list args) {
            return new err(t, errCode, args);
        }
        err* _newRes(const area& src, type t, wcnt errCode, va_list args);
	};

    struct dummyErr : public err {
        WRD(ME(dummyErr, err),
            TYPE(wtype),
            INIT_META(me))

    public:
        dummyErr(): super(err::ERR, 0) {}

    public:
        void log() const override {}
    };

	struct srcErr : public err {
		WRD(ME(srcErr, err),
			TYPE(wtype),
			INIT_META(me))

	public:
        template <typename... Args>
        srcErr(err::type t, const area& src, wcnt errCode, Args... args): super(t, errCode, args...), srcArea(src) {}

		area srcArea;

    public:
        void log() const override {
            switch(fType) {
                case ERR: WRD_E("%d:%d: err(%d): %s", srcArea.start.row, srcArea.start.col, code, msg.c_str()); break;
                case WARN: WRD_W(":%d:%d: warn(%d): %s", srcArea.start.row, srcArea.start.col, code, msg.c_str()); break;
                case INFO: WRD_I(":%d:%d: info(%d): %s", srcArea.start.row, srcArea.start.col, code, msg.c_str()); break;
            }
        }
	};
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DrawDocShell.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:32:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_DRAW_DOC_SHELL_HXX
#define SD_DRAW_DOC_SHELL_HXX

#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#include <vcl/jobset.hxx>

#ifndef _SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif
#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef INCLUDED_SDDLLAPI_H
#include "sddllapi.h"
#endif
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

class SfxStyleSheetBasePool;
class SfxStatusBarManager;
class SdStyleSheetPool;
class FontList;
class SdDrawDocument;
class SvxItemFactory;
class SdPage;
class SfxPrinter;
struct SdrDocumentStreamInfo;
struct SpellCallbackInfo;
class AbstractSvxNameDialog;
class SdFormatClipboard;

namespace sd {

class FrameView;
class View;
class ViewShell;

// ------------------
// - DrawDocShell -
// ------------------

class SD_DLLPUBLIC DrawDocShell : public SfxObjectShell
{
public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SD_IF_SDDRAWDOCSHELL)
    SFX_DECL_OBJECTFACTORY();

    DrawDocShell (
        SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
        BOOL bSdDataObj=FALSE,
        DocumentType=DOCUMENT_TYPE_IMPRESS);

    DrawDocShell (
        SdDrawDocument* pDoc,
        SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
        BOOL bSdDataObj=FALSE,
        DocumentType=DOCUMENT_TYPE_IMPRESS);
    virtual ~DrawDocShell();

    void                    UpdateRefDevice();
    virtual void            Activate( BOOL bMDI );
    virtual void            Deactivate( BOOL bMDI );
    virtual BOOL            InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL            ConvertFrom( SfxMedium &rMedium );
    virtual BOOL            Save();
    virtual BOOL            SaveAsOwnFormat( SfxMedium& rMedium );
    virtual BOOL            ConvertTo( SfxMedium &rMedium );
    virtual BOOL            SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    virtual sal_Bool        Load( SfxMedium &rMedium  );
    virtual sal_Bool        LoadFrom( SfxMedium& rMedium );
    virtual sal_Bool        SaveAs( SfxMedium &rMedium  );

    virtual Rectangle       GetVisArea(USHORT nAspect) const;
    virtual void            Draw(OutputDevice*, const JobSetup& rSetup, USHORT nAspect = ASPECT_CONTENT);
    virtual SfxUndoManager* GetUndoManager();
    virtual Printer*        GetDocumentPrinter();
    virtual void            OnDocumentPrinterChanged(Printer* pNewPrinter);
    virtual SfxStyleSheetBasePool* GetStyleSheetPool();
    virtual void            SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const;
    virtual Size            GetFirstPageSize();
    virtual void            FillClass(SvGlobalName* pClassName, sal_uInt32*  pFormat, String* pAppName, String* pFullTypeName, String* pShortTypeName, sal_Int32 nFileFormat ) const;
    virtual void            SetModified( BOOL = TRUE );

    using SotObject::GetInterface;
    using SfxObjectShell::GetVisArea;
    using SfxShell::GetViewShell;

    sd::ViewShell* GetViewShell() { return mpViewShell; }
    ::sd::FrameView* GetFrameView();
    ::Window* GetWindow() const;
    ::sd::FunctionReference GetDocShellFunction() const { return mxDocShellFunction; }
    void SetDocShellFunction( const ::sd::FunctionReference& xFunction );

    SdDrawDocument*         GetDoc();
    DocumentType            GetDocumentType() const { return meDocType; }

    SfxPrinter*             GetPrinter(BOOL bCreate);
    void                    SetPrinter(SfxPrinter *pNewPrinter);
    void                    UpdateFontList();

    BOOL                    IsInDestruction() const { return mbInDestruction; }

    void                    CancelSearching();

    void                    Execute( SfxRequest& rReq );
    void                    GetState(SfxItemSet&);

    void                    Connect(sd::ViewShell* pViewSh);
    void                    Disconnect(sd::ViewShell* pViewSh);
    void                    UpdateTablePointers();

    BOOL                    GotoBookmark(const String& rBookmark);

    Bitmap                  GetPagePreviewBitmap(SdPage* pPage, USHORT nMaxEdgePixel);

    /** checks, if the given name is a valid new name for a slide

If the name is invalid, an <type>SvxNameDialog</type> pops up that
        queries again for a new name until it is ok or the user chose
        Cancel.

        @param pWin is necessary to pass to the <type>SvxNameDialog</type> in
                    case an invalid name was entered.
        @param rName the new name that is to be set for a slide.  This string
                     may be set to an empty string (see below).

        @return TRUE, if the new name is unique.  Note that if the user entered
                a default name of a not-yet-existing slide (e.g. 'Slide 17'),
                TRUE is returned, but rName is set to an empty string.
     */
    BOOL                    CheckPageName(::Window* pWin, String& rName );

    void                    SetSlotFilter(BOOL bEnable = FALSE, USHORT nCount = 0, const USHORT* pSIDs = NULL) { mbFilterEnable = bEnable; mnFilterCount = nCount; mpFilterSIDs = pSIDs; }
    void                    ApplySlotFilter() const;

    UINT16                  GetStyleFamily() const { return mnStyleFamily; }
    void                    SetStyleFamily( UINT16 nSF ) { mnStyleFamily = nSF; }

    BOOL                    HasSpecialProgress() const { return ( mpSpecialProgress != NULL && mpSpecialProgressHdl != NULL ); }
    void                    ReleaseSpecialProgress() { mpSpecialProgress = NULL; mpSpecialProgressHdl = NULL; }
    void                    SetSpecialProgress( SfxProgress* _pProgress, Link* pLink ) { mpSpecialProgress = _pProgress; mpSpecialProgressHdl = pLink; }
    SfxProgress*            GetSpecialProgress() { return( HasSpecialProgress() ? mpSpecialProgress : NULL ); }

    sal_Bool                IsNewDocument() const;

    /** executes the SID_OPENDOC slot to let the framework open a document
        with the given URL and this document as a referer */
    void                    OpenBookmark( const String& rBookmarkURL );

    /** checks, if the given name is a valid new name for a slide

This method does not pop up any dialog (like CheckPageName).

        @param rInOutPageName the new name for a slide that is to be renamed.
                    This string will be set to an empty string if
                    bResetStringIfStandardName is true and the name is of the
                    form of any, possibly not-yet existing, standard slide
                    (e.g. 'Slide 17')

        @param bResetStringIfStandardName if true allows setting rInOutPageName
                    to an empty string, which returns true and implies that the
                    slide will later on get a new standard name (with a free
                    slide number).

        @return true, if the new name is unique.  If bResetStringIfStandardName
                    is true, the return value is also true, if the slide name is
                    a standard name (see above)
     */
    bool                    IsNewPageNameValid( String & rInOutPageName, bool bResetStringIfStandardName = false );

    /** Return the reference device for the current document.  When the
        inherited implementation returns a device then this is passed to the
        caller.  Otherwise the returned value depends on the printer
        independent layout mode and will usually be either a printer or a
        virtual device used for screen rendering.
        @return
            Returns NULL when the current document has no reference device.
    */
    virtual OutputDevice* GetDocumentRefDev (void);

    DECL_LINK( RenameSlideHdl, AbstractSvxNameDialog* );

                            // #91457# ExecuteSpellPopup now handled by DrawDocShell
                            DECL_LINK( OnlineSpellCallback, SpellCallbackInfo* );

public:
    SdFormatClipboard*      mpFormatClipboard;

protected:

    SdDrawDocument*         mpDoc;
    SfxUndoManager*         mpUndoManager;
    SfxPrinter*             mpPrinter;
    ::sd::ViewShell*        mpViewShell;
    FontList*               mpFontList;
    ::sd::FunctionReference mxDocShellFunction;
    DocumentType            meDocType;
    UINT16                  mnStyleFamily;
    const USHORT*           mpFilterSIDs;
    USHORT                  mnFilterCount;
    BOOL                    mbFilterEnable;
    BOOL                    mbSdDataObj;
    BOOL                    mbInDestruction;
    BOOL                    mbOwnPrinter;
    BOOL                    mbNewDocument;

    static SfxProgress*     mpSpecialProgress;
    static Link*            mpSpecialProgressHdl;

    bool                    mbOwnDocument;          // if true, we own mpDoc and will delete it in our d'tor
    void                    Construct();
    virtual void            InPlaceActivate( BOOL bActive );
};

#ifndef SV_DECL_DRAW_DOC_SHELL_DEFINED
#define SV_DECL_DRAW_DOC_SHELL_DEFINED
SV_DECL_REF(DrawDocShell)
#endif

SV_IMPL_REF (DrawDocShell)

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS impress136_SRC680 (1.14.224); FILE MERGED 2007/11/28 16:21:59 cl 1.14.224.1: #i79757# consolidate clear undo code to DrawDocShell::ClearUndoBuffer()<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DrawDocShell.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-28 14:55:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_DRAW_DOC_SHELL_HXX
#define SD_DRAW_DOC_SHELL_HXX

#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#include <vcl/jobset.hxx>

#ifndef _SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif
#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef INCLUDED_SDDLLAPI_H
#include "sddllapi.h"
#endif
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

class SfxStyleSheetBasePool;
class SfxStatusBarManager;
class SdStyleSheetPool;
class FontList;
class SdDrawDocument;
class SvxItemFactory;
class SdPage;
class SfxPrinter;
struct SdrDocumentStreamInfo;
struct SpellCallbackInfo;
class AbstractSvxNameDialog;
class SdFormatClipboard;

namespace sd {

class FrameView;
class View;
class ViewShell;

// ------------------
// - DrawDocShell -
// ------------------

class SD_DLLPUBLIC DrawDocShell : public SfxObjectShell
{
public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SD_IF_SDDRAWDOCSHELL)
    SFX_DECL_OBJECTFACTORY();

    DrawDocShell (
        SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
        BOOL bSdDataObj=FALSE,
        DocumentType=DOCUMENT_TYPE_IMPRESS);

    DrawDocShell (
        SdDrawDocument* pDoc,
        SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
        BOOL bSdDataObj=FALSE,
        DocumentType=DOCUMENT_TYPE_IMPRESS);
    virtual ~DrawDocShell();

    void                    UpdateRefDevice();
    virtual void            Activate( BOOL bMDI );
    virtual void            Deactivate( BOOL bMDI );
    virtual BOOL            InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL            ConvertFrom( SfxMedium &rMedium );
    virtual BOOL            Save();
    virtual BOOL            SaveAsOwnFormat( SfxMedium& rMedium );
    virtual BOOL            ConvertTo( SfxMedium &rMedium );
    virtual BOOL            SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    virtual sal_Bool        Load( SfxMedium &rMedium  );
    virtual sal_Bool        LoadFrom( SfxMedium& rMedium );
    virtual sal_Bool        SaveAs( SfxMedium &rMedium  );

    virtual Rectangle       GetVisArea(USHORT nAspect) const;
    virtual void            Draw(OutputDevice*, const JobSetup& rSetup, USHORT nAspect = ASPECT_CONTENT);
    virtual SfxUndoManager* GetUndoManager();
    virtual Printer*        GetDocumentPrinter();
    virtual void            OnDocumentPrinterChanged(Printer* pNewPrinter);
    virtual SfxStyleSheetBasePool* GetStyleSheetPool();
    virtual void            SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const;
    virtual Size            GetFirstPageSize();
    virtual void            FillClass(SvGlobalName* pClassName, sal_uInt32*  pFormat, String* pAppName, String* pFullTypeName, String* pShortTypeName, sal_Int32 nFileFormat ) const;
    virtual void            SetModified( BOOL = TRUE );

    using SotObject::GetInterface;
    using SfxObjectShell::GetVisArea;
    using SfxShell::GetViewShell;

    sd::ViewShell* GetViewShell() { return mpViewShell; }
    ::sd::FrameView* GetFrameView();
    ::Window* GetWindow() const;
    ::sd::FunctionReference GetDocShellFunction() const { return mxDocShellFunction; }
    void SetDocShellFunction( const ::sd::FunctionReference& xFunction );

    SdDrawDocument*         GetDoc();
    DocumentType            GetDocumentType() const { return meDocType; }

    SfxPrinter*             GetPrinter(BOOL bCreate);
    void                    SetPrinter(SfxPrinter *pNewPrinter);
    void                    UpdateFontList();

    BOOL                    IsInDestruction() const { return mbInDestruction; }

    void                    CancelSearching();

    void                    Execute( SfxRequest& rReq );
    void                    GetState(SfxItemSet&);

    void                    Connect(sd::ViewShell* pViewSh);
    void                    Disconnect(sd::ViewShell* pViewSh);
    void                    UpdateTablePointers();

    BOOL                    GotoBookmark(const String& rBookmark);

    Bitmap                  GetPagePreviewBitmap(SdPage* pPage, USHORT nMaxEdgePixel);

    /** checks, if the given name is a valid new name for a slide

If the name is invalid, an <type>SvxNameDialog</type> pops up that
        queries again for a new name until it is ok or the user chose
        Cancel.

        @param pWin is necessary to pass to the <type>SvxNameDialog</type> in
                    case an invalid name was entered.
        @param rName the new name that is to be set for a slide.  This string
                     may be set to an empty string (see below).

        @return TRUE, if the new name is unique.  Note that if the user entered
                a default name of a not-yet-existing slide (e.g. 'Slide 17'),
                TRUE is returned, but rName is set to an empty string.
     */
    BOOL                    CheckPageName(::Window* pWin, String& rName );

    void                    SetSlotFilter(BOOL bEnable = FALSE, USHORT nCount = 0, const USHORT* pSIDs = NULL) { mbFilterEnable = bEnable; mnFilterCount = nCount; mpFilterSIDs = pSIDs; }
    void                    ApplySlotFilter() const;

    UINT16                  GetStyleFamily() const { return mnStyleFamily; }
    void                    SetStyleFamily( UINT16 nSF ) { mnStyleFamily = nSF; }

    BOOL                    HasSpecialProgress() const { return ( mpSpecialProgress != NULL && mpSpecialProgressHdl != NULL ); }
    void                    ReleaseSpecialProgress() { mpSpecialProgress = NULL; mpSpecialProgressHdl = NULL; }
    void                    SetSpecialProgress( SfxProgress* _pProgress, Link* pLink ) { mpSpecialProgress = _pProgress; mpSpecialProgressHdl = pLink; }
    SfxProgress*            GetSpecialProgress() { return( HasSpecialProgress() ? mpSpecialProgress : NULL ); }

    sal_Bool                IsNewDocument() const;

    /** executes the SID_OPENDOC slot to let the framework open a document
        with the given URL and this document as a referer */
    void                    OpenBookmark( const String& rBookmarkURL );

    /** checks, if the given name is a valid new name for a slide

This method does not pop up any dialog (like CheckPageName).

        @param rInOutPageName the new name for a slide that is to be renamed.
                    This string will be set to an empty string if
                    bResetStringIfStandardName is true and the name is of the
                    form of any, possibly not-yet existing, standard slide
                    (e.g. 'Slide 17')

        @param bResetStringIfStandardName if true allows setting rInOutPageName
                    to an empty string, which returns true and implies that the
                    slide will later on get a new standard name (with a free
                    slide number).

        @return true, if the new name is unique.  If bResetStringIfStandardName
                    is true, the return value is also true, if the slide name is
                    a standard name (see above)
     */
    bool                    IsNewPageNameValid( String & rInOutPageName, bool bResetStringIfStandardName = false );

    /** Return the reference device for the current document.  When the
        inherited implementation returns a device then this is passed to the
        caller.  Otherwise the returned value depends on the printer
        independent layout mode and will usually be either a printer or a
        virtual device used for screen rendering.
        @return
            Returns NULL when the current document has no reference device.
    */
    virtual OutputDevice* GetDocumentRefDev (void);

    DECL_LINK( RenameSlideHdl, AbstractSvxNameDialog* );

                            // #91457# ExecuteSpellPopup now handled by DrawDocShell
                            DECL_LINK( OnlineSpellCallback, SpellCallbackInfo* );

    void                    ClearUndoBuffer();

public:
    SdFormatClipboard*      mpFormatClipboard;

protected:

    SdDrawDocument*         mpDoc;
    SfxUndoManager*         mpUndoManager;
    SfxPrinter*             mpPrinter;
    ::sd::ViewShell*        mpViewShell;
    FontList*               mpFontList;
    ::sd::FunctionReference mxDocShellFunction;
    DocumentType            meDocType;
    UINT16                  mnStyleFamily;
    const USHORT*           mpFilterSIDs;
    USHORT                  mnFilterCount;
    BOOL                    mbFilterEnable;
    BOOL                    mbSdDataObj;
    BOOL                    mbInDestruction;
    BOOL                    mbOwnPrinter;
    BOOL                    mbNewDocument;

    static SfxProgress*     mpSpecialProgress;
    static Link*            mpSpecialProgressHdl;

    bool                    mbOwnDocument;          // if true, we own mpDoc and will delete it in our d'tor
    void                    Construct();
    virtual void            InPlaceActivate( BOOL bActive );
};

#ifndef SV_DECL_DRAW_DOC_SHELL_DEFINED
#define SV_DECL_DRAW_DOC_SHELL_DEFINED
SV_DECL_REF(DrawDocShell)
#endif

SV_IMPL_REF (DrawDocShell)

} // end of namespace sd

#endif
<|endoftext|>