NodePtr makeTransformedCube (Real32 xsize,
			     Real32 ysize,
			     Real32 zsize,
			     UInt16 hor,
			     UInt16 vert,
			     UInt16 depth,
			     const Color3f& c)
{
   GeoColors3fPtr color = GeoColors3f::create();
   beginEditCP(color);
   color->addValue(c);
   endEditCP(color);
   GeometryPtr box = makeBoxGeo(xsize, ysize, zsize, hor, vert, depth);
   beginEditCP(box);
   box->setColors(color);
   endEditCP(box);
   NodePtr boxNode = Node::create();
   beginEditCP(boxNode);
   boxNode->setCore(box);
   endEditCP(boxNode);
   NodePtr node = Node::create();
   beginEditCP(node);
   node->setCore(Transform::create());
   node->addChild(boxNode);
   endEditCP(node);
   return node;
}
Exemplo n.º 2
0
Action::ResultE changeGeo(NodePtr& node)
{   
    GeometryPtr geo = GeometryPtr::dcast(node->getCore());
    
    if(geo == NullFC)
        return Action::Continue;


    GeoColors3fPtr colors = GeoColors3fPtr::dcast(geo->getColors());
    if(colors == NullFC)
    {
        colors = GeoColors3f::create();

        colors->resize(geo->getPositions()->getSize());
        
        // Change the geometry to use the new colors
        beginEditCP(geo, Geometry::ColorsFieldMask);
            geo->setColors(colors);
            // If multi-indexed, make the colors use the same index as
            // the geometry
            if(geo->getMFIndexMapping()->size() > 0)
            {
                Int16 pind = geo->calcMappingIndex(Geometry::MapPosition);
                
                if(pind < 0)
                {
                    FFATAL(("Multi-indexed, but no positions index???\n"));
                    return Action::Continue; 
                }
                
                // This makes the colors use the same indices as the positions
                geo->editIndexMapping(pind) |= Geometry::MapColor;
            }
        endEditCP  (geo, Geometry::ColorsFieldMask);
    }
    

    beginEditCP(geo, Geometry::ColorsFieldMask);
    beginEditCP(colors);
    Real32 size = colors->getSize();
    for(UInt32 i=0;i<size;++i)
    {
        Color3f c;
        c[0] = ((Real32) i) / size;
        c[1] = 0.0f;
        c[2] = 0.0f;
        colors->setValue(c, i);
    }
    endEditCP(colors);
    endEditCP(geo, Geometry::ColorsFieldMask);
    
    return Action::Continue; 
}
Exemplo n.º 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();
    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;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

    TutorialWindowEventProducer->setDisplayCallback(display);
    TutorialWindowEventProducer->setReshapeCallback(reshape);

	TutorialUpdateListener TheTutorialUpdateListener;
    TutorialWindowEventProducer->addUpdateListener(&TheTutorialUpdateListener);

    //Add Window Listener
    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindowEventProducer->addMouseListener(&TheTutorialMouseListener);
    TutorialWindowEventProducer->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(MainWindow);
	

	//Print key command info
	std::cout << "\n\nKEY COMMANDS:" << std::endl;
	std::cout << "space   Play/Pause the animation" << std::endl;
	std::cout << "G       Show/Hide the grid" << std::endl;
	std::cout << "A       Show/Hide the axes" << std::endl;
	std::cout << "B       Show/Hide the bind pose skeleton" << std::endl;
	std::cout << "SHIFT-B Show/Hide the bind pose mesh" << std::endl;
	std::cout << "P       Show/Hide the current pose skeleton" << std::endl;
	std::cout << "SHIFT-P Show/Hide the current pose mesh" << std::endl;
	std::cout << "CTRL-Q  Exit\n\n" << std::endl;




	//Setup axes
	LineChunkPtr AxesLineChunk = LineChunk::create();
	beginEditCP(AxesLineChunk);
		AxesLineChunk->setWidth(0.0f);
		AxesLineChunk->setSmooth(true);
	endEditCP(AxesLineChunk);

	//Axes material
	ChunkMaterialPtr AxesMaterial = ChunkMaterial::create();
	beginEditCP(AxesMaterial, ChunkMaterial::ChunksFieldMask);
		AxesMaterial->addChunk(AxesLineChunk);
	endEditCP(AxesMaterial, ChunkMaterial::ChunksFieldMask);

	//Grid material
	ChunkMaterialPtr gridMaterial = ChunkMaterial::create();
	beginEditCP(gridMaterial, ChunkMaterial::ChunksFieldMask);
		gridMaterial->addChunk(AxesLineChunk);
	endEditCP(gridMaterial, ChunkMaterial::ChunksFieldMask);

	//Axes should render as lines
	GeoPTypesPtr axesType = GeoPTypesUI8::create();        
    beginEditCP(axesType, GeoPTypesUI8::GeoPropDataFieldMask);
    {
        axesType->addValue(GL_LINES);
    }
    endEditCP  (axesType, GeoPTypesUI8::GeoPropDataFieldMask);

	//Grid type
	GeoPTypesPtr gridType = GeoPTypesUI8::create();        
    beginEditCP(gridType, GeoPTypesUI8::GeoPropDataFieldMask);
    {
        gridType->addValue(GL_LINES);
    }
    endEditCP  (gridType, GeoPTypesUI8::GeoPropDataFieldMask);

	//Axes lens
	GeoPLengthsPtr axesLens = GeoPLengthsUI32::create();    
    beginEditCP(axesLens, GeoPLengthsUI32::GeoPropDataFieldMask);
    {
        axesLens->addValue(6);
    }
    endEditCP  (axesLens, GeoPLengthsUI32::GeoPropDataFieldMask);

	//Grid lens
	GeoPLengthsPtr gridLens = GeoPLengthsUI32::create();    
    beginEditCP(gridLens, GeoPLengthsUI32::GeoPropDataFieldMask);
    {
        gridLens->addValue(84);
    }
    endEditCP  (gridLens, GeoPLengthsUI32::GeoPropDataFieldMask);
	
	//Axes points
	GeoPositions3fPtr axesPnts = GeoPositions3f::create();
    beginEditCP(axesPnts, GeoPositions3f::GeoPropDataFieldMask);
    {
		// X-Axis
        axesPnts->addValue(Pnt3f(0,  0,  0));
        axesPnts->addValue(Pnt3f(15,  0,  0));
        
		// Y-Axis
		axesPnts->addValue(Pnt3f(0,  0,  0));
        axesPnts->addValue(Pnt3f(0,  15,  0));

		// Z-Axis
        axesPnts->addValue(Pnt3f(0,  0, 0));
        axesPnts->addValue(Pnt3f(0,  0, 15));
    }
    endEditCP  (axesPnts, GeoPositions3f::GeoPropDataFieldMask);

	//Grid points
	GeoPositions3fPtr gridPnts = GeoPositions3f::create();
    beginEditCP(gridPnts, GeoPositions3f::GeoPropDataFieldMask);
    {
		float height = 0;

		gridPnts->addValue(Pnt3f(-10, height, 0));
		if(height == 0)
			gridPnts->addValue(Pnt3f(0, height, 0));
		else
			gridPnts->addValue(Pnt3f(10, height, 0));

		gridPnts->addValue(Pnt3f(-10, height, 1));
		gridPnts->addValue(Pnt3f(10, height, 1));

		gridPnts->addValue(Pnt3f(-10, height, 2));
		gridPnts->addValue(Pnt3f(10, height, 2));

		gridPnts->addValue(Pnt3f(-10, height, 3));
		gridPnts->addValue(Pnt3f(10, height, 3));

		gridPnts->addValue(Pnt3f(-10, height, 4));
		gridPnts->addValue(Pnt3f(10, height, 4));

		gridPnts->addValue(Pnt3f(-10, height, 5));
		gridPnts->addValue(Pnt3f(10, height, 5));

		gridPnts->addValue(Pnt3f(-10, height, 6));
		gridPnts->addValue(Pnt3f(10, height, 6));

		gridPnts->addValue(Pnt3f(-10, height, 7));
		gridPnts->addValue(Pnt3f(10, height, 7));

		gridPnts->addValue(Pnt3f(-10, height, 8));
		gridPnts->addValue(Pnt3f(10, height, 8));

		gridPnts->addValue(Pnt3f(-10, height, 9));
		gridPnts->addValue(Pnt3f(10, height, 9));

		gridPnts->addValue(Pnt3f(-10, height, 10));
		gridPnts->addValue(Pnt3f(10, height, 10));

		gridPnts->addValue(Pnt3f(-10, height, -1));
		gridPnts->addValue(Pnt3f(10, height, -1));

		gridPnts->addValue(Pnt3f(-10, height, -2));
		gridPnts->addValue(Pnt3f(10, height, -2));

		gridPnts->addValue(Pnt3f(-10, height, -3));
		gridPnts->addValue(Pnt3f(10, height, -3));

		gridPnts->addValue(Pnt3f(-10, height, -4));
		gridPnts->addValue(Pnt3f(10, height, -4));

		gridPnts->addValue(Pnt3f(-10, height, -5));
		gridPnts->addValue(Pnt3f(10, height, -5));

		gridPnts->addValue(Pnt3f(-10, height, -6));
		gridPnts->addValue(Pnt3f(10, height, -6));

		gridPnts->addValue(Pnt3f(-10, height, -7));
		gridPnts->addValue(Pnt3f(10, height, -7));

		gridPnts->addValue(Pnt3f(-10, height, -8));
		gridPnts->addValue(Pnt3f(10, height, -8));

		gridPnts->addValue(Pnt3f(-10, height, -9));
		gridPnts->addValue(Pnt3f(10, height, -9));

		gridPnts->addValue(Pnt3f(-10, height, -10));
		gridPnts->addValue(Pnt3f(10, height, -10));


		gridPnts->addValue(Pnt3f(0, height, -10));
		if(height == 0)
			gridPnts->addValue(Pnt3f(0, height, 0));
		else
			gridPnts->addValue(Pnt3f(0, height, 10));
		
		gridPnts->addValue(Pnt3f(1, height, -10));
		gridPnts->addValue(Pnt3f(1, height, 10));

		gridPnts->addValue(Pnt3f(2, height, -10));
		gridPnts->addValue(Pnt3f(2, height, 10));

		gridPnts->addValue(Pnt3f(3, height, -10));
		gridPnts->addValue(Pnt3f(3, height, 10));

		gridPnts->addValue(Pnt3f(4, height, -10));
		gridPnts->addValue(Pnt3f(4, height, 10));

		gridPnts->addValue(Pnt3f(5, height, -10));
		gridPnts->addValue(Pnt3f(5, height, 10));

		gridPnts->addValue(Pnt3f(6, height, -10));
		gridPnts->addValue(Pnt3f(6, height, 10));

		gridPnts->addValue(Pnt3f(7, height, -10));
		gridPnts->addValue(Pnt3f(7, height, 10));

		gridPnts->addValue(Pnt3f(8, height, -10));
		gridPnts->addValue(Pnt3f(8, height, 10));

		gridPnts->addValue(Pnt3f(9, height, -10));
		gridPnts->addValue(Pnt3f(9, height, 10));

		gridPnts->addValue(Pnt3f(10, height, -10));
		gridPnts->addValue(Pnt3f(10, height, 10));

		gridPnts->addValue(Pnt3f(-1, height, -10));
		gridPnts->addValue(Pnt3f(-1, height, 10));

		gridPnts->addValue(Pnt3f(-2, height, -10));
		gridPnts->addValue(Pnt3f(-2, height, 10));

		gridPnts->addValue(Pnt3f(-3, height, -10));
		gridPnts->addValue(Pnt3f(-3, height, 10));

		gridPnts->addValue(Pnt3f(-4, height, -10));
		gridPnts->addValue(Pnt3f(-4, height, 10));

		gridPnts->addValue(Pnt3f(-5, height, -10));
		gridPnts->addValue(Pnt3f(-5, height, 10));

		gridPnts->addValue(Pnt3f(-6, height, -10));
		gridPnts->addValue(Pnt3f(-6, height, 10));

		gridPnts->addValue(Pnt3f(-7, height, -10));
		gridPnts->addValue(Pnt3f(-7, height, 10));

		gridPnts->addValue(Pnt3f(-8, height, -10));
		gridPnts->addValue(Pnt3f(-8, height, 10));

		gridPnts->addValue(Pnt3f(-9, height, -10));
		gridPnts->addValue(Pnt3f(-9, height, 10));

		gridPnts->addValue(Pnt3f(-10, height, -10));
		gridPnts->addValue(Pnt3f(-10, height, 10));

		
    }
    endEditCP  (gridPnts, GeoPositions3f::GeoPropDataFieldMask);
    
    //Axes normals
	GeoNormals3fPtr axesNorms = GeoNormals3f::create();
    beginEditCP(axesNorms, GeoNormals3f::GeoPropDataFieldMask);
        axesNorms->addValue(Vec3f( 0.0,0.0,1.0));
        axesNorms->addValue(Vec3f( 0.0,0.0,1.0));
        
		axesNorms->addValue(Vec3f( 0.0,0.0,1.0));
        axesNorms->addValue(Vec3f( 0.0,0.0,1.0));

        axesNorms->addValue(Vec3f( 1.0,0.0,0.0));
        axesNorms->addValue(Vec3f( 1.0,0.0,0.0));
    endEditCP(axesNorms, GeoNormals3f::GeoPropDataFieldMask);

	//Grid normals
	GeoNormals3fPtr gridNorms = GeoNormals3f::create();
    beginEditCP(gridNorms, GeoNormals3f::GeoPropDataFieldMask);
		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));

		gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
        gridNorms->addValue(Vec3f( 0.0,0.0,1.0));
    endEditCP(gridNorms, GeoNormals3f::GeoPropDataFieldMask);

	//Axes colors
	GeoColors3fPtr axesColors = GeoColors3f::create();
    beginEditCP(axesColors, GeoColors3f::GeoPropDataFieldMask);
        //X-Axis = Red
	 	  axesColors->addValue(Color3f( 1.0,0.0,0.0));
        axesColors->addValue(Color3f( 1.0,0.0,0.0));
        
		  //Y-Axis = Green
		axesColors->addValue(Color3f( 0.0,1.0,0.0));
        axesColors->addValue(Color3f( 0.0,1.0,0.0));

		  //Z-Axis = Blue
        axesColors->addValue(Color3f( 0.0,0.0,1.0));
        axesColors->addValue(Color3f( 0.0,0.0,1.0));
    endEditCP(axesColors, GeoColors3f::GeoPropDataFieldMask);

	//Grid gridColors
	GeoColors3fPtr gridColors = GeoColors3f::create();
    beginEditCP(gridColors, GeoColors3f::GeoPropDataFieldMask);
		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));

		gridColors->addValue(Color3f( 0.5,0.5,0.5));
        gridColors->addValue(Color3f( 0.5,0.5,0.5));
    endEditCP(gridColors, GeoColors3f::GeoPropDataFieldMask);

	//Create axes geometry
	GeometryPtr axesGeo = Geometry::create();
    beginEditCP(axesGeo, Geometry::TypesFieldMask     |
                     Geometry::LengthsFieldMask   |
                     Geometry::PositionsFieldMask |
                     Geometry::NormalsFieldMask |
                     Geometry::MaterialFieldMask |
					 Geometry::ColorsFieldMask);
    {
        axesGeo->setTypes    (axesType);
        axesGeo->setLengths  (axesLens);
        axesGeo->setPositions(axesPnts);
        axesGeo->setNormals(axesNorms);
        axesGeo->setColors(axesColors);

        // assign a material to the geometry to make it visible. The details
        // of materials are defined later.
        axesGeo->setMaterial(AxesMaterial);   
    }
    endEditCP  (axesGeo, Geometry::TypesFieldMask     |
                     Geometry::LengthsFieldMask   |
                     Geometry::PositionsFieldMask |
                     Geometry::NormalsFieldMask |
                     Geometry::MaterialFieldMask |
					 Geometry::ColorsFieldMask  );

	//Create grid geometry
	GeometryPtr gridGeo = Geometry::create();
    beginEditCP(gridGeo, Geometry::TypesFieldMask     |
                     Geometry::LengthsFieldMask   |
                     Geometry::PositionsFieldMask |
                     Geometry::NormalsFieldMask |
                     Geometry::MaterialFieldMask |
					 Geometry::ColorsFieldMask);
    {
        gridGeo->setTypes    (gridType);
        gridGeo->setLengths  (gridLens);
        gridGeo->setPositions(gridPnts);
        gridGeo->setNormals(gridNorms);
        gridGeo->setColors(gridColors);

        // assign a material to the geometry to make it visible. The details
        // of materials are defined later.
        gridGeo->setMaterial(AxesMaterial);   
    }
    endEditCP  (gridGeo, Geometry::TypesFieldMask     |
                     Geometry::LengthsFieldMask   |
                     Geometry::PositionsFieldMask |
                     Geometry::NormalsFieldMask |
                     Geometry::MaterialFieldMask |
					 Geometry::ColorsFieldMask  );

	//Create unbound geometry Node
	Axes = osg::Node::create();
	beginEditCP(Axes, Node::CoreFieldMask);
		Axes->setCore(axesGeo);
	endEditCP(Axes, Node::CoreFieldMask);

	//Create unbound geometry Node
	Grid = osg::Node::create();
	beginEditCP(Grid, Node::CoreFieldMask);
		Grid->setCore(gridGeo);
	endEditCP(Grid, Node::CoreFieldMask);


	//Import scene from an XML file
	ChunkMaterialPtr ExampleMaterial;
	std::vector<SkeletonPtr> SkeletonPtrs;
	std::vector<SkeletonBlendedGeometryPtr> SkeletonBlendedGeometryPtrs;
	std::vector<GeometryPtr> GeometryPtrs;

	FCFileType::FCPtrStore NewContainers;
	NewContainers = FCFileHandler::the()->read(Path("./Data/21SceneFromMaya.xml"));
	FCFileType::FCPtrStore::iterator Itor;
    for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor)
    {
		if( (*Itor)->getType() == (ChunkMaterial::getClassType()))
		{
			//Set ExampleMaterial to the ChunkMaterial we just read in
			ExampleMaterial = (ChunkMaterial::Ptr::dcast(*Itor));
		}
		if( (*Itor)->getType() == (Skeleton::getClassType()))
		{
			//Add the skeleton we just read in to SkeletonPtrs
			SkeletonPtrs.push_back(Skeleton::Ptr::dcast(*Itor));
		}
		if( (*Itor)->getType() == (SkeletonBlendedGeometry::getClassType()))
		{
			//Add the SkeletonBlendedGeometry we just read in to SkeletonBlendedGeometryPtrs
			SkeletonBlendedGeometryPtrs.push_back(SkeletonBlendedGeometry::Ptr::dcast(*Itor));
		}
		if( (*Itor)->getType().isDerivedFrom(SkeletonAnimation::getClassType()))
		{
			//Set TheSkeletonAnimation to the Animation we just read in
			TheSkeletonAnimation = (Animation::Ptr::dcast(*Itor));
		}
		if( (*Itor)->getType() == (Geometry::getClassType()))
		{
			//Add the Geometry we just read in to GeometryPtrs
			GeometryPtrs.push_back(Geometry::Ptr::dcast(*Itor));
		}
    }
	
	//Create unbound geometry Node (to show the mesh in its bind pose)
	for (int i(0); i < GeometryPtrs.size(); ++i)
	{
		NodePtr UnboundGeometry = Node::create();
		beginEditCP(UnboundGeometry, Node::CoreFieldMask | Node::TravMaskFieldMask);
			UnboundGeometry->setCore(GeometryPtrs[i]);
			UnboundGeometry->setTravMask(0);
		endEditCP(UnboundGeometry, Node::CoreFieldMask | Node::TravMaskFieldMask);

		UnboundGeometries.push_back(UnboundGeometry);
	}


	//Create skeleton nodes
	for (int i(0); i < SkeletonPtrs.size(); ++i)
	{
		//SkeletonDrawer
		SkeletonDrawablePtr ExampleSkeletonDrawable = osg::SkeletonDrawable::create();
		beginEditCP(ExampleSkeletonDrawable, SkeletonDrawable::SkeletonFieldMask | SkeletonDrawable::MaterialFieldMask | SkeletonDrawable::DrawPoseFieldMask | SkeletonDrawable::PoseColorFieldMask  | SkeletonDrawable::DrawBindPoseFieldMask | SkeletonDrawable::BindPoseColorFieldMask);
			ExampleSkeletonDrawable->setSkeleton(SkeletonPtrs[i]);
			ExampleSkeletonDrawable->setMaterial(AxesMaterial);
			ExampleSkeletonDrawable->setDrawPose(true);								  //By default we draw the current skeleton
			ExampleSkeletonDrawable->setPoseColor(Color4f(1.0, 0.0, 1.0, 1.0));       //Set color of current skeleton
			ExampleSkeletonDrawable->setDrawBindPose(false);                          //By default we don't draw the bind pose skeleton
			ExampleSkeletonDrawable->setBindPoseColor(Color4f(1.0, 1.0, 0.0, 1.0));   //Set color of bind pose skeleton
		endEditCP(ExampleSkeletonDrawable, SkeletonDrawable::SkeletonFieldMask | SkeletonDrawable::MaterialFieldMask | SkeletonDrawable::DrawPoseFieldMask | SkeletonDrawable::PoseColorFieldMask  | SkeletonDrawable::DrawBindPoseFieldMask | SkeletonDrawable::BindPoseColorFieldMask);
		
		//Skeleton Node
		NodePtr SkeletonNode = osg::Node::create();
		beginEditCP(SkeletonNode, Node::CoreFieldMask);
			SkeletonNode->setCore(ExampleSkeletonDrawable);
		endEditCP(SkeletonNode, Node::CoreFieldMask);

		SkeletonNodes.push_back(SkeletonNode);
	}



	//Create skeleton blended geometry nodes
	for (int i(0); i < SkeletonBlendedGeometryPtrs.size(); ++i)
	{
		NodePtr MeshNode = osg::Node::create();
		beginEditCP(MeshNode, Node::CoreFieldMask);
			MeshNode->setCore(SkeletonBlendedGeometryPtrs[i]);
		endEditCP(MeshNode, Node::CoreFieldMask);

		MeshNodes.push_back(MeshNode);
	}



    //Create Animation Advancer
    TheAnimationAdvancer = osg::ElapsedTimeAnimationAdvancer::create();
    osg::beginEditCP(TheAnimationAdvancer);
    osg::ElapsedTimeAnimationAdvancer::Ptr::dcast(TheAnimationAdvancer)->setStartTime( 0.0 );
    osg::beginEditCP(TheAnimationAdvancer);


    //Add nodes to scene
    NodePtr scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
		scene->addChild(Axes);
		scene->addChild(Grid);

		//Add all imported skeletons to scene
		for (int i(0); i < SkeletonNodes.size(); ++i)
		{
			scene->addChild(SkeletonNodes[i]);
		}

		//Add all imported geometries to scene
		for (int i(0); i < UnboundGeometries.size(); ++i)
		{
			scene->addChild(UnboundGeometries[i]);
		}

		//Add all imported SkeletonBlendedGeometries to scene
		for (int i(0); i < MeshNodes.size(); ++i)
		{
			scene->addChild(MeshNodes[i]);
		}
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    mgr->setRoot(scene);


	//By default the animation is not paused
	animationPaused = false;

    // Show the whole Scene
    mgr->showAll();
    TheAnimationAdvancer->start();

	 //Show window
    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
                        WinSize,
                                        "21LoadXMLSceneFromMaya");

    //Enter main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}
