long ClipVolumeData ( vtkImageData *result, vtkImageData *data, vtkDataSet *element) // version 1.0
{
vtkImplicitDataSet *ids = vtkImplicitDataSet::New();
vtkImageReslice *reslice = vtkImageReslice::New();
vtkImplicitFunctionToImageStencil *stencilCreator = vtkImplicitFunctionToImageStencil::New();
double spacing[3], origin[3], bounds[6], Pcenter[3];
int newbox[6], extent[6];
//compute the new bounding box
element->ComputeBounds();
element->GetBounds(bounds);
data->GetSpacing(spacing);
data->GetWholeExtent(extent);
data->GetOrigin(origin);
newbox[0]=(int)((bounds[0]-origin[0])/spacing[0])+extent[0];
newbox[1]=(int)((bounds[1]-origin[0])/spacing[0])+extent[0];
newbox[2]=(int)((bounds[2]-origin[1])/spacing[1])+extent[2];
newbox[3]=(int)((bounds[3]-origin[1])/spacing[1])+extent[2];
newbox[4]=(int)((bounds[4]-origin[2])/spacing[2])+extent[4];
newbox[5]=(int)((bounds[5]-origin[2])/spacing[2])+extent[4];
//transform the dataset into a function which returns 1 if a given point is inside the volume, setOutValue otherwise
ids->SetDataSet(element);
ids->SetOutValue(10.0);
//pass all the necessary information to the "cookie cutter"
stencilCreator->SetOutputOrigin(origin);
stencilCreator->SetOutputSpacing(spacing);
stencilCreator->SetOutputWholeExtent(newbox);
stencilCreator->SetInput(ids);
double stencilCreator_Threshold = 5.0; //the values below threshold will be considered as background
stencilCreator->SetThreshold(stencilCreator_Threshold);
//Clip the data
reslice->ReleaseDataFlagOn();
stencilCreator->ReleaseDataFlagOn();
reslice->TransformInputSamplingOff();
reslice->SetInputConnection(0,data->GetProducerPort());
double reslice_background_level = 2.;
reslice->SetBackgroundLevel(reslice_background_level);
reslice->SetOutputSpacing(spacing);
reslice->SetOutputOrigin(origin);
reslice->SetOutputExtent(newbox);
//reslice->Update();
regionVolume=vtkImageData::New();
regionVolume->DeepCopy(reslice->GetOutput());
regionVolume->SetSource(NULL);
//Set the values outside the finite element to the background value
reslice->SetStencil(stencilCreator->GetOutput());
vtkTimerLog *timerClip = vtkTimerLog::New();
timerClip->StartTimer();
timerClip->MarkStartEvent("before update");
reslice->Update();
timerClip->MarkEndEvent("after update");
timerClip->StopTimer();
timerClip->DumpLog("logClip");
regionVolume->ComputeBounds();
result->DeepCopy(reslice->GetOutput());
ids->Delete();
reslice->Delete();
stencilCreator->Delete();
return 0;
}