[vtkusers] how to cast a vtkDataArray from one type into	another?
    David Doria 
    daviddoria+vtk at gmail.com
       
    Thu Oct  8 05:55:39 EDT 2009
    
    
  
On Tue, Oct 6, 2009 at 4:30 PM, Fabio Meneghini <fab.meneghini at gmail.com>wrote:
> Hi all,
> just like the subject of this topic says:
> Let's suppose I got a vtkPolyData with one vtkDataArray field with scalar
> values, of type unsigned char.
> Is there a way to quickly cast all the unsigned char values after loading
> and before visualizing the data??
>
> Thanks in advance,
>
> Cheers.
>
> Fabio Meneghini
>
I thought SafeDowncast would do this - but I guess not? Can anyone explain
why this example does not work (my "invalid cast" output is hit):
#include <vtkDoubleArray.h>
#include <vtkIntArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <iostream>
int main(int argc, char *argv[])
{
    //create points
    vtkPoints* Points = vtkPoints::New();
    unsigned int NumberOfPoints = 3;
    Points->InsertNextPoint(0.0, 0.0, 0.0);
    Points->InsertNextPoint(1.0, 0.0, 0.0);
    Points->InsertNextPoint(0.0, 1.0, 0.0);
    //add the points to a polydata
    vtkPolyData* polydata = vtkPolyData::New();
    polydata->SetPoints(Points);
    //add distances to each point
    vtkDoubleArray* Distances = vtkDoubleArray::New();
    Distances->SetNumberOfComponents(1);
    Distances->SetName("Distances");
    Distances->InsertNextValue(1.1);
    Distances->InsertNextValue(2.2);
    Distances->InsertNextValue(3.3);
    polydata->GetPointData()->AddArray(Distances);
    //get the distances from the polydata
    vtkDoubleArray* Array =
vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetArray("Distances"));
    if(Array)
    {
        for(unsigned int i = 0; i < NumberOfPoints; i++)
        {
            double dist;
            dist = Array->GetValue(i);
            std::cout << "Distance: " << dist << std::endl;
        }
    }
    //cast the double distances to ints
    vtkDoubleArray* DoubleDistances =
vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetArray("Distances"));
    vtkIntArray* IntDistances = vtkIntArray::SafeDownCast(DoubleDistances);
    if(IntDistances)
    {
        for(unsigned int i = 0; i < NumberOfPoints; i++)
        {
            int dist;
            dist = IntDistances->GetValue(i);
            std::cout << "Distance: " << dist << std::endl;
        }
    }
    else
    {
        std::cout << "invalid cast." << std::endl;
    }
    return 0;
}
Thanks,
David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.vtk.org/pipermail/vtkusers/attachments/20091008/8bc39a2d/attachment.htm>
    
    
More information about the vtkusers
mailing list