Exemplo n.º 5
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;
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
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;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
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;
}
Exemplo n.º 10
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;
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
//    enableFPE();

#ifdef __sgi 	
	signal(SIGSEGV, (void (*)(int))sighand);
	signal(SIGTRAP, (void (*)(int))sighand);
	signal(SIGBUS, (void (*)(int))sighand);
#endif
   
    // OSG init
    osgInit(argc,argv);

    if (argc > 1 && ! strcmp(argv[1],"-bench"))
    {
        runBench = true;
        argc--;
        argv++;
        glutInitWindowPosition(0,0);
        glutInitWindowSize(600,600);
    }

    if (argc > 1 && ! strcmp(argv[1],"-test"))
    {
        testSet = true;
        doMotion = false;
        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
    NodePtr scene = Node::create();    
    NodePtr pnode = Node::create();
    
    ComponentTransformPtr trans = ComponentTransform::create();
    beginEditCP(scene);
    scene->setCore(trans);
    scene->addChild(pnode);
    endEditCP(scene);
    
    beginEditCP(trans);
    trans->setTranslation(Vec3f(2,0,0));
    trans->setRotation(Quaternion(Vec3f(0,1,0),Pi/2));
    trans->setScale(Vec3f(2,2,2));
    endEditCP(trans);
    
    
    particles = Particles::create();
    beginEditCP(pnode);
    pnode->setCore(particles);
    endEditCP(pnode);

    numParticles = 100;
    
    if (argc > 1)
    {
        numParticles=atoi(argv[1]);
    }
    
    beginEditCP(particles);

    pnts=GeoPositions3f::create();
    secpnts=GeoPositions3f::create();
    
    addRefCP(pnts);
    addRefCP(secpnts);
    
    GeoColors3fPtr  cols  = GeoColors3f::create();
    GeoNormals3fPtr norms = GeoNormals3f::create();

    MFPnt3f* p=pnts->editFieldPtr();
    MFPnt3f* sp=secpnts->editFieldPtr();
    MFVec3f *size=particles->editMFSizes();

    indices = particles->editMFIndices();
    
    velocities=new Vec3f [numParticles];
    
    beginEditCP(pnts);
    beginEditCP(secpnts);
    beginEditCP(cols);
    if(!testSet)
    {
        for(UInt32 i=0; i < numParticles; ++i)
        {
            Pnt3f pnt(osgrand(),osgrand(),osgrand());
            indices->push_back(i);  
            p->push_back(pnt);  
            sp->push_back(pnt);  
            velocities[i].setValues(osgrand()/30.f/2, osgrand()/30.f/2, osgrand()/30.f/2);
            cols->editFieldPtr()->push_back( 
                Color3f(osgrand()/2.f + .5f,osgrand()/2.f + .5f,osgrand()/2.f + .5f) );
            size->push_back(
                Vec3f(osgrand()/20.f+0.05,osgrand()/20.f+0.05,osgrand()/20.f+0.05));
        }
    }
    else
    {
        Pnt3f   tpos[] = 
        { Pnt3f(.5,.5,.5), Pnt3f (.5,.5,.7), Pnt3f(.5,.5,.9), Pnt3f(.7,.5,.5), 
          Pnt3f(.5,.7,.5), Pnt3f (-1000,-1000,-1000) };
        
        Pnt3f   tsecpos[] = 
        { Pnt3f(0,0,0), Pnt3f(0,0,0), Pnt3f(0,0,0), Pnt3f(0,0,0), 
          Pnt3f(0,0,0) };
        
        Vec3f   tvel[] = 
        { Vec3f(0,0,0), Vec3f(0,0,0), Vec3f(0,0,0), Vec3f(0,0,0), 
          Vec3f(0,0,0) };
        
        Color3f tcol[] = 
        { Color3f(1,0,0), Color3f(0,1,0), Color3f(0,0,1), Color3f(1,1,0), 
          Color3f(1,0,1), Color3f(0,1,1), Color3f(1,1,1) };
        
        Vec3f   tsize[] = 
        { Vec3f(.1,0,0), Vec3f(.1,0,0), Vec3f(.1,0,0), Vec3f(.1,0,0), 
          Vec3f(.1,0,0) };

        for(UInt32 i=0; tpos[i][0] > -1000; ++i)
        {
            indices->push_back(i);  
            p->push_back(tpos[i]);  
            sp->push_back(tsecpos[i]);  
            velocities[i].setValue(tvel[i]);
            cols->editFieldPtr()->push_back(tcol[i]);
            size->push_back(tsize[i]);
        }
       
    }
    endEditCP(pnts);
    endEditCP(secpnts);
    endEditCP(cols);

    beginEditCP(norms);
    norms->push_back(Vec3f(0,1,0));
    endEditCP(norms);

    particles->setPositions( pnts );
    particles->setSecPositions( secpnts );
    particles->setColors( cols );
    particles->setNormals( norms );
                    
    endEditCP(particles);
 
    // set volume static to prevent constant update
    beginEditCP(pnode, Node::VolumeFieldMask);
#ifndef OSG_2_PREP
    Volume &v = pnode->editVolume(false).getInstance();
#else
    Volume &v = pnode->editVolume(false);
#endif
    v.setEmpty();
    v.extendBy(Pnt3f(0,0,0));
    v.extendBy(Pnt3f(1,1,1));
    v.setStatic();
#ifndef OSG_2_PREP
    pnode->editVolume(false).instanceChanged();
#endif
    endEditCP  (pnode, Node::VolumeFieldMask);
  
    SimpleTexturedMaterialPtr tm;

    tm = SimpleTexturedMaterial::create();

    UChar8 imgdata[] =
        {  255,255,255,  255,0,0,  255,0,255,
           255,0,0,  255,0,0,  255,255,255 };
    ImagePtr pImage = Image::create();

    if (argc > 2)
    {
        pImage->read(argv[2]);
    }
    else
    {
        pImage->set(Image::OSG_RGB_PF, 3, 2, 1, 1, 1, 0, imgdata);
    }
    
    beginEditCP(tm);
    tm->setDiffuse( Color3f( 1,1,1 ) );
    tm->setLit( false );

    tm->setImage( pImage );
    tm->setEnvMode( GL_MODULATE );
    
    BlendChunkPtr bl=BlendChunk::create();
    
    beginEditCP(bl);
    bl->setSrcFactor(GL_SRC_ALPHA);
    //bl->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);
    bl->setDestFactor(GL_ONE);
#if 0
    bl->setAlphaFunc(GL_EQUAL);
    bl->setAlphaValue(1);   
#endif
    endEditCP(bl);
   
    tm->addChunk(bl);
    
    endEditCP(tm);

    particles->setMaterial( tm );

#if 0
    // write it, just for testing

    std::ofstream out("test.osg");
    OSGWriter w(out);
    
    w.write(scene);
    
#endif

    // 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->setHighlight(scene);
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}