How to set different colors for different parts of a single 3D model? The article introduces a way that set scalars for pointData and map the information by vtkColorTransferFunction object, then vtkPolyDataMapper object configure a correct scalar mode and use vtkColorTransferFunction object as its lookupTable.
The code snippet shows all details of implementation, the data file curve.vtp
can be downloaded from my github repository documents
#define vtkSPtr vtkSmartPointer
#define vtkSPtrNew(Var, Type) vtkSPtr<Type> Var = vtkSPtr<Type>::New();
using namespace std;
int main()
{
vtkSPtrNew( reader, vtkXMLPolyDataReader );
reader->SetFileName( "/Users/weiyang/Desktop/curve.vtp" );
reader->Update();
vtkPolyData *pd = reader->GetOutput();
vtkPoints *points = pd->GetPoints();
int ptsCount = pd->GetNumberOfPoints();
vtkSPtrNew( scalars, vtkCharArray );
scalars->SetNumberOfTuples( ptsCount );
enum E_Colors{ RED, GREEN, BLUE };
E_Colors COLORS[3] = { RED, GREEN, BLUE };
for( int i = 0; i < ptsCount / 4; ++i )
{
scalars->SetTuple1(i, RED);
}
for( int i = ptsCount / 4; i < ptsCount / 2; ++i )
{
scalars->SetTuple1(i, GREEN);
}
for( int i = ptsCount / 2; i < ptsCount; ++i )
{
scalars->SetTuple1(i, BLUE);
}
pd->GetPointData()->SetScalars( scalars );
vtkSPtrNew( mapper, vtkPolyDataMapper );
mapper->SetInputConnection( reader->GetOutputPort() );
mapper->SetScalarModeToUsePointData();
vtkSPtrNew( lut, vtkColorTransferFunction );
lut->SetClamping( 0 );
int colorParameters[3][3] = { {255, 0, 0}, {0, 255, 0}, {0, 0, 255} };
for( int i = 0; i < 3; ++i )
{
lut->AddRGBPoint( COLORS[i], colorParameters[i][0]/255.0, colorParameters[i][1]/255.0, colorParameters[i][2]/255.0 );
}
mapper->SetLookupTable( lut );
mapper->SetScalarRange( COLORS[0], COLORS[2] );
vtkSPtrNew( actor, vtkActor );
actor->SetMapper( mapper );
actor->GetProperty()->SetLineWidth( 3 );
vtkSPtrNew( axesActor, vtkAxesActor );
vtkSPtrNew( renderer, vtkRenderer );
renderer->AddActor( actor );
renderer->AddActor( axesActor );
renderer->SetBackground( 0, 0, 0 );
vtkSPtrNew( renderWindow, vtkRenderWindow );
renderWindow->AddRenderer( renderer );
vtkSPtrNew( renderWindowInteractor, vtkRenderWindowInteractor );
renderWindowInteractor->SetRenderWindow( renderWindow );
renderer->ResetCamera();
renderWindow->Render();
renderWindowInteractor->Start();
return 0;
}
Header files:
#include <iostream>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkActor.h>
#include <vtkConeSource.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkPolyDataMapper.h>
#include <vtkLineSource.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkAxesActor.h>
#include <vtkProperty.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkCharArray.h>
#include <vtkPointData.h>
#include <vtkColorTransferFunction.h>