OSG::NodePtr makePolygon(double pntData[][3], int numPoints) {

  OSG::GeometryPtr geoPtr  = OSG::Geometry::create();
  OSG::NodePtr     nodePtr = OSG::Node::create();

  GeoPositions3fPtr    pnts    = GeoPositions3f::create();
  GeoNormals3fPtr      norms   = GeoNormals3f::create();
  GeoTexCoords2fPtr    tex     = GeoTexCoords2f::create();
  GeoIndicesUI32Ptr    indices = GeoIndicesUI32::create();   
  GeoPLengthsUI32Ptr   lens    = GeoPLengthsUI32::create();  
  GeoPTypesUI8Ptr      types   = GeoPTypesUI8::create();     

  //Set up the properties according to the geometry defined above
  beginEditCP(pnts);
  beginEditCP(norms);
  
  for(int i = 0; i < numPoints; i++) 
    {
      pnts->push_back(Pnt3f(pntData[i][0],
                            pntData[i][1], 
                            pntData[i][2]));

      indices->push_back(2*i);

      norms->push_back(Vec3f(0.0, 0.0, pntData[i][2]));
      indices->push_back(2*i + 1);
    }

  endEditCP(pnts);
  endEditCP(norms);

  beginEditCP(types);
  beginEditCP(lens);
  types->push_back(GL_POLYGON);
  lens->push_back(numPoints);
  endEditCP(types);
  endEditCP(lens);

  beginEditCP(geoPtr);
  
  geoPtr->setMaterial(getDefaultMaterial());
  geoPtr->setPositions(pnts);
  geoPtr->setNormals(norms);
  geoPtr->setIndices(indices);
  
  geoPtr->editMFIndexMapping()->push_back(Geometry::MapPosition | 
                                          Geometry::MapNormal);
  
  geoPtr->setTypes(types);
  geoPtr->setLengths(lens);
  
  endEditCP(geoPtr);

  nodePtr->setCore(geoPtr);
  return nodePtr;
}
Beispiel #2
0
NodePtr createScenegraph(){
    // the scene must be created here
    for (int x = 0; x < N; x++)
        for (int z = 0; z < N; z++)
            wMesh[x][z] = 0;
            
    // GeoPTypes will define the types of primitives to be used
    GeoPTypesPtr type = GeoPTypesUI8::create();
    beginEditCP(type, GeoPTypesUI8::GeoPropDataFieldMask);
	// we want to use quads ONLY 
	type->addValue(GL_QUADS);
    endEditCP(type, GeoPTypesUI8::GeoPropDataFieldMask);
    
    // GeoPLength will define the number of vertices of
    // the used primitives
    GeoPLengthsPtr length = GeoPLengthsUI32::create();
    beginEditCP(length, GeoPLengthsUI32::GeoPropDataFieldMask);
	// the length of our quads is four ;-)
	length->addValue((N-1)*(N-1)*4);
    endEditCP(length, GeoPLengthsUI32::GeoPropDataFieldMask);

    // GeoPositions3f stores the positions of all vertices used in 
    // this specific geometry core
    GeoPositions3fPtr pos = GeoPositions3f::create();
    beginEditCP(pos, GeoPositions3f::GeoPropDataFieldMask);
	// here they all come
	for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		pos->addValue(Pnt3f(x, wMesh[x][z], z));
    endEditCP(pos, GeoPositions3f::GeoPropDataFieldMask);

    //GeoColors3f stores all color values that will be used
    GeoColors3fPtr colors = GeoColors3f::create();
    beginEditCP(colors, GeoColors3f::GeoPropDataFieldMask);
        for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		colors->addValue(Color3f(0,0,1));
    endEditCP(colors, GeoColors3f::GeoPropDataFieldMask);
    
    GeoNormals3fPtr norms = GeoNormals3f::create();
    beginEditCP(norms, GeoNormals3f::GeoPropDataFieldMask);
        for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		// As initially all heights are set to zero thus yielding a plane,
		// we set all normals to (0,1,0) parallel to the y-axis
		norms->addValue(Vec3f(0,1,0));
    endEditCP(norms, GeoNormals3f::GeoPropDataFieldMask);
    
    SimpleMaterialPtr mat = SimpleMaterial::create();
    beginEditCP(mat);
        mat->setDiffuse(Color3f(0,0,1));
    endEditCP(mat);
    
    // GeoIndicesUI32 points to all relevant data used by the 
    // provided primitives
    GeoIndicesUI32Ptr indices = GeoIndicesUI32::create();
    beginEditCP(indices, GeoIndicesUI32::GeoPropDataFieldMask);
        for (int x = 0; x < N-1; x++)
            for (int z = 0; z < N-1; z++){
		// points to four vertices that will
		// define a single quad
		indices->addValue(z*N+x);	
		indices->addValue((z+1)*N+x);
		indices->addValue((z+1)*N+x+1);
		indices->addValue(z*N+x+1);
            }
    endEditCP(indices, GeoIndicesUI32::GeoPropDataFieldMask);

        GeometryPtr geo = Geometry::create();
    beginEditCP(geo,
        Geometry::TypesFieldMask	|
	Geometry::LengthsFieldMask	|
	Geometry::IndicesFieldMask	|
	Geometry::PositionsFieldMask	|
	Geometry::NormalsFieldMask      |
        Geometry::MaterialFieldMask     |
	Geometry::ColorsFieldMask	|
        Geometry::DlistCacheFieldMask
	);
	
	geo->setTypes(type);
	geo->setLengths(length);
	geo->setIndices(indices);
	geo->setPositions(pos);
	geo->setNormals(norms);
        geo->setMaterial(mat);
	//geo->setColors(colors);
        geo->setDlistCache(false);

    endEditCP(geo,
        Geometry::TypesFieldMask	|
	Geometry::LengthsFieldMask	|
	Geometry::IndicesFieldMask	|
	Geometry::PositionsFieldMask	|
	Geometry::NormalsFieldMask	|
        Geometry::MaterialFieldMask     |
	Geometry::ColorsFieldMask	|
        Geometry::DlistCacheFieldMask
	);
    
    PointLightPtr pLight = PointLight::create();
    NodePtr root = Node::create();
    NodePtr water = Node::create();
    NodePtr pLightTransformNode = Node::create();
    TransformPtr pLightTransform = Transform::create();
    NodePtr pLightNode = Node::create();
    
    beginEditCP(pLightNode);
        pLightNode->setCore(Group::create());
    endEditCP(pLightNode);
    
    Matrix m;
    m.setIdentity();
    m.setTranslate(50,25,50);
    
    beginEditCP(pLightTransform);
        pLightTransform->setMatrix(m);
    endEditCP(pLightTransform);
    
    //we add a little spehere that will represent the light source
    GeometryPtr sphere = makeSphereGeo(2,2);

    SimpleMaterialPtr sm = SimpleMaterial::create();

    beginEditCP(sm, SimpleMaterial::DiffuseFieldMask |
                    SimpleMaterial::LitFieldMask);
    {
        sm->setLit(false);
        sm->setDiffuse(Color3f(1,1,1));
    }
    endEditCP  (sm, SimpleMaterial::DiffuseFieldMask |
                    SimpleMaterial::LitFieldMask);

    beginEditCP(sphere, Geometry::MaterialFieldMask);
    {
        sphere->setMaterial(sm);
    }
    endEditCP  (sphere, Geometry::MaterialFieldMask);
    
    NodePtr sphereNode = Node::create();
    beginEditCP(sphereNode);
        sphereNode->setCore(sphere);
    endEditCP(sphereNode);

    beginEditCP(pLightTransformNode);
        pLightTransformNode->setCore(pLightTransform);
        pLightTransformNode->addChild(pLightNode);
        pLightTransformNode->addChild(sphereNode);
    endEditCP(pLightTransformNode);

    beginEditCP(pLight);
        pLight->setPosition(Pnt3f(0,0,0));
    
        //Attenuation parameters
        pLight->setConstantAttenuation(1);
        pLight->setLinearAttenuation(0);
        pLight->setQuadraticAttenuation(0);
        
        //color information
        pLight->setDiffuse(Color4f(1,1,1,1));
        pLight->setAmbient(Color4f(0.2,0.2,0.2,1));
        pLight->setSpecular(Color4f(1,1,1,1));
        
        //set the beacon
        pLight->setBeacon(pLightNode);
    endEditCP  (pLight);

    
    beginEditCP(water);
        water->setCore(geo);
    endEditCP(water);
    
    beginEditCP(root);
        root->setCore(pLight);
        root->addChild(water);
        root->addChild(pLightTransformNode);
    endEditCP(root);    
    return root;
}
Beispiel #3
0
NodePtr createScenegraph(){
    // the scene must be created here
    for (int x = 0; x < N; x++)
        for (int z = 0; z < N; z++)
            wMesh[x][z] = 0;
            
    // GeoPTypes will define the types of primitives to be used
    GeoPTypesPtr type = GeoPTypesUI8::create();
    beginEditCP(type, GeoPTypesUI8::GeoPropDataFieldMask);
	// we want to use quads ONLY 
	type->addValue(GL_QUADS);
    endEditCP(type, GeoPTypesUI8::GeoPropDataFieldMask);
    
    // GeoPLength will define the number of vertices of
    // the used primitives
    GeoPLengthsPtr length = GeoPLengthsUI32::create();
    beginEditCP(length, GeoPLengthsUI32::GeoPropDataFieldMask);
	// the length of our quads is four ;-)
	length->addValue((N-1)*(N-1)*4);
    endEditCP(length, GeoPLengthsUI32::GeoPropDataFieldMask);

    // GeoPositions3f stores the positions of all vertices used in 
    // this specific geometry core
    GeoPositions3fPtr pos = GeoPositions3f::create();
    beginEditCP(pos, GeoPositions3f::GeoPropDataFieldMask);
	// here they all come
	for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		pos->addValue(Pnt3f(x, wMesh[x][z], z));
    endEditCP(pos, GeoPositions3f::GeoPropDataFieldMask);

    //GeoColors3f stores all color values that will be used
    GeoColors3fPtr colors = GeoColors3f::create();
    beginEditCP(colors, GeoColors3f::GeoPropDataFieldMask);
        for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		colors->addValue(Color3f(0,0,1));
    endEditCP(colors, GeoColors3f::GeoPropDataFieldMask);
    
    GeoNormals3fPtr norms = GeoNormals3f::create();
    beginEditCP(norms, GeoNormals3f::GeoPropDataFieldMask);
        for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
		// As initially all heights are set to zero thus yielding a plane,
		// we set all normals to (0,1,0) parallel to the y-axis
		norms->addValue(Vec3f(0,1,0));
    endEditCP(norms, GeoNormals3f::GeoPropDataFieldMask);
    
    SimpleMaterialPtr mat = SimpleMaterial::create();
    
    // GeoIndicesUI32 points to all relevant data used by the 
    // provided primitives
    GeoIndicesUI32Ptr indices = GeoIndicesUI32::create();
    beginEditCP(indices, GeoIndicesUI32::GeoPropDataFieldMask);
        for (int x = 0; x < N-1; x++)
            for (int z = 0; z < N-1; z++){
		// points to four vertices that will
		// define a single quad
		indices->addValue(z*N+x);	
		indices->addValue((z+1)*N+x);
		indices->addValue((z+1)*N+x+1);
		indices->addValue(z*N+x+1);
            }
    endEditCP(indices, GeoIndicesUI32::GeoPropDataFieldMask);

        GeometryPtr geo = Geometry::create();
    beginEditCP(geo,
        Geometry::TypesFieldMask	|
	Geometry::LengthsFieldMask	|
	Geometry::IndicesFieldMask	|
	Geometry::PositionsFieldMask	|
	Geometry::NormalsFieldMask      |
        Geometry::MaterialFieldMask     |
	Geometry::ColorsFieldMask	
	);
	
	geo->setTypes(type);
	geo->setLengths(length);
	geo->setIndices(indices);
	geo->setPositions(pos);
	geo->setNormals(norms);
        geo->setMaterial(mat);
	geo->setColors(colors);

    endEditCP(geo,
        Geometry::TypesFieldMask	|
	Geometry::LengthsFieldMask	|
	Geometry::IndicesFieldMask	|
	Geometry::PositionsFieldMask	|
	Geometry::NormalsFieldMask	|
        Geometry::MaterialFieldMask     |
	Geometry::ColorsFieldMask	
	);
        
    NodePtr root = Node::create();
    beginEditCP(root);
        root->setCore(geo);
    endEditCP(root);
	
    return root;
}
Beispiel #4
0
bool vtkOsgConverter::WriteAnActor()
{
	vtkMapper* actorMapper = _actor->GetMapper();
	// see if the actor has a mapper. it could be an assembly
	if (actorMapper == NULL)
		return false;
	// dont export when not visible
	if (_actor->GetVisibility() == 0)
		return false;

	vtkDataObject* inputDO = actorMapper->GetInputDataObject(0, 0);
	if (inputDO == NULL)
		return false;

	// Get PolyData. Convert if necessary becasue we only want polydata
	vtkSmartPointer<vtkPolyData> pd;
	if(inputDO->IsA("vtkCompositeDataSet"))
	{
		vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else if(inputDO->GetDataObjectType() != VTK_POLY_DATA)
	{
		vtkGeometryFilter* gf = vtkGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else
		pd = static_cast<vtkPolyData*>(inputDO);

	// Get the color range from actors lookup table
	double range[2];
	vtkLookupTable* actorLut = static_cast<vtkLookupTable*>(actorMapper->GetLookupTable());
	actorLut->GetTableRange(range);

	// Copy mapper to a new one
	vtkPolyDataMapper* pm = vtkPolyDataMapper::New();
	// Convert cell data to point data
	// NOTE: Comment this out to export a mesh
	if (actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA ||
		actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
	{
		vtkCellDataToPointData* cellDataToPointData = vtkCellDataToPointData::New();
		cellDataToPointData->PassCellDataOff();
		cellDataToPointData->SetInput(pd);
		cellDataToPointData->Update();
		pd = cellDataToPointData->GetPolyDataOutput();
		cellDataToPointData->Delete();

		pm->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_DATA);
	}
	else
		pm->SetScalarMode(actorMapper->GetScalarMode());

	pm->SetInput(pd);
	pm->SetScalarVisibility(actorMapper->GetScalarVisibility());

	vtkLookupTable* lut = NULL;
	// ParaView OpenSG Exporter
	if (dynamic_cast<vtkDiscretizableColorTransferFunction*>(actorMapper->GetLookupTable()))
		lut = actorLut;
	// Clone the lut in OGS because otherwise the original lut gets destroyed
	else
	{
		lut = vtkLookupTable::New();
		lut->DeepCopy(actorLut);
		lut->Build();
	}
	pm->SetLookupTable(lut);
	pm->SetScalarRange(range);
	pm->Update();

	if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ||
	   pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
	{
		if(actorMapper->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )
			pm->ColorByArrayComponent(actorMapper->GetArrayId(),
			                          actorMapper->GetArrayComponent());
		else
			pm->ColorByArrayComponent(actorMapper->GetArrayName(),
			                          actorMapper->GetArrayComponent());
	}


	vtkPointData* pntData = pd->GetPointData();
	bool hasTexCoords = false;
	vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0);

	// ARRAY SIZES
	vtkIdType m_iNumPoints = pd->GetNumberOfPoints();
	if (m_iNumPoints == 0)
		return false;
	vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells();
	vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells();
	vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells();
	vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells();
	vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons +
	                               m_iNumGLTriStrips;
	bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0);

	if (_verbose)
	{
		std::cout << "Array sizes:" << std::endl;
		std::cout << "  number of vertices: " << m_iNumPoints << std::endl;
		std::cout << "  number of GL_POINTS: " << m_iNumGLPoints << std::endl;
		std::cout << "  number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl;
		std::cout << "  number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl;
		std::cout << "  number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl;
		std::cout << "  number of primitives: " << m_iNumGLPrimitives << std::endl;
	}

	// NORMALS
	vtkDataArray* vtkNormals = NULL;
	int m_iNormalType = NOT_GIVEN;
	if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT)
	{
		vtkNormals = pd->GetCellData()->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_CELL;
	}
	else
	{
		vtkNormals = pntData->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_VERTEX;
	}
	if (_verbose)
	{
		std::cout << "Normals:" << std::endl;
		if (m_iNormalType != NOT_GIVEN)
		{
			std::cout << "  number of normals: " << vtkNormals->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  normals are given: ";
			std::cout <<
			((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no normals are given" << std::endl;
	}

	// COLORS
	int m_iColorType = NOT_GIVEN;
	if(pm->GetScalarVisibility())
	{
		int iScalarMode = pm->GetScalarMode();
		if(vtkColors == NULL)
		{
			m_iColorType = NOT_GIVEN;
			std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA)
			m_iColorType = PER_CELL;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA)
			m_iColorType = PER_VERTEX;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!"
			          << std::endl;
			m_iColorType = PER_CELL;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!"
			          << std::endl;
			m_iColorType = PER_VERTEX;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT)
		{
			//Bummer, we do not know what it is. may be we can make a guess
			int numColors = vtkColors->GetNumberOfTuples();
			if (numColors == 0)
			{
				m_iColorType = NOT_GIVEN;
				std::cout << "WARNING: No colors found!" << std::endl;
			}
			else if (numColors == m_iNumPoints)
				m_iColorType = PER_VERTEX;
			else if (numColors == m_iNumGLPrimitives)
				m_iColorType = PER_CELL;
			else
			{
				m_iColorType = NOT_GIVEN;
				std::cout <<
				"WARNING: Number of colors do not match number of points / cells!"
				          << std::endl;
			}
		}
	}
	if (_verbose)
	{
		std::cout << "Colors:" << std::endl;
		if (m_iColorType != NOT_GIVEN)
		{
			std::cout << "  number of colors: " << vtkColors->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  colors are given: " <<
			((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no colors are given" << std::endl;
	}

	// TEXCOORDS
	vtkDataArray* vtkTexCoords = pntData->GetTCoords();
	if (_verbose)
	{
		std::cout << "Tex-coords:" << std::endl;
		if (vtkTexCoords)
		{
			std::cout << "  Number of tex-coords: " <<
			vtkTexCoords->GetNumberOfTuples() << std::endl;
			hasTexCoords = true;
		}
		else
			std::cout << "  No tex-coords where given" << std::endl;
	}

	// TRANSFORMATION
	double scaling[3];
	double translation[3];
	// double rotation[3];

	_actor->GetPosition(translation);
	_actor->GetScale(scaling);
	//_actor->GetRotation(rotation[0], rotation[1], rotation[2]);

	if (_verbose)
		std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " <<
		scaling[2] << std::endl;

	osg::Matrix m;
	m.setIdentity();
	m.setTranslate(translation[0], translation[1], translation[2]);
	m.setScale(scaling[0], scaling[1], scaling[2]);
	// TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2])
	beginEditCP(_osgTransform);
	_osgTransform->setMatrix(m);
	endEditCP(_osgTransform);

	//pm->Update();

	// Get the converted OpenSG node
	NodePtr osgGeomNode = Node::create();
	GeometryPtr osgGeometry = Geometry::create();
	beginEditCP(osgGeomNode);
	osgGeomNode->setCore(osgGeometry);
	endEditCP(osgGeomNode);

	bool osgConversionSuccess = false;

	GeoPTypesPtr osgTypes = GeoPTypesUI8::create();
	GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create();
	GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create();
	GeoPositions3fPtr osgPoints = GeoPositions3f::create();
	GeoNormals3fPtr osgNormals = GeoNormals3f::create();
	GeoColors3fPtr osgColors = GeoColors3f::create();
	GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create();

	//Rendering with OpenSG simple indexed geometry
	if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) &&
		((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN)))
	{
		if (_verbose)
			std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << std::endl;

		//getting the vertices:
		beginEditCP(osgPoints);
		{
			for (int i = 0; i < m_iNumPoints; i++)
			{
				double* aVertex = pd->GetPoint(i);
				osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));
			}
		} endEditCP(osgPoints);

		//possibly getting the normals
		if (m_iNormalType == PER_VERTEX)
		{
			vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples();
			beginEditCP(osgNormals);
			{
				double* aNormal;
				for (int i = 0; i < iNumNormals; i++)
				{
					aNormal = vtkNormals->GetTuple(i);
					osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
				}
			} endEditCP(osgNormals);
			if (iNumNormals != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" <<	std::endl << std::endl;
			}
		}

		//possibly getting the colors
		if (m_iColorType == PER_VERTEX)
		{
			vtkIdType iNumColors = vtkColors->GetNumberOfTuples();
			beginEditCP(osgColors);
			{
				unsigned char aColor[4];
				for (int i = 0; i < iNumColors; i++)
				{
					vtkColors->GetTupleValue(i, aColor);
					float r = ((float) aColor[0]) / 255.0f;
					float g = ((float) aColor[1]) / 255.0f;
					float b = ((float) aColor[2]) / 255.0f;
					osgColors->addValue(Color3f(r, g, b));
				}
			} endEditCP(osgColors);
			if (iNumColors != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl;
			}
		}

		//possibly getting the texture coordinates. These are alwary per vertex
		if (vtkTexCoords != NULL)
		{
			int numTuples = vtkTexCoords->GetNumberOfTuples();
			for (int i = 0; i < numTuples; i++)
			{
				double texCoords[3];
				vtkTexCoords->GetTuple(i, texCoords);
				osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
			}
		}

		//getting the cells
		beginEditCP(osgTypes);
		beginEditCP(osgLengths);
		beginEditCP(osgIndices);
		{
			vtkCellArray* pCells;
			vtkIdType npts, * pts;
			int prim;

			prim = 0;
			pCells = pd->GetVerts();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POINTS);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetLines();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_LINE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetPolys();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POLYGON);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetStrips();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_TRIANGLE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}
		} endEditCP(osgIndices);
		endEditCP(osgLengths);
		endEditCP(osgTypes);

		ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
		beginEditCP(osgGeometry);
		{
			osgGeometry->setPositions(osgPoints);
			osgGeometry->setTypes(osgTypes);
			osgGeometry->setLengths(osgLengths);
			osgGeometry->setIndices(osgIndices);
			osgGeometry->setMaterial(material);

			if (m_iNormalType == PER_VERTEX)
				osgGeometry->setNormals(osgNormals);
			if (m_iColorType == PER_VERTEX)
				osgGeometry->setColors(osgColors);
			if (osgTexCoords->getSize() > 0)
				osgGeometry->setTexCoords(osgTexCoords);
		} endEditCP(osgGeometry);

		osgConversionSuccess = true;

		if (_verbose)
			std::cout << "    End ProcessGeometryNormalsAndColorsPerVertex()" <<
			std::endl;
	}
	else
	{
		//Rendering with OpenSG non indexed geometry by copying a lot of attribute data
		if (_verbose)
			std::cout <<
			"Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
		int gl_primitive_type = -1;
		if(m_iNumGLPolygons > 0)
		{
			if(m_iNumGLPolygons != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POLYGON;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry);
		}
		else if(m_iNumGLLineStrips > 0)
		{
			if (m_iNumGLLineStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_LINE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry);
		}
		else if(m_iNumGLTriStrips > 0)
		{
			if (m_iNumGLTriStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_TRIANGLE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry);
		}
		else if (m_iNumGLPoints > 0)
		{
			if (m_iNumGLPoints != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POINTS;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry);
		}
		if(gl_primitive_type != -1)
		{
			vtkCellArray* pCells;
			if (gl_primitive_type == GL_POINTS)
				pCells = pd->GetVerts();
			else if (gl_primitive_type == GL_LINE_STRIP)
				pCells = pd->GetLines();
			else if (gl_primitive_type == GL_POLYGON)
				pCells = pd->GetPolys();
			else if (gl_primitive_type == GL_TRIANGLE_STRIP)
				pCells = pd->GetStrips();
			else
			{
				std::cout <<
				"CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)"
				<< std::endl << " was called with non implemented gl_primitive_type!" << std::endl;
			}

			beginEditCP(osgTypes);
			beginEditCP(osgLengths);
			beginEditCP(osgPoints);
			beginEditCP(osgColors);
			beginEditCP(osgNormals);
			{
				int prim = 0;
				if (pCells->GetNumberOfCells() > 0)
				{
					vtkIdType npts, * pts;
					for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
					     prim++)
					{
						osgLengths->addValue(npts);
						osgTypes->addValue(GL_POLYGON);
						for (int i = 0; i < npts; i++)
						{
							double* aVertex;
							double* aNormal;
							unsigned char aColor[4];

							aVertex = pd->GetPoint(pts[i]);
							osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));

							if (m_iNormalType == PER_VERTEX)
							{
								aNormal =
								        vtkNormals->GetTuple(pts[i]);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}
							else if (m_iNormalType == PER_CELL)
							{
								aNormal = vtkNormals->GetTuple(prim);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}

							if (m_iColorType == PER_VERTEX)
							{
								vtkColors->GetTupleValue(pts[i], aColor);
								float r = ((float) aColor[0]) /	 255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
							else if (m_iColorType == PER_CELL)
							{
								vtkColors->GetTupleValue(prim,
								                         aColor);
								float r = ((float) aColor[0]) /	255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
						}
					}
				}
			} endEditCP(osgTypes);
			endEditCP(osgLengths);
			endEditCP(osgPoints);
			endEditCP(osgColors);
			endEditCP(osgNormals);

			//possibly getting the texture coordinates. These are always per vertex
			vtkPoints* points = pd->GetPoints();
			if ((vtkTexCoords != NULL) && (points != NULL))
			{
				int numPoints = points->GetNumberOfPoints();
				int numTexCoords = vtkTexCoords->GetNumberOfTuples();
				if (numPoints == numTexCoords)
				{
					beginEditCP(osgTexCoords);
					{
						int numTuples = vtkTexCoords->GetNumberOfTuples();
						for (int i = 0; i < numTuples; i++)
						{
							double texCoords[3];
							vtkTexCoords->GetTuple(i, texCoords);
							osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
						}
					} endEditCP(osgTexCoords);
				}
			}

			ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
			//GeometryPtr geo = Geometry::create();
			beginEditCP(osgGeometry);
			{
				osgGeometry->setPositions(osgPoints);
				osgGeometry->setTypes(osgTypes);
				osgGeometry->setLengths(osgLengths);
				osgGeometry->setMaterial(material);

				if (m_iNormalType != NOT_GIVEN)
					osgGeometry->setNormals(osgNormals);
				if (m_iColorType != NOT_GIVEN)
					osgGeometry->setColors(osgColors);
				if (osgTexCoords->getSize() > 0)
					osgGeometry->setTexCoords(osgTexCoords);
				//geo->setMaterial(getDefaultMaterial());
			} endEditCP(osgGeometry);

			osgConversionSuccess = true;
		}
		if (_verbose)
			std::cout <<
			"    End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
	}

	if(!osgConversionSuccess)
	{
		std::cout << "OpenSG converter was not able to convert this actor." << std::endl;
		return false;
	}

	if(m_iNormalType == NOT_GIVEN)
	{
		//GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore());
		if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
		else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per face!"
			          << std::endl;
			calcFaceNormals(osgGeometry);
		}
		else if (osgGeometry != NullFC)
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
	}

	std::cout << "Conversion finished." << std::endl;

	// Add node to root
	beginEditCP(_osgRoot);
	_osgRoot->addChild(osgGeomNode);
	endEditCP(_osgRoot);

	pm->Delete();

	return true;
}
Beispiel #5
0
// Create the coordinate cross
NodePtr createCoordinateCross()
{
    GeometryPtr geoPtr = Geometry::create();
    beginEditCP(geoPtr);
    {
        GeoPTypesUI8Ptr typesPtr = GeoPTypesUI8::create();
        typesPtr->push_back(GL_LINES);
        geoPtr->setTypes(typesPtr);

        GeoPLengthsUI32Ptr lensPtr = GeoPLengthsUI32::create();
        lensPtr->push_back(6);
        geoPtr->setLengths(lensPtr);

        GeoPositions3fPtr posPtr = GeoPositions3f::create();
        posPtr->push_back(Vec3f(-0.1f, 0.f, 0.f));
        posPtr->push_back(Vec3f(1.f, 0.f, 0.f));
        posPtr->push_back(Vec3f(0.f, -0.1f, 0.f));
        posPtr->push_back(Vec3f(0.f, 1.f, 0.f));
        posPtr->push_back(Vec3f(0.f, 0.f, -0.1f));
        posPtr->push_back(Vec3f(0.f, 0.f, 1.f));
        geoPtr->setPositions(posPtr);

        GeoColors3fPtr colorsPtr = GeoColors3f::create();
        colorsPtr->push_back(Color3f(1.f, 0.f, 0.f));
        colorsPtr->push_back(Color3f(0.f, 1.f, 0.f));
        colorsPtr->push_back(Color3f(0.f, 0.f, 1.f));
        geoPtr->setColors(colorsPtr);

        GeoIndicesUI32Ptr indicesPtr = GeoIndicesUI32::create();
        // X Axis
        indicesPtr->push_back(0);
        indicesPtr->push_back(0);
        indicesPtr->push_back(1);
        indicesPtr->push_back(0);
        // Y Axis
        indicesPtr->push_back(2);
        indicesPtr->push_back(1);
        indicesPtr->push_back(3);
        indicesPtr->push_back(1);
        // Z Axis
        indicesPtr->push_back(4);
        indicesPtr->push_back(2);
        indicesPtr->push_back(5);
        indicesPtr->push_back(2);
        geoPtr->setIndices(indicesPtr);

        geoPtr->editMFIndexMapping()->clear();
        geoPtr->editMFIndexMapping()->push_back(Geometry::MapPosition);
        geoPtr->editMFIndexMapping()->push_back(Geometry::MapColor);

        SimpleMaterialPtr matPtr = SimpleMaterial::create();
        geoPtr->setMaterial(matPtr);
    }
    endEditCP(geoPtr);

    NodePtr nodePtr = Node::create();
    beginEditCP(nodePtr, Node::CoreFieldMask);
    {
        nodePtr->setCore(geoPtr);
    }
    endEditCP(nodePtr, Node::CoreFieldMask);

    return nodePtr;
}
Beispiel #6
0
// Create the metrics
NodePtr createMetrics(TextFace *face, Real32 scale, const TextLayoutParam &layoutParam,
                      const TextLayoutResult &layoutResult)
{
    GeometryPtr geoPtr = Geometry::create();
    beginEditCP(geoPtr);
    {
        GeoPTypesUI8Ptr typesPtr = GeoPTypesUI8::create();
        geoPtr->setTypes(typesPtr);

        GeoPLengthsUI32Ptr lensPtr = GeoPLengthsUI32::create();
        geoPtr->setLengths(lensPtr);

        GeoPositions3fPtr posPtr = GeoPositions3f::create();
        geoPtr->setPositions(posPtr);

        GeoColors3fPtr colorsPtr = GeoColors3f::create();
        colorsPtr->push_back(Color3f(0.f, 0.f, 1.f));
        colorsPtr->push_back(Color3f(1.f, 0.f, 0.f));
        colorsPtr->push_back(Color3f(0.f, 1.f, 0.f));
        colorsPtr->push_back(Color3f(1.f, 1.f, 0.f));
        geoPtr->setColors(colorsPtr);

        GeoIndicesUI32Ptr indicesPtr = GeoIndicesUI32::create();
        geoPtr->setIndices(indicesPtr);

        UInt32 i, numGlyphs = layoutResult.getNumGlyphs();
        for (i = 0; i < numGlyphs; ++i)
        {
            const TextGlyph &glyph = face->getGlyph(layoutResult.indices[i]);
            typesPtr->push_back(GL_LINE_LOOP);
            lensPtr->push_back(4);
            const Vec2f &pos = layoutResult.positions[i];
            Real32 left = pos.x() * scale;
            Real32 right = (pos.x() + glyph.getWidth()) * scale;
            Real32 top = pos.y() * scale;
            Real32 bottom = (pos.y() - glyph.getHeight()) * scale;
            UInt32 posOffset = posPtr->size();
            posPtr->push_back(Vec3f(left, bottom, 0.f));
            posPtr->push_back(Vec3f(right, bottom, 0.f));
            posPtr->push_back(Vec3f(right, top, 0.f));
            posPtr->push_back(Vec3f(left, top, 0.f));
            indicesPtr->push_back(posOffset);
            indicesPtr->push_back(0);
            indicesPtr->push_back(posOffset + 1);
            indicesPtr->push_back(0);
            indicesPtr->push_back(posOffset + 2);
            indicesPtr->push_back(0);
            indicesPtr->push_back(posOffset + 3);
            indicesPtr->push_back(0);
        }

        // Bounding box
        Vec2f lowerLeft, upperRight;
        face->calculateBoundingBox(layoutResult, lowerLeft, upperRight);
        typesPtr->push_back(GL_LINE_LOOP);
        lensPtr->push_back(4);
        Real32 left = lowerLeft.x() * scale;
        Real32 right = upperRight.x() * scale;
        Real32 top = upperRight.y() * scale;
        Real32 bottom = lowerLeft.y() * scale;
        UInt32 posOffset = posPtr->size();
        posPtr->push_back(Vec3f(left, bottom, 0.f));
        posPtr->push_back(Vec3f(right, bottom, 0.f));
        posPtr->push_back(Vec3f(right, top, 0.f));
        posPtr->push_back(Vec3f(left, top, 0.f));
        indicesPtr->push_back(posOffset);
        indicesPtr->push_back(1);
        indicesPtr->push_back(posOffset + 1);
        indicesPtr->push_back(1);
        indicesPtr->push_back(posOffset + 2);
        indicesPtr->push_back(1);
        indicesPtr->push_back(posOffset + 3);
        indicesPtr->push_back(1);

        // Text bounds & Line bounds
        Vec2f pos, textPos, offset;
        if (layoutParam.horizontal == true)
        {
            Real32 lineHeight = face->getHoriAscent() - face->getHoriDescent();
            Real32 spacing = layoutParam.spacing * lineHeight;
            if (layoutParam.topToBottom == true)
            {
                switch (layoutParam.minorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                        break;
                    case TextLayoutParam::ALIGN_FIRST:
                        pos[1] = textPos[1] = face->getHoriAscent();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        pos[1] = textPos[1] = (spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        pos[1] = textPos[1] = spacing * (layoutResult.lineBounds.size() - 1) + lineHeight;
                        break;
                }
                offset.setValues(0.f, -spacing);
            }
            else
            {
                switch (layoutParam.minorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                        pos[1] = lineHeight;
                        textPos[1] = spacing * (layoutResult.lineBounds.size() - 1) + lineHeight;
                        break;
                    case TextLayoutParam::ALIGN_FIRST:
                        pos[1] = face->getHoriAscent();
                        textPos[1] = spacing * (layoutResult.lineBounds.size() - 1) + face->getHoriAscent();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        pos[1] = -(spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f + lineHeight;
                        textPos[1] = (spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        pos[1] = -spacing * (layoutResult.lineBounds.size() - 1);
                        break;
                }
                offset.setValues(0.f, spacing);
            }
        }
        else
        {
            Real32 lineHeight = face->getVertDescent() - face->getVertAscent();
            Real32 spacing = layoutParam.spacing * lineHeight;
            if (layoutParam.leftToRight == true)
            {
                switch (layoutParam.minorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                        break;
                    case TextLayoutParam::ALIGN_FIRST:
                        pos[0] = textPos[0] = face->getVertAscent();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        pos[0] = textPos[0] = -(spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        pos[0] = textPos[0] = -spacing * (layoutResult.lineBounds.size() - 1) - lineHeight;
                        break;
                }
                offset.setValues(spacing, 0.f);
            }
            else
            {
                switch (layoutParam.minorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                        pos[0] = -lineHeight;
                        textPos[0] = -spacing * (layoutResult.lineBounds.size() - 1) - lineHeight;
                        break;
                    case TextLayoutParam::ALIGN_FIRST:
                        pos[0] = -face->getVertDescent();
                        textPos[0] = -spacing * (layoutResult.lineBounds.size() - 1) -face->getVertDescent();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        pos[0] = (spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f - lineHeight;
                        textPos[0] = -(spacing * (layoutResult.lineBounds.size() - 1) + lineHeight) / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        pos[0] = spacing * (layoutResult.lineBounds.size() - 1);
                        break;
                }
                offset.setValues(-spacing, 0.f);
            }
        }

        typesPtr->push_back(GL_LINE_LOOP);
        lensPtr->push_back(4);
        left = textPos.x();
        top = textPos.y();
        if (layoutParam.horizontal == true)
            if (layoutParam.leftToRight == true)
                switch (layoutParam.majorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                    case TextLayoutParam::ALIGN_FIRST:
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        left -= layoutResult.textBounds.x() / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        left -= layoutResult.textBounds.x();
                        break;
                }
            else
                switch (layoutParam.majorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                    case TextLayoutParam::ALIGN_FIRST:
                        left -= layoutResult.textBounds.x();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        left -= layoutResult.textBounds.x() / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        break;
                }
        else
            if (layoutParam.topToBottom == true)
                switch (layoutParam.majorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                    case TextLayoutParam::ALIGN_FIRST:
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        top += layoutResult.textBounds.y() / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        top += layoutResult.textBounds.y();
                        break;
                }
            else
                switch (layoutParam.majorAlignment)
                {
                    case TextLayoutParam::ALIGN_BEGIN:
                    case TextLayoutParam::ALIGN_FIRST:
                        top += layoutResult.textBounds.y();
                        break;
                    case TextLayoutParam::ALIGN_MIDDLE:
                        top += layoutResult.textBounds.y() / 2.f;
                        break;
                    case TextLayoutParam::ALIGN_END:
                        break;
                }
        left *= scale;
        right = left + layoutResult.textBounds.x() * scale;
        top *= scale;
        bottom = top - layoutResult.textBounds.y() * scale;
        posOffset = posPtr->size();
        posPtr->push_back(Vec3f(left, bottom, 0.f));
        posPtr->push_back(Vec3f(right, bottom, 0.f));
        posPtr->push_back(Vec3f(right, top, 0.f));
        posPtr->push_back(Vec3f(left, top, 0.f));
        indicesPtr->push_back(posOffset);
        indicesPtr->push_back(3);
        indicesPtr->push_back(posOffset + 1);
        indicesPtr->push_back(3);
        indicesPtr->push_back(posOffset + 2);
        indicesPtr->push_back(3);
        indicesPtr->push_back(posOffset + 3);
        indicesPtr->push_back(3);

        vector<Vec2f>::const_iterator lbIt;
        for (lbIt = layoutResult.lineBounds.begin(); lbIt != layoutResult.lineBounds.end(); ++lbIt)
        {
            typesPtr->push_back(GL_LINE_LOOP);
            lensPtr->push_back(4);
            Real32 left = pos.x();
            Real32 top = pos.y();
            if (layoutParam.horizontal == true)
                if (layoutParam.leftToRight == true)
                    switch (layoutParam.majorAlignment)
                    {
                        case TextLayoutParam::ALIGN_BEGIN:
                        case TextLayoutParam::ALIGN_FIRST:
                            break;
                        case TextLayoutParam::ALIGN_MIDDLE:
                            left -= lbIt->x() / 2.f;
                            break;
                        case TextLayoutParam::ALIGN_END:
                            left -= lbIt->x();
                            break;
                    }
                else
                    switch (layoutParam.majorAlignment)
                    {
                        case TextLayoutParam::ALIGN_BEGIN:
                        case TextLayoutParam::ALIGN_FIRST:
                            left -= lbIt->x();
                            break;
                        case TextLayoutParam::ALIGN_MIDDLE:
                            left -= lbIt->x() / 2.f;
                            break;
                        case TextLayoutParam::ALIGN_END:
                            break;
                    }
            else
                if (layoutParam.topToBottom == true)
                    switch (layoutParam.majorAlignment)
                    {
                        case TextLayoutParam::ALIGN_BEGIN:
                        case TextLayoutParam::ALIGN_FIRST:
                            break;
                        case TextLayoutParam::ALIGN_MIDDLE:
                            top += lbIt->y() / 2.f;
                            break;
                        case TextLayoutParam::ALIGN_END:
                            top += lbIt->y();
                            break;
                    }
                else
                    switch (layoutParam.majorAlignment)
                    {
                        case TextLayoutParam::ALIGN_BEGIN:
                        case TextLayoutParam::ALIGN_FIRST:
                            top += lbIt->y();
                            break;
                        case TextLayoutParam::ALIGN_MIDDLE:
                            top += lbIt->y() / 2.f;
                            break;
                        case TextLayoutParam::ALIGN_END:
                            break;
                    }
            left *= scale;
            Real32 right = left + lbIt->x() * scale;
            top *= scale;
            Real32 bottom = top - lbIt->y() * scale;
            UInt32 posOffset = posPtr->size();
            posPtr->push_back(Vec3f(left, bottom, 0.f));
            posPtr->push_back(Vec3f(right, bottom, 0.f));
            posPtr->push_back(Vec3f(right, top, 0.f));
            posPtr->push_back(Vec3f(left, top, 0.f));
            indicesPtr->push_back(posOffset);
            indicesPtr->push_back(2);
            indicesPtr->push_back(posOffset + 1);
            indicesPtr->push_back(2);
            indicesPtr->push_back(posOffset + 2);
            indicesPtr->push_back(2);
            indicesPtr->push_back(posOffset + 3);
            indicesPtr->push_back(2);

            typesPtr->push_back(GL_LINE_STRIP);
            lensPtr->push_back(2);
            posOffset = posPtr->size();
            if (layoutParam.horizontal == true)
            {
                Real32 base = top - face->getHoriAscent() * scale;
                posPtr->push_back(Vec3f(left, base, 0.f));
                posPtr->push_back(Vec3f(right, base, 0.f));
            }
            else
            {
                Real32 base = left - face->getVertAscent() * scale;
                posPtr->push_back(Vec3f(base, top, 0.f));
                posPtr->push_back(Vec3f(base, bottom, 0.f));
            }
            indicesPtr->push_back(posOffset);
            indicesPtr->push_back(2);
            indicesPtr->push_back(posOffset + 1);
            indicesPtr->push_back(2);
            pos += offset;
        }

        geoPtr->editMFIndexMapping()->clear();
        geoPtr->editMFIndexMapping()->push_back(Geometry::MapPosition);
        geoPtr->editMFIndexMapping()->push_back(Geometry::MapColor);

        SimpleMaterialPtr matPtr = SimpleMaterial::create();
        geoPtr->setMaterial(matPtr);
    }
    endEditCP(geoPtr);

    NodePtr nodePtr = Node::create();
    beginEditCP(nodePtr, Node::CoreFieldMask);
    {
        nodePtr->setCore(geoPtr);
    }
    endEditCP(nodePtr, Node::CoreFieldMask);

    return nodePtr;
}
int main(int argc, char *argv[])
{
    osgLogP->setLogLevel(LOG_NOTICE);

    osgInit(argc, argv);

    int winid = setupGLUT(&argc, argv);

    // create a GLUT window
    GLUTWindowPtr gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    osgLogP->setLogLevel(LOG_DEBUG);

    // build the test scene
    NodePtr  pRoot      = Node ::create();
    GroupPtr pRootCore  = Group::create();
    NodePtr  pRayGeo    = Node ::create();
    NodePtr  pScene     = buildGraph();
    GroupPtr pSceneCore = Group::create();

    Time     tStart;
    Time     tStop;
    Time     tDFTotal  = 0.0;
    Time     tDFSTotal = 0.0;
    Time     tPTotal   = 0.0;
    Time     tOTotal   = 0.0;

    StatCollector statP;
    StatCollector statDF;
    StatCollector statDFS;

    beginEditCP(pRoot, Node::CoreFieldId | Node::ChildrenFieldId);
    pRoot->setCore (pRootCore   );
    pRoot->addChild(pScene      );
    pRoot->addChild(pRayGeo     );
    endEditCP  (pRoot, Node::CoreFieldId | Node::ChildrenFieldId);

    createRays(uiNumRays, testRays);

    // build the geometry to visualize the rays
    pPoints = GeoPositions3f::create();
    beginEditCP(pPoints);
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    endEditCP  (pPoints);

    GeoIndicesUI32Ptr pIndices = GeoIndicesUI32::create();
    beginEditCP(pIndices);
    pIndices->addValue(0);
    pIndices->addValue(1);
    pIndices->addValue(2);
    pIndices->addValue(3);
    pIndices->addValue(4);
    endEditCP  (pIndices);

    GeoPLengthsPtr pLengths = GeoPLengthsUI32::create();
    beginEditCP(pLengths);
    pLengths->addValue(2);
    pLengths->addValue(3);
    endEditCP  (pLengths);

    GeoPTypesPtr pTypes = GeoPTypesUI8::create();
    beginEditCP(pTypes);
    pTypes->addValue(GL_LINES    );
    pTypes->addValue(GL_TRIANGLES);
    endEditCP  (pTypes);

    GeoColors3fPtr pColors = GeoColors3f::create();
    beginEditCP(pColors);
    pColors->addValue(Color3f(1.0, 1.0, 1.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    endEditCP  (pColors);

    SimpleMaterialPtr pMaterial = SimpleMaterial::create();
    beginEditCP(pMaterial);
    pMaterial->setLit(false);
    endEditCP  (pMaterial);

    GeometryPtr pRayGeoCore = Geometry::create();
    beginEditCP(pRayGeoCore);
    pRayGeoCore->setPositions(pPoints  );
    pRayGeoCore->setIndices  (pIndices );
    pRayGeoCore->setLengths  (pLengths );
    pRayGeoCore->setTypes    (pTypes   );
    pRayGeoCore->setColors   (pColors  );
    pRayGeoCore->setMaterial (pMaterial);
    endEditCP  (pRayGeoCore);

    beginEditCP(pRayGeo, Node::CoreFieldId);
    pRayGeo->setCore(pRayGeoCore);
    endEditCP  (pRayGeo, Node::CoreFieldId);

    IntersectActor::regDefaultClassEnter(
        osgTypedFunctionFunctor2CPtr<
            NewActionTypes::ResultE,          NodeCorePtr,
            ActorBase::FunctorArgumentType &              >(enterDefault));


    NewActionBase  *pDFAction  = DepthFirstAction     ::create();
    NewActionBase  *pDFSAction = DepthFirstStateAction::create();
    NewActionBase  *pPAction   = PriorityAction       ::create();
    IntersectActor *pIActorDF  = IntersectActor       ::create();
    IntersectActor *pIActorDFS = IntersectActor       ::create();
    IntersectActor *pIActorP   = IntersectActor       ::create();

    pDFAction ->setStatistics(&statDF );
    pDFSAction->setStatistics(&statDFS);
    pPAction  ->setStatistics(&statP  );

    // IntersectActor with DFS-Action does not need leave calls
    pIActorDFS->setLeaveNodeFlag(false);

    pDFAction ->addActor(pIActorDF );
    pDFSAction->addActor(pIActorDFS);
    pPAction  ->addActor(pIActorP  );

    // create old action
    IntersectAction *pIntAction = IntersectAction ::create();

    // make sure bv are up to date
    pScene->updateVolume();


    SINFO << "-=< Intersect >=-" << endLog;

    std::vector<Line>::iterator itRays  = testRays.begin();
    std::vector<Line>::iterator endRays = testRays.end  ();

    for(; itRays != endRays; ++itRays)
    {
        // DepthFirst

        tStart = getSystemTime();

        pIActorDF->setRay        (*itRays);
        pIActorDF->setMaxDistance(10000.0);
        pIActorDF->reset         (       );

        pDFAction->apply(pScene);

        tStop            =  getSystemTime();
        tDFTotal += (tStop - tStart);

        if(pIActorDF->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorDF->getHitObject       ();
            result._tri  = pIActorDF->getHitTriangleIndex();
            result._dist = pIActorDF->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsDF.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsDF.push_back(result);
        }

        std::string strStatDF;
        statDF.putToString(strStatDF);

        //SINFO << "stat DF:  " << strStatDF << endLog;

        // Depth First State

        tStart = getSystemTime();

        pIActorDFS->setRay        (*itRays);
        pIActorDFS->setMaxDistance(10000.0);
        pIActorDFS->reset         (       );

        pDFSAction->apply(pScene);

        tStop     =  getSystemTime();
        tDFSTotal += (tStop - tStart);

        if(pIActorDFS->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorDFS->getHitObject       ();
            result._tri  = pIActorDFS->getHitTriangleIndex();
            result._dist = pIActorDFS->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsDFS.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsDFS.push_back(result);
        }

        std::string strStatDFS;
        statDFS.putToString(strStatDFS);

        //SINFO << "stat DFS: " << strStatDFS << endLog;

        // Priority

        tStart = getSystemTime();

        pIActorP->setRay        (*itRays);
        pIActorP->setMaxDistance(10000.0);
        pIActorP->reset         (       );

        pPAction->apply(pScene);

        tStop          =  getSystemTime();
        tPTotal += (tStop - tStart);

        if(pIActorP->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorP->getHitObject       ();
            result._tri  = pIActorP->getHitTriangleIndex();
            result._dist = pIActorP->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsP.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsP.push_back(result);
        }

        std::string strStatP;
        statP.putToString(strStatP);

        //SINFO << "stat P:   " << strStatP << endLog;

        // Old

        tStart = getSystemTime();

        pIntAction->setLine(*itRays, 100000);
        pIntAction->apply  (pScene         );

        tStop     =  getSystemTime();
        tOTotal += (tStop - tStart);

        if(pIntAction->didHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIntAction->getHitObject  ();
            result._tri  = pIntAction->getHitTriangle();
            result._dist = pIntAction->getHitT       ();
            result._time = (tStop - tStart);

            resultsO.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsO.push_back(result);
        }
    }

    UInt32 DFwins      = 0;
    UInt32 DFwinsHit   = 0;
    UInt32 DFwinsMiss  = 0;

    UInt32 DFSwins     = 0;
    UInt32 DFSwinsHit  = 0;
    UInt32 DFSwinsMiss = 0;

    UInt32 Pwins       = 0;
    UInt32 PwinsHit    = 0;
    UInt32 PwinsMiss   = 0;

    UInt32 Owins       = 0;
    UInt32 OwinsHit    = 0;
    UInt32 OwinsMiss   = 0;

    UInt32 failCount   = 0;
    UInt32 passCount   = 0;
    UInt32 hitCount    = 0;
    UInt32 missCount   = 0;

    for(UInt32 i = 0; i < uiNumRays; ++i)
    {
        bool DFfastest  = ((resultsDF [i]._time <= resultsDFS[i]._time) &&
                           (resultsDF [i]._time <= resultsP  [i]._time) &&
                           (resultsDF [i]._time <= resultsO  [i]._time)   );
        bool DFSfastest = ((resultsDFS[i]._time <= resultsDF [i]._time) &&
                           (resultsDFS[i]._time <= resultsP  [i]._time) &&
                           (resultsDFS[i]._time <= resultsO  [i]._time)   );
        bool Pfastest   = ((resultsP  [i]._time <= resultsDF [i]._time) &&
                           (resultsP  [i]._time <= resultsDFS[i]._time) &&
                           (resultsP  [i]._time <= resultsO  [i]._time)   );
        bool Ofastest   = ((resultsO  [i]._time <= resultsDF [i]._time) &&
                           (resultsO  [i]._time <= resultsDFS[i]._time) &&
                           (resultsO  [i]._time <= resultsP  [i]._time)   );

        if((resultsDF [i]._hit == resultsDFS[i]._hit) &&
           (resultsDFS[i]._hit == resultsP  [i]._hit) &&
           (resultsP  [i]._hit == resultsO  [i]._hit)    )
        {
            if((osgabs(resultsDF [i]._dist - resultsDFS[i]._dist) >= 0.001) ||
               (osgabs(resultsDFS[i]._dist - resultsP  [i]._dist) >= 0.001) ||
               (osgabs(resultsP  [i]._dist - resultsO  [i]._dist) >= 0.001) ||
               (osgabs(resultsO  [i]._dist - resultsDF [i]._dist) >= 0.001)   )
            {
                ++failCount;

                SINFO << "FAIL: df: " << resultsDF [i]._dist
                      << " dfs: "     << resultsDFS[i]._dist
                      << " p: "       << resultsP  [i]._dist
                      << " o: "       << resultsO  [i]._dist
                      << endLog;
                SINFO << "FAIL: df: " << resultsDF [i]._tri
                      << " dfs: "     << resultsDFS[i]._tri
                      << " p: "       << resultsP  [i]._tri
                      << " o: "       << resultsO  [i]._tri
                      << endLog;
            }
            else
            {
                ++passCount;
            }

            if(resultsDF[i]._hit == true)
            {
                ++hitCount;

                DFwinsHit  = DFfastest  ? DFwinsHit  + 1 : DFwinsHit;
                DFSwinsHit = DFSfastest ? DFSwinsHit + 1 : DFSwinsHit;
                PwinsHit   = Pfastest   ? PwinsHit   + 1 : PwinsHit;
                OwinsHit   = Ofastest   ? OwinsHit   + 1 : OwinsHit;
            }
            else
            {
                ++missCount;

                DFwinsMiss  = DFfastest  ? DFwinsMiss  + 1 : DFwinsMiss;
                DFSwinsMiss = DFSfastest ? DFSwinsMiss + 1 : DFSwinsMiss;
                PwinsMiss   = Pfastest   ? PwinsMiss   + 1 : PwinsMiss;
                OwinsMiss   = Ofastest   ? OwinsMiss   + 1 : OwinsMiss;
            }

            DFwins  = DFfastest  ? DFwins  + 1 : DFwins;
            DFSwins = DFSfastest ? DFSwins + 1 : DFSwins;
            Pwins   = Pfastest   ? Pwins   + 1 : Pwins;
            Owins   = Ofastest   ? Owins   + 1 : Owins;
        }
        else
        {
            ++failCount;
        }

        //SINFO << i << " \t" << (DFfastest  ? "D ->" : "    ") << " hit: " << resultsDF [i]._hit << " time: " << resultsDF [i]._time << endLog;
        //SINFO << "  \t"     << (DFSfastest ? "S ->" : "    ") << " hit: " << resultsDFS[i]._hit << " time: " << resultsDFS[i]._time << endLog;
        //SINFO << "  \t"     << (Pfastest   ? "P ->" : "    ") << " hit: " << resultsP  [i]._hit << " time: " << resultsP  [i]._time << endLog;
        //SINFO << "  \t"     << (Ofastest   ? "O ->" : "    ") << " hit: " << resultsO  [i]._hit << " time: " << resultsO  [i]._time << endLog;
    }

    SINFO << " df total:  "    << tDFTotal   << (tDFTotal < tDFSTotal && tDFTotal < tPTotal && tDFTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << DFwins     << " (" << (static_cast<Real32>(DFwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << DFwinsHit  << " (" << (static_cast<Real32>(DFwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << DFwinsMiss << " (" << (static_cast<Real32>(DFwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " dfs total: "    << tDFSTotal  << (tDFSTotal < tDFTotal && tDFSTotal < tPTotal && tDFSTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << DFSwins     << " (" << (static_cast<Real32>(DFSwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << DFSwinsHit  << " (" << (static_cast<Real32>(DFSwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << DFSwinsMiss << " (" << (static_cast<Real32>(DFSwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " p total:   "    << tPTotal   << (tPTotal < tDFTotal && tPTotal < tDFSTotal && tPTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << Pwins     << " (" << (static_cast<Real32>(Pwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << PwinsHit  << " (" << (static_cast<Real32>(PwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << PwinsMiss << " (" << (static_cast<Real32>(PwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " o total:   "    << tOTotal   << (tOTotal < tDFTotal && tOTotal < tDFSTotal && tOTotal < tPTotal ? " *" : "  ") 
          << " wins: "         << Owins     << " (" << (static_cast<Real32>(Owins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << OwinsHit  << " (" << (static_cast<Real32>(OwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << OwinsMiss << " (" << (static_cast<Real32>(OwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << "pass: "******" fail: " << failCount
          << " hit: " << hitCount  << " miss: " << missCount << endLog;

    osgLogP->setLogLevel(LOG_NOTICE);

#if 0
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (pRoot);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();
#endif


    return 0;
}
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // create the scene
     
    /*
        In the previous example, the colors and positions used the same
        indices. That might not always be the preferred way, and it might not
        make sense for other properties, e.g. normals.
        
        It is possible to assign a different index for every property. See the
        indices section below for details.
    */
    
    /*
        The initial setup is the same as in the single indexed geometry...
    */
    GeoPTypesPtr type = GeoPTypesUI8::create();        
    beginEditCP(type, GeoPTypesUI8::GeoPropDataFieldMask);
    {
        type->push_back(GL_POLYGON  );
        type->push_back(GL_TRIANGLES);
        type->push_back(GL_QUADS    );
    }
    endEditCP  (type, GeoPTypesUI8::GeoPropDataFieldMask);

    GeoPLengthsPtr lens = GeoPLengthsUI32::create();    
    beginEditCP(lens, GeoPLengthsUI32::GeoPropDataFieldMask);
    {
        lens->push_back(4);
        lens->push_back(6);
        lens->push_back(8);
    }
    endEditCP  (lens, GeoPLengthsUI32::GeoPropDataFieldMask);
       
    GeoPositions3fPtr pnts = GeoPositions3f::create();
    beginEditCP(pnts, GeoPositions3f::GeoPropDataFieldMask);
    {
        // the base
        pnts->push_back(Pnt3f(-1, -1, -1));
        pnts->push_back(Pnt3f(-1, -1,  1));
        pnts->push_back(Pnt3f( 1, -1,  1));
        pnts->push_back(Pnt3f( 1, -1, -1));

        // the roof base
        pnts->push_back(Pnt3f(-1,  0, -1));
        pnts->push_back(Pnt3f(-1,  0,  1));
        pnts->push_back(Pnt3f( 1,  0,  1));
        pnts->push_back(Pnt3f( 1,  0, -1));

        // the gable
        pnts->push_back(Pnt3f( 0,  1, -1));
        pnts->push_back(Pnt3f( 0,  1,  1));
    }
    endEditCP  (pnts, GeoPositions3f::GeoPropDataFieldMask);
   
    GeoColors3fPtr colors = GeoColors3f::create();
    beginEditCP(colors, GeoColors3f::GeoPropDataFieldMask);
    {
        colors->push_back(Color3f(1, 1, 0));
        colors->push_back(Color3f(1, 0, 0));
        colors->push_back(Color3f(1, 0, 0));
        colors->push_back(Color3f(1, 1, 0));
        colors->push_back(Color3f(0, 1, 1));
        colors->push_back(Color3f(1, 0, 1));
    }
    endEditCP  (colors, GeoPositions3f::GeoPropDataFieldMask);

    /*
        A new property: normals.
        
        They are used for lighting calculations and have to point away from the
        surface. Normals are standard vectors.
    */
    GeoNormals3fPtr norms = GeoNormals3f::create();
    beginEditCP(norms, GeoNormals3f::GeoPropDataFieldMask);
    {
        norms->push_back(Vec3f(-1,  0,  0));
        norms->push_back(Vec3f( 1,  0,  0));
        norms->push_back(Vec3f( 0, -1,  0));
        norms->push_back(Vec3f( 0,  1,  0));
        norms->push_back(Vec3f( 0,  0, -1));
        norms->push_back(Vec3f( 0,  0,  1));
    }
    endEditCP  (norms, GeoNormals3f::GeoPropDataFieldMask);
    
  
    /*
        To use different indices for different attributes they have to be
        specified. This is done within the single index property, by using more
        than one index per vertex.
        
        In this case every vertex reads multiple indices from the Indices
        property. The meaning of every index is defined by the indexMapping
        given below.
    */
    GeoIndicesUI32Ptr indices = GeoIndicesUI32::create();
    beginEditCP(indices, GeoIndicesUI32::GeoPropDataFieldMask);
    {
        // indices for the polygon
        indices->push_back(0);   // position index
        indices->push_back(3);   // color/normal index
        indices->push_back(1);   // position index
        indices->push_back(3);   // color/normal index
        indices->push_back(2);   // position index
        indices->push_back(3);   // color/normal index
        indices->push_back(3);   // position index
        indices->push_back(3);   // color/normal index
       
        // indices for the triangles
        indices->push_back(7);   // position index
        indices->push_back(4);   // color/normal index
        indices->push_back(4);   // position index
        indices->push_back(4);   // color/normal index
        indices->push_back(8);   // position index
        indices->push_back(4);   // color/normal index

        indices->push_back(5);   // position index
        indices->push_back(5);   // color/normal index
        indices->push_back(6);   // position index
        indices->push_back(5);   // color/normal index
        indices->push_back(9);   // position index
        indices->push_back(5);   // color/normal index
        
        // indices for the quads
        indices->push_back(1);   // position index
        indices->push_back(5);   // color/normal index
        indices->push_back(2);   // position index
        indices->push_back(5);   // color/normal index
        indices->push_back(6);   // position index
        indices->push_back(5);   // color/normal index
        indices->push_back(5);   // position index
        indices->push_back(5);   // color/normal index

        indices->push_back(3);   // position index
        indices->push_back(4);   // color/normal index
        indices->push_back(0);   // position index
        indices->push_back(4);   // color/normal index
        indices->push_back(4);   // position index
        indices->push_back(4);   // color/normal index
        indices->push_back(7);   // position index
        indices->push_back(4);   // color/normal index
    }
    endEditCP  (indices, GeoIndicesUI32::GeoPropDataFieldMask);
    
    /*
       Put it all together into a Geometry NodeCore.
    */
    GeometryPtr geo=Geometry::create();
    beginEditCP(geo, Geometry::TypesFieldMask          |
                     Geometry::LengthsFieldMask        |
                     Geometry::IndicesFieldMask        |
                     Geometry::IndexMappingFieldMask   |
                     Geometry::PositionsFieldMask      |
                     Geometry::NormalsFieldMask        |
                     Geometry::ColorsFieldMask         |
                     Geometry::MaterialFieldMask       );
    {
        geo->setTypes    (type);
        geo->setLengths  (lens);
        geo->setIndices  (indices);
        
        /*
             The meaning of the different indices is given by the indexMapping
             field. 

             If contains an entry that defines which index for a vertex
             selects which attribute. In this example the first index selects
             the positions, the second is used for colors and normals.

             The number of elements in the indexMapping field defines the
             number of indices used for every vertex.
        */
        geo->editMFIndexMapping()->push_back(Geometry::MapPosition   );
        geo->editMFIndexMapping()->push_back(Geometry::MapColor    |
                                             Geometry::MapNormal     );
         
        geo->setPositions(pnts  );
        geo->setColors   (colors);
        geo->setNormals  (norms );
        
        /*
            Use a lit material this time, to show the effect of the normals.
        */
        geo->setMaterial (getDefaultMaterial());   
    }
    endEditCP  (geo, Geometry::TypesFieldMask          |
                     Geometry::LengthsFieldMask        |
                     Geometry::IndicesFieldMask        |
                     Geometry::IndexMappingFieldMask   |
                     Geometry::PositionsFieldMask      |
                     Geometry::NormalsFieldMask        |
                     Geometry::ColorsFieldMask         |
                     Geometry::MaterialFieldMask       );
    
    // put the geometry core into a node
    NodePtr n = Node::create();
    beginEditCP(n, Node::CoreFieldMask);
    {
        n->setCore(geo);
    }
    endEditCP  (n, Node::CoreFieldMask);
    
    // add a transformation to make it move     
    NodePtr scene = Node::create();  
    trans = Transform::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask  );
    {
        scene->setCore(trans);
        scene->addChild(n);
    }
    endEditCP  (scene, Node::CoreFieldMask | Node::ChildrenFieldMask  );
 

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
Beispiel #9
0
NodePtr Puck::init()
{
	// CREATE THE PUCK
    NodePtr puck_trans_node = makeCoredNode<Transform>(&transPtr);
    beginEditCP(transPtr);
	{
		transPtr->getMatrix().setTranslate(position[0],position[1],position[2]);
	}
    endEditCP(transPtr);


    NodePtr puck = OSG::makeCylinder(PUCK_HALF_HEIGHT*2.0,radius, 32, true, true ,true);
    beginEditCP(puck_trans_node);
	{
		puck_trans_node->addChild(puck);
	}
    endEditCP(puck_trans_node);

    SimpleMaterialPtr puck_mat = SimpleMaterial::create();
    beginEditCP(puck_mat);
	{
		puck_mat->setAmbient(Color3f(0.0,0.0,0.0));
		puck_mat->setDiffuse(Color3f(1.0,0.0,0.0));
	}
    endEditCP(puck_mat);

    GeometryPtr puck_geo = GeometryPtr::dcast(puck->getCore());
    beginEditCP(puck_geo);
		puck_geo->setMaterial(puck_mat);
    beginEditCP(puck_geo);

	/////////////////////////////
	// SETUP THE INTERSECTION TEST COMPONENTS
	// Create a small geometry to show the ray and what was hit
    // Contains a line and a single triangle.
    // The line shows the ray, the triangle whatever was hit.
	isectPoints = GeoPositions3f::create();
    beginEditCP(isectPoints);
    {
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
    }
    endEditCP(isectPoints);
	GeoIndicesUI32Ptr index = GeoIndicesUI32::create();     
    beginEditCP(index);
    {
        index->addValue(0);
        index->addValue(1);
        index->addValue(2);
        index->addValue(3);
        index->addValue(4);
    }
    endEditCP(index);

    GeoPLengthsUI32Ptr lens = GeoPLengthsUI32::create();    
    beginEditCP(lens);
    {
        lens->addValue(2);
        lens->addValue(3);
    }
    endEditCP(lens);
    
    GeoPTypesUI8Ptr type = GeoPTypesUI8::create();  
    beginEditCP(type);
    {
        type->addValue(GL_LINES);
        type->addValue(GL_TRIANGLES);
    }
    endEditCP(type);
    
    SimpleMaterialPtr red = SimpleMaterial::create();
    
    beginEditCP(red);
    {
        red->setDiffuse     (Color3f( 1,0,0 ));   
        red->setTransparency(0.5);   
        red->setLit         (false);   
    }
    endEditCP  (red);

    testgeocore = Geometry::create();
    beginEditCP(testgeocore);
    {
        testgeocore->setPositions(isectPoints);
        testgeocore->setIndices(index);
        testgeocore->setLengths(lens);
        testgeocore->setTypes(type);
        testgeocore->setMaterial(red);
    }
    endEditCP(testgeocore);   

	NodePtr testgeo = Node::create();
    beginEditCP(testgeo);
    {
        testgeo->setCore(testgeocore);
    }
    endEditCP(testgeo);
    
	beginEditCP(puck_trans_node);
	{
		puck_trans_node->addChild(testgeo);
	}


	return puck_trans_node;
}
int main (int argc, char **argv)
{
    osgInit(argc, argv);

    FieldContainerPtr pProto = Geometry::getClassType().getPrototype();

    GeometryPtr pGeoProto = GeometryPtr::dcast(pProto);

    if(pGeoProto != NullFC)
    {
        pGeoProto->setDlistCache(false);
    }

    // init GLUT
    
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    // glutReshapeFunc(resize);
    glutDisplayFunc(display);       
    // glutMouseFunc(mouse);   
    // glutMotionFunc(motion); 
    
    glutIdleFunc(display);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60, 1, 0.1, 10 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( 3, 3, 3,  0, 0, 0,   0, 0, 1 );
    
    glDepthFunc( GL_LEQUAL );
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glLineWidth( 3 );

#if 0   
    // for testing only: register Node type functions

    IntersectAction::registerEnterDefault(Group::getStaticType(), 
                               osgFunctionFunctor2(groupEnter));
    IntersectAction::registerEnterDefault(Geometry::getStaticType(), 
                               osgFunctionFunctor2(geometryEnter));
    IntersectAction::registerEnterDefault(Transform::getStaticType(), 
                               osgFunctionFunctor2(transformEnter));
    IntersectAction::registerLeaveDefault(Transform::getStaticType(), 
                               osgFunctionFunctor2(transformLeave));
#endif
    
    // create test scene
  
    SimpleMaterialPtr white = SimpleMaterial::create();
    SimpleMaterialPtr red = SimpleMaterial::create();
    
    white->setEmission( Color3f( 1,1,1 ) );
    red->setEmission( Color3f( 1,0,0 ) );
    
    //  g1->(g2->g3->p1,t1->p2)
    GeometryPtr g;
    NodePtr  p1 = makePlane( 2,2,2,2 );
    g = GeometryPtr::dcast(p1->getCore());
    g->setMaterial( white );
    p1->updateVolume();
    NodePtr  p2 = makePlane( 2,2,2,2 );
    g = GeometryPtr::dcast(p2->getCore());
    g->setMaterial( white );
    p2->updateVolume();
    
    NodePtr g4 = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1);
    t1->editMatrix().setRotate( Quaternion( Vec3f(1,0,0), 30 ) );
    endEditCP(t1);
    beginEditCP(g4);
    g4->setCore( t1 );
    g4->addChild( p2 );
    g4->updateVolume();
    endEditCP(g4);

    NodePtr g3 = Node::create();
    GroupPtr g3c = Group::create();
    beginEditCP(g3);
    g3->setCore( g3c );
    g3->addChild( p1 );
    g3->updateVolume();
    endEditCP(g3);
    
    NodePtr g2 = Node::create();
    GroupPtr g2c = Group::create();
    beginEditCP(g2);
    g2->setCore( g2c );
    g2->addChild( g3 );
    g2->updateVolume();
    endEditCP(g2);

    iroot = Node::create();
    GroupPtr g1c = Group::create();
    beginEditCP(iroot);
    iroot->setCore( g1c );
    iroot->addChild( g2 );
    iroot->addChild( g4 );
    iroot->updateVolume();
    endEditCP(iroot);

   
    // make the root and test objects

    points = GeoPositions3f::create();
    beginEditCP(points);
    points->addValue( Pnt3f(0,0,0) );
    points->addValue( Pnt3f(0,0,0) );
    points->addValue( Pnt3f(0,0,0) );
    points->addValue( Pnt3f(0,0,0) );
    points->addValue( Pnt3f(0,0,0) );
    endEditCP(points);

    GeoIndicesUI32Ptr index = GeoIndicesUI32::create();     
    beginEditCP(index);
    index->addValue( 0 );
    index->addValue( 1 );
    index->addValue( 2 );
    index->addValue( 3 );
    index->addValue( 4 );
    endEditCP(index);

    GeoPLengthsPtr lens = GeoPLengthsUI32::create();    
    beginEditCP(lens);
    lens->addValue( 2 );
    lens->addValue( 3 );
    endEditCP(lens);
    
    GeoPTypesPtr type = GeoPTypesUI8::create();     
    beginEditCP(type);
    type->addValue( GL_LINES );
    type->addValue( GL_TRIANGLES );
    endEditCP(type);

    GeometryPtr testgeocore = Geometry::create();
    beginEditCP(testgeocore);
    testgeocore->setPositions( points );
    testgeocore->setIndices( index );
    testgeocore->setLengths( lens );
    testgeocore->setTypes( type );
    testgeocore->setMaterial( red );
    endEditCP( testgeocore );
    
    
    NodePtr testgeo = Node::create();
    beginEditCP(testgeo);
    testgeo->setCore( testgeocore );
    endEditCP( testgeo );
    
    
    root = Node::create();
    GroupPtr rootc = Group::create();
    beginEditCP(root);
    root->setCore( rootc );
    root->addChild( iroot );
    root->addChild( testgeo );
    endEditCP( root );


    dact = DrawAction::create();

    dact->setFrustumCulling(false);

    glutMainLoop();
    
    return 0;
}
Beispiel #11
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // The scene group
    
    NodePtr  scene = Node::create();
    GroupPtr g     = Group::create();
    
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
    scene->setCore(g);
    
    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
        FWARNING(("Supported file formats:\n"));
        
        std::list<const char*> suffixes;
        SceneFileHandler::the().getSuffixList(suffixes);
        
        for(std::list<const char*>::iterator it  = suffixes.begin();
                                             it != suffixes.end();
                                           ++it)
        {
            FWARNING(("%s\n", *it));
        }

        fileroot = makeTorus(.5, 2, 16, 16);
    }
    else
    {
        /*
            All scene file loading is handled via the SceneFileHandler.
        */
        fileroot = SceneFileHandler::the().read(argv[1]);
    }

    scene->addChild(fileroot);
    
    // Create a small geometry to show the ray and what was hit
    // Contains a line and a single triangle.
    // The line shows the ray, the triangle whatever was hit.
    
    SimpleMaterialPtr red = SimpleMaterial::create();
    
    beginEditCP(red);
    {
        red->setDiffuse     (Color3f( 1,0,0 ));   
        red->setTransparency(0.5);   
        red->setLit         (false);   
    }
    endEditCP  (red);

    isectPoints = GeoPositions3f::create();
    beginEditCP(isectPoints);
    {
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
    }
    endEditCP(isectPoints);

    GeoIndicesUI32Ptr index = GeoIndicesUI32::create();     
    beginEditCP(index);
    {
        index->addValue(0);
        index->addValue(1);
        index->addValue(2);
        index->addValue(3);
        index->addValue(4);
        index->addValue(5);
        index->addValue(6);
    }
    endEditCP(index);

    GeoPLengthsUI32Ptr lens = GeoPLengthsUI32::create();    
    beginEditCP(lens);
    {
        lens->addValue(4);
        lens->addValue(3);
    }
    endEditCP(lens);
    
    GeoPTypesUI8Ptr type = GeoPTypesUI8::create();  
    beginEditCP(type);
    {
        type->addValue(GL_LINES);
        type->addValue(GL_TRIANGLES);
    }
    endEditCP(type);

    testgeocore = Geometry::create();
    beginEditCP(testgeocore);
    {
        testgeocore->setPositions(isectPoints);
        testgeocore->setIndices(index);
        testgeocore->setLengths(lens);
        testgeocore->setTypes(type);
        testgeocore->setMaterial(red);
    }
    endEditCP(testgeocore);   
    
    NodePtr testgeo = Node::create();
    beginEditCP(testgeo);
    {
        testgeo->setCore(testgeocore);
    }
    endEditCP(testgeo);
    
    scene->addChild(testgeo);
    endEditCP(scene);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();

    mgr->getCamera()->setNear(mgr->getCamera()->getNear() / 10);

    // Show the bounding volumes? Not for now
    mgr->getAction()->setVolumeDrawing(false);
    
    // GLUT main loop
    glutMainLoop();

    return 0;

    // GLUT main loop
    glutMainLoop();

    return 0;
}