コード例 #1
0
void
ColladaLight::createAmbientLight(ColladaLightAmbientInstInfo *colInstInfo)
{
    OSG_COLLADA_LOG(("ColladaLight::createAmbientLight\n"));

    LightLoaderState *state =
        getGlobal()->getLoaderStateAs<LightLoaderState>(_loaderStateName);
    OSG_ASSERT(state != NULL);

    ChunkOverrideGroupUnrecPtr coGroup  = ChunkOverrideGroup::create();
    NodeUnrecPtr               coGroupN = makeNodeFor(coGroup);

    coGroup->addChunk(state->getLightModelChunk());

    Node *rootN = getGlobal()->getRoot();

    while(rootN->getNChildren() > 0)
    {
        coGroupN->addChild(rootN->getChild(0));
    }

    if(getGlobal()->getOptions()->getCreateNameAttachments() == true)
    {
        setName(coGroupN, "OpenSG_AmbientLight");
    }

    rootN->addChild(coGroupN);
}
コード例 #2
0
ファイル: dyndrawing1.cpp プロジェクト: jondo2010/OpenSG
//
// setup scene
//
static int doMain(int argc, char *argv[])
{
    preloadSharedObject("OSGFileIO");
    preloadSharedObject("OSGImageFileIO");

    osgInit(argc,argv);

    int winid = setupGLUT(&argc, argv);

    win = GLUTWindow::create();
    win->setGlutId(winid);
    win->init();

    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
        FWARNING(("Supported file formats:\n"));

        std::list<const char*> suffixes;
        SceneFileHandler::the()->getSuffixList(suffixes);

        for(std::list<const char*>::iterator it  = suffixes.begin();
                                            it != suffixes.end();
                                        ++it)
        {
            FWARNING(("%s\n", *it));
        }

        staticScene = createStaticScene();
    }
    else
    {
        staticScene = SceneFileHandler::the()->read(argv[1]);
    }

    dynamicScene = createDynamicScene();

    commitChanges();

    mgr = SimpleSceneManager::create();

    NodeUnrecPtr root = makeCoredNode<Group>();
    root->addChild(staticScene);

    mgr->setWindow(win);
    mgr->setRoot  (root);

    GradientBackgroundUnrecPtr background = GradientBackground::create();
    background->addLine(Color3f(0,0,0), 0);
    background->addLine(Color3f(1,1,1), 1);

    staticVp = win->getPort(0);
    staticVp->setBackground(background);

    camera = staticVp->getCamera();

    mgr->showAll();

    return 0;
}
コード例 #3
0
ComponentTransitPtr SceneNodeTreeComponentGenerator::getTreeComponent(Tree* const Parent, 
                                                                            const boost::any& Value, 
                                                                            bool IsSelected, 
                                                                            bool Expanded, 
                                                                            bool Leaf, 
                                                                            UInt32 Row, 
                                                                            bool HasFocus)
{
    NodeUnrecPtr TheNode;
    try
    {
        TheNode = boost::any_cast<NodeUnrecPtr>(Value);
    }
    catch (boost::bad_any_cast &)
    {
        //Could not convert to FieldContinerFieldPath
        return ComponentTransitPtr(NULL);
    }

    //Get the text for the label
    std::string LabelText("");
    if(TheNode != NULL)
    {
        const Char8* name(getName(TheNode));
        if(name)
        {
            LabelText += std::string(name) + " ";
        }
        if(TheNode->getCore() != NULL)
        {
            LabelText += std::string("[") + TheNode->getCore()->getType().getCName() + "]";
        }
        else
        {
            LabelText += "[NULL core]";
        }
    }
    else
    {
        LabelText += "NULL";
    }

    ComponentRecPtr GenComp = getTreeComponentText(Parent, LabelText, IsSelected, Expanded, Leaf, Row, HasFocus);
    if(TheNode != NULL &&
       !(TheNode->getTravMask() & getTravMask()))
    {
        GenComp->setEnabled(false);
    }

    return ComponentTransitPtr(GenComp);
}
コード例 #4
0
ファイル: dyndrawing1.cpp プロジェクト: jondo2010/OpenSG
static void enableStaticScene()
{
    win->subPortByObj(dynamicVp);
    dynamicVp = nullptr;

    NodeUnrecPtr root = makeCoredNode<Group>();
    root->addChild(staticScene);
    mgr->setRoot(root);

    mgr->getNavigator()->setViewport(staticVp);

    staticVp->setCamera(camera);

    win->addPort(staticVp);
}
コード例 #5
0
void SceneGraphTreeModel::removeNode(NodeUnrecPtr nodeToBeRemoved)
{

    NodeRefPtr parent = nodeToBeRemoved->getParent();

    TreePath pathOfNode = createPath(nodeToBeRemoved);
    if(parent!=NULL)
    {
        UInt32 ChildIndex(parent->findChild(nodeToBeRemoved));


        produceTreeNodesWillBeRemoved(pathOfNode.getParentPath(),std::vector<UInt32>(1, ChildIndex),std::vector<boost::any>(1, nodeToBeRemoved));
        parent->subChild(nodeToBeRemoved);
        produceTreeNodesRemoved(pathOfNode.getParentPath(),std::vector<UInt32>(1, ChildIndex),std::vector<boost::any>(1, nodeToBeRemoved));

        if(parent->getNChildren() == 0)
        {
            if(parent->getParent() != NULL)
            {
                std::vector<UInt32> childIndices;
                childIndices.push_back(parent->getParent()->findChild(parent));
                std::vector<boost::any> ChildUserObjects;
                for(UInt32 i(0) ; i< childIndices.size() ; ++i)
                {
                    ChildUserObjects.push_back(boost::any(NodeUnrecPtr(parent->getParent()->getChild(childIndices[i]))));
                }
                produceTreeNodesChanged(createPath(parent->getParent()), childIndices, ChildUserObjects);
            }
        }
    }
}
コード例 #6
0
ファイル: dyndrawing1.cpp プロジェクト: jondo2010/OpenSG
//
// create an arbitrarly complex render scene
//
static NodeTransitPtr createStaticScene()
{
    NodeUnrecPtr root = makeCoredNode<Group>();

    typedef boost::mt19937 base_generator_type;
    static base_generator_type generator(0);
    static boost::uniform_01<float> value;
    static boost::variate_generator< base_generator_type, boost::uniform_01<float> > die(generator, value);

    for (int i = 0; i < max_tori; ++i) {
        NodeUnrecPtr scene = makeTorus(.5, 2, 32, 32);

        TransformUnrecPtr transformCore = Transform::create();
        Matrix mat;

        mat.setIdentity();

        float x = 500.f * die();
        float y = 500.f * die();
        float z = 500.f * die();

        float e1 = die();
        float e2 = die();
        float e3 = die();

        Vec3f v(e1,e2,e3);
        v.normalize();

        float a = TwoPi * die();

        Quaternion q(v, a);

        mat.setTranslate(x,y,z);
        mat.setRotate(q);

        transformCore->setMatrix(mat);

        NodeUnrecPtr trafo = makeNodeFor(transformCore);

        trafo->addChild(scene);

        root->addChild(trafo);
    }
    
    return NodeTransitPtr(root);
}
コード例 #7
0
NodeTransitPtr buildScene(void)
{
    NodeUnrecPtr geoN = makeBox(1.f, 1.f, 1.f, 1, 1, 1);

    ComponentTransformUnrecPtr xform  = ComponentTransform::create();
    NodeUnrecPtr               xformN = makeNodeFor(xform);
    
    setTargetId(xform, "xform0");

    gXForm = xform;

    NodeUnrecPtr      groupN = makeCoredNode<Group>();

    xformN->addChild(geoN  );
    groupN->addChild(xformN);

    return NodeTransitPtr(groupN);
}
コード例 #8
0
void dropPhysicsBody(RenderAction* action,const NodeUnrecPtr node, MaterialUnrecPtr mat)
{
    //Get the Physics Body object attached to this node, if there is one
    AttachmentUnrecPtr TheBodyAttachment(node->findAttachment(PhysicsBody::getClassType()));

    if(TheBodyAttachment != NULL)
    {
        PhysicsBodyDrawWrapper::drop(action, node, dynamic_pointer_cast<PhysicsBody>(TheBodyAttachment), mat);
    }
}
コード例 #9
0
UInt32 SceneGraphTreeModel::getChildCount(const boost::any& parent) const
{
    try
    {
        NodeUnrecPtr TheNode = boost::any_cast<NodeUnrecPtr>(parent);
        if(TheNode != NULL)
        {
            return TheNode->getNChildren();
        }
        else
        {
            return 0;
        }
    }
    catch(boost::bad_any_cast &ex)
    {
        SWARNING << "Bad any cast: " << ex.what() << std::endl;
        return 0;
    }
}
コード例 #10
0
boost::any SceneGraphTreeModel::getChild(const boost::any& parent, const UInt32& index) const
{
    try
    {
        NodeUnrecPtr TheNode = boost::any_cast<NodeUnrecPtr>(parent);
        if(TheNode != NULL &&
           TheNode->getNChildren() > index)
        {
            return boost::any(NodeUnrecPtr(TheNode->getChild(index)));
        }
        else
        {
            return boost::any();
        }
    }
    catch(boost::bad_any_cast &ex)
    {
        SWARNING << "Bad any cast: " << ex.what() << std::endl;
        return boost::any();
    }
}
コード例 #11
0
UInt32 SceneGraphTreeModel::getIndexOfChild(const boost::any& parent, const boost::any& child) const
{
    try
    {
        NodeUnrecPtr ParentNode = boost::any_cast<NodeUnrecPtr>(parent);
        NodeUnrecPtr ChildNode = boost::any_cast<NodeUnrecPtr>(child);
        if(ParentNode != NULL &&
           ChildNode  != NULL)
        {
            return ParentNode->findChild(ChildNode);
        }
        else
        {
            return 0;
        }
    }
    catch(boost::bad_any_cast &ex)
    {
        SWARNING << "Bad any cast: " << ex.what() << std::endl;
        return 0;
    }
}
コード例 #12
0
void SceneGraphTreeModel::insertNode(NodeUnrecPtr parent,
                                     NodeUnrecPtr nodeToBeAdded,
                                     UInt32 Index)
{
    NodeRefPtr(parent)->insertChild(Index, nodeToBeAdded);
    produceTreeNodesInserted(createPath(parent),std::vector<UInt32>(1, Index),std::vector<boost::any>(1, nodeToBeAdded));

    if(parent->getNChildren() == 1)
    {
        if(parent->getParent() != NULL)
        {
            std::vector<UInt32> childIndices;
            childIndices.push_back(parent->getParent()->findChild(parent));
            std::vector<boost::any> ChildUserObjects;
            for(UInt32 i(0) ; i< childIndices.size() ; ++i)
            {
                ChildUserObjects.push_back(boost::any(NodeUnrecPtr(parent->getParent()->getChild(childIndices[i]))));
            }
            produceTreeNodesChanged(createPath(NodeUnrecPtr(parent->getParent())), childIndices, ChildUserObjects);
        }
    }
}
コード例 #13
0
   virtual void keyPressed(const KeyEventUnrecPtr e)
   {
       if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_CONTROL)
       {
           TutorialWindow->closeWindow();
       }
       switch(e->getKey())
       {
       case KeyEvent::KEY_B:
           buildBox(Vec3f(10.0,10.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0));
           break;
	   case KeyEvent::KEY_UP:
           _IsUpKeyDown = true;
		   break;
	   case KeyEvent::KEY_DOWN:
           _IsDownKeyDown = true;
		   break;
	   case KeyEvent::KEY_LEFT:
           _IsLeftKeyDown = true;
		   break;
	   case KeyEvent::KEY_RIGHT:
           _IsRightKeyDown = true;
           break;
       case KeyEvent::KEY_D:
            {
                if(PhysDrawableNode->getTravMask())
                {
                    PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMin());
                }
                else
                {
                    PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMax());
                }
            }
            break;
       }
   }
コード例 #14
0
void SceneGraphTreeModel::valueForPathChanged(TreePath path, const boost::any& newValue)
{
    try
    {
        NodeUnrecPtr NewNode = boost::any_cast<NodeUnrecPtr>(newValue);
        NodeUnrecPtr OldNode = boost::any_cast<NodeUnrecPtr>(path.getLastPathComponent());
        if(NewNode != NULL &&
           OldNode  != NULL &&
           NewNode != OldNode &&
           OldNode->getParent() != NULL)
        {
            NodeUnrecPtr ParentNode(OldNode->getParent());
            if(ParentNode->replaceChildBy(OldNode, NewNode))
            {
                UInt32 ChildIndex(ParentNode->findChild(NewNode));
                produceTreeStructureChanged(path.getParentPath(),std::vector<UInt32>(1, ChildIndex),std::vector<boost::any>(1, newValue));
            }
        }
    }
    catch(boost::bad_any_cast &ex)
    {
        SWARNING << "Bad any cast: " << ex.what() << std::endl;
    }
}
コード例 #15
0
ファイル: dyndrawing1.cpp プロジェクト: jondo2010/OpenSG
static void createDynamicViewport()
{
    win->subPortByObj(staticVp);

    FBOBackgroundUnrecPtr fboBckgnd = FBOBackground::create();
    fboBckgnd->setFrameBufferObject(spSimpleFBO->fbo());

    NodeUnrecPtr root = makeCoredNode<Group>();
    root->addChild(dynamicScene);

    mgr->setRoot(root);

    dynamicVp = Viewport::create();
    dynamicVp->setRoot      (rootNode(root));
    dynamicVp->setBackground(fboBckgnd);
    dynamicVp->setCamera    (camera);
    dynamicVp->setSize      (0,0, 1,1);

    mgr->getNavigator()->setViewport(dynamicVp);
    
    win->addPort(dynamicVp);

    mgr->update();
}
コード例 #16
0
   virtual void keyPressed(const KeyEventUnrecPtr e)
   {
	   //Exit
       if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
       {
           TutorialWindow->closeWindow();
       }

	   //Toggle animation
	   if(e->getKey() == KeyEvent::KEY_SPACE)
	   {
		   if(animationPaused)
			   animationPaused = false;
		   else
			   animationPaused = true;
	   }

	   //Toggle bind pose
	   if(e->getKey() == KeyEvent::KEY_B)
	   {
		   //Toggle skeleton
		   if(dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->getDrawBindPose() == false)
		   {
				 dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->setDrawBindPose(true);
		   } 
		   else
		   {
				 dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->setDrawBindPose(false);
		   }
	   }

	   //Toggle current pose
	   if(e->getKey() == KeyEvent::KEY_P)
	   {
		   //Toggle skeleton
		   if(dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->getDrawPose() == false)
		   {
				 dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->setDrawPose(true);
		   } 
		   else
		   {
				 dynamic_cast<SkeletonDrawable*>(SkeletonNode->getCore())->setDrawPose(false);
		   }
	   }

	   //Switch animation
	   if(e->getKey() == KeyEvent::KEY_1)
	   {
			TheCurrentAnimation = TheJointAnimation;
	   }
	   else if(e->getKey() == KeyEvent::KEY_2)
	   {
			TheCurrentAnimation = TheChildJointAnimation;
	   }
   }
コード例 #17
0
//////////////////////////////////////////////////////////////////////////
//! build a sphere
//////////////////////////////////////////////////////////////////////////
PhysicsBodyUnrecPtr buildSphere(void)
{
    Real32 Radius((Real32)(rand()%2)*0.5+0.5);
    Matrix m;
    //create OpenSG mesh
    GeometryUnrecPtr sphere;
    NodeUnrecPtr sphereNode = makeSphere(2, Radius);
    sphere = dynamic_cast<Geometry*>(sphereNode->getCore());
    SimpleMaterialUnrecPtr sphere_mat = SimpleMaterial::create();
    sphere_mat->setAmbient(Color3f(0.0,0.0,0.0));
    sphere_mat->setDiffuse(Color3f(0.0,0.0,1.0));
    sphere->setMaterial(sphere_mat);
    TransformUnrecPtr sphereTrans;
    NodeUnrecPtr sphereTransNode = makeCoredNode<Transform>(&sphereTrans);
    m.setIdentity();
    Real32 randX = (Real32)(rand()%10)-5.0;
    Real32 randY = (Real32)(rand()%10)-5.0;
    m.setTranslate(randX, randY, 10.0);
    sphereTrans->setMatrix(m);
    //create ODE data
    PhysicsBodyUnrecPtr sphereBody = PhysicsBody::create(physicsWorld);
        sphereBody->setPosition(Vec3f(randX, randY, 10.0));
        sphereBody->setLinearDamping(0.0001);
        sphereBody->setAngularDamping(0.0001);
    sphereBody->setSphereMass(1.0,Radius);

    PhysicsSphereGeomUnrecPtr sphereGeom = PhysicsSphereGeom::create();
        sphereGeom->setBody(sphereBody);
        sphereGeom->setSpace(physicsSpace);
        sphereGeom->setRadius(Radius);
    
    //add attachments
    sphereNode->addAttachment(sphereGeom);
    sphereTransNode->addAttachment(sphereBody);
    sphereTransNode->addChild(sphereNode);
    //add to SceneGraph
    spaceGroupNode->addChild(sphereTransNode);

    commitChanges();

    return sphereBody;
}
コード例 #18
0
//////////////////////////////////////////////////////////////////////////
//! build a box
//////////////////////////////////////////////////////////////////////////
PhysicsBodyUnrecPtr buildBox(void)
{
    Vec3f Lengths((Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0);
    Matrix m;
    //create OpenSG mesh
    GeometryUnrecPtr box;
    NodeUnrecPtr boxNode = makeBox(Lengths.x(), Lengths.y(), Lengths.z(), 1, 1, 1);
    box = dynamic_cast<Geometry*>(boxNode->getCore());
    SimpleMaterialUnrecPtr box_mat = SimpleMaterial::create();
        box_mat->setAmbient(Color3f(0.0,0.0,0.0));
        box_mat->setDiffuse(Color3f(0.0,1.0 ,0.0));
        box->setMaterial(box_mat);
    TransformUnrecPtr boxTrans;
    NodeUnrecPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    Real32 randX = (Real32)(rand()%10)-5.0;
    Real32 randY = (Real32)(rand()%10)-5.0;
    m.setTranslate(randX, randY, 10.0);
        boxTrans->setMatrix(m);

    //create ODE data
    PhysicsBodyUnrecPtr boxBody = PhysicsBody::create(physicsWorld);
        boxBody->setPosition(Vec3f(randX, randY, 10.0));
    boxBody->setBoxMass(1.0, Lengths.x(), Lengths.y(), Lengths.z());

    PhysicsBoxGeomUnrecPtr boxGeom = PhysicsBoxGeom::create();
        boxGeom->setBody(boxBody);
        boxGeom->setSpace(physicsSpace);
        boxGeom->setLengths(Lengths);

    //add attachments
        boxNode->addAttachment(boxGeom);
        boxTransNode->addAttachment(boxBody);
        boxTransNode->addChild(boxNode);

    //add to SceneGraph
        spaceGroupNode->addChild(boxTransNode);

    commitChanges();
    return boxBody;
}
コード例 #19
0
PhysicsBodyUnrecPtr  buildBox(const Pnt3f& Position,
                              const Vec3f& Dimensions,
                              const Color3f& Color,
                              Node* const spaceGroupNode,
                              PhysicsWorld* const physicsWorld,
                              PhysicsHashSpace* const physicsSpace)
{
    Matrix m;
    //create OpenSG mesh
    GeometryUnrecPtr box;
    NodeUnrecPtr boxNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1);
    box = dynamic_cast<Geometry*>(boxNode->getCore());
    SimpleMaterialUnrecPtr box_mat = SimpleMaterial::create();
    box_mat->setAmbient(Color3f(0.0,0.0,0.0));
    box_mat->setDiffuse(Color);
    box->setMaterial(box_mat);
    TransformUnrecPtr boxTrans;
    NodeUnrecPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    m.setTranslate(Position);
    boxTrans->setMatrix(m);

    //create ODE data
    PhysicsBodyUnrecPtr boxBody = PhysicsBody::create(physicsWorld);
    boxBody->setPosition(Vec3f(Position));
    boxBody->setBoxMass(1.0,Dimensions.x(), Dimensions.y(), Dimensions.z());
    boxBody->setLinearDamping(0.0001);
    boxBody->setAngularDamping(0.0001);
    PhysicsBoxGeomUnrecPtr boxGeom = PhysicsBoxGeom::create();
    boxGeom->setBody(boxBody);
    boxGeom->setSpace(physicsSpace);
    boxGeom->setLengths(Dimensions);

    //add attachments
    boxNode->addAttachment(boxGeom);
    boxTransNode->addAttachment(boxBody);
    boxTransNode->addChild(boxNode);

    //add to SceneGraph
    spaceGroupNode->addChild(boxTransNode);

    return boxBody;
}
コード例 #20
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();

        //Initialize Window
        TutorialWindow->initWindow();

        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        //Torus Material
        SimpleMaterialUnrecPtr TheTorusMaterial = SimpleMaterial::create();
        TheTorusMaterial->setAmbient(Color3f(0.3,0.3,0.3));
        TheTorusMaterial->setDiffuse(Color3f(0.7,0.7,0.7));
        TheTorusMaterial->setSpecular(Color3f(1.0,1.0,1.0));
        TheTorusMaterial->setShininess(20.0);

        //Torus Geometry
        GeometryUnrecPtr TorusGeometry = makeTorusGeo(.5, 2, 32, 32);
        TorusGeometry->setMaterial(TheTorusMaterial);

        NodeUnrecPtr TorusGeometryNode = Node::create();
        TorusGeometryNode->setCore(TorusGeometry);

        //Make Torus Node
        NodeUnrecPtr TorusNode = Node::create();
        TransformUnrecPtr TorusNodeTrans = Transform::create();
        setName(TorusNodeTrans, std::string("TorusNodeTransformationCore"));

        TorusNode->setCore(TorusNodeTrans);
        TorusNode->addChild(TorusGeometryNode);

        //Make Main Scene Node
        NodeUnrecPtr scene = Node::create();
        ComponentTransformUnrecPtr Trans = ComponentTransform::create();
        setName(Trans, std::string("MainTransformationCore"));
        scene->setCore(Trans);

        // add the torus as a child
        scene->addChild(TorusNode);

        AnimationGroupUnrecPtr TheAnimation = setupAnimation(TheTorusMaterial, TorusNodeTrans);
        TutorialWindow->connectKeyPressed(boost::bind(keyPressed, _1,
                                                      TheAnimation.get(),
                                                      TutorialWindow.get()));
        TheAnimation->attachUpdateProducer(TutorialWindow);
        TheAnimation->start();

        // tell the manager what to manage
        sceneManager.setRoot  (scene);

        //Create the Documentation
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);

        // show the whole scene
        sceneManager.showAll();


        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "07AnimationGroup");

        //Enter main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
コード例 #21
0
// Initialize GLUT & OpenSG and set up the rootNode
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

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

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
	TutorialUpdateListener TheTutorialUpdateListener;
    TutorialWindow->addUpdateListener(&TheTutorialUpdateListener);


    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    //Make Main Scene Node
	NodeRefPtr scene = makeCoredNode<Group>();
    setName(scene, "scene");
    rootNode = Node::create();
    setName(rootNode, "rootNode");
    ComponentTransformRefPtr Trans;
    Trans = ComponentTransform::create();
    {
        rootNode->setCore(Trans);
 
        // add the torus as a child
        rootNode->addChild(scene);
    }

    //Make The Physics Characteristics Node
    PhysicsCharacteristicsDrawableUnrecPtr PhysDrawable = PhysicsCharacteristicsDrawable::create();
        PhysDrawable->setRoot(rootNode);

	PhysDrawableNode = Node::create();
    PhysDrawableNode->setCore(PhysDrawable);
    PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMin());

    rootNode->addChild(PhysDrawableNode);

    //Light Beacon
    NodeRefPtr TutorialLightBeacon = makeCoredNode<Transform>();

    //Light Node
    DirectionalLightRefPtr TutorialLight = DirectionalLight::create();
    TutorialLight->setDirection(0.0,0.0,-1.0);
    TutorialLight->setBeacon(TutorialLightBeacon);

    NodeRefPtr TutorialLightNode = Node::create();
    TutorialLightNode->setCore(TutorialLight);

    scene->addChild(TutorialLightNode);
    scene->addChild(TutorialLightBeacon);


    //Setup Physics Scene
    physicsWorld = PhysicsWorld::create();
        physicsWorld->setWorldContactSurfaceLayer(0.01);
        physicsWorld->setAutoDisableFlag(1);
        physicsWorld->setAutoDisableTime(0.75);
        physicsWorld->setWorldContactMaxCorrectingVel(1.0);
        //physicsWorld->setGravity(Vec3f(0.0, 0.0, -9.81));
        //physicsWorld->setCfm(0.001);
        //physicsWorld->setErp(0.2);

    hashSpace = PhysicsHashSpace::create();

    physHandler = PhysicsHandler::create();
        physHandler->setWorld(physicsWorld);
        physHandler->pushToSpaces(hashSpace);
        physHandler->setUpdateNode(rootNode);
    physHandler->attachUpdateProducer(TutorialWindow->editEventProducer());
    

        rootNode->addAttachment(physHandler);    
        rootNode->addAttachment(physicsWorld);
        rootNode->addAttachment(hashSpace);


	/************************************************************************/
	/* create spaces, geoms and bodys                                                                     */
	/************************************************************************/
    //create a group for our space
    GroupRefPtr spaceGroup;
	spaceGroupNode = makeCoredNode<Group>(&spaceGroup);
	//add Attachments to nodes...
	    spaceGroupNode->addAttachment(hashSpace);

	    TutorialLightNode->addChild(spaceGroupNode);

    //Create Character
    ShipBody = buildShip(Vec3f(3.0,3.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0));
    ShipMotor = buildMotor(ShipBody);

    for(UInt32 i(0) ; i<5 ; ++i)
    {
        buildBox(Vec3f(10.0,10.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0));
    }

    // tell the manager what to manage
    mgr->setRoot  (rootNode);

    // show the whole rootNode
    mgr->showAll();
    
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "04ZeroGravityShip");

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

    osgExit();

    return 0;
}
コード例 #22
0
Action::ResultE GeometryMergeGraphOp::traverseLeave(
        Node * const node, Action::ResultE res)
{
    if(isInExcludeList(node))
        return Action::Skip;

    NodeCore *core = node->getCore();
    
    // skip cores with a dependency on the children number/order
    // TODO: find a way to make this extendable
    if(core == NULL                                               ||
       core->getType().isDerivedFrom(DistanceLOD::getClassType()) ||
       core->getType().isDerivedFrom(ScreenLOD  ::getClassType()) ||
       core->getType().isDerivedFrom(Switch     ::getClassType()) ||
       core->getType().isDerivedFrom(MultiCore  ::getClassType())   )
    {
        return Action::Continue;
    }
    
    typedef std::vector<NodeUnrecPtr> NodeStore;
    NodeStore addStore;     // nodes to add as children to current one
    NodeStore subStore;     // nodes (children) to remove from current one
    
    typedef std::vector<Node *    > MergeGroup; // geometries that can be merged
    typedef std::vector<MergeGroup> MergeList;  // list of merge groups
    
    MergeList                            ml;
    Node::MFChildrenType::const_iterator childIt  =
            node->getMFChildren()->begin();
    Node::MFChildrenType::const_iterator childEnd =
            node->getMFChildren()->end  ();
    
    // group geometry children that are mergeable
    for(; childIt != childEnd; ++childIt)
    {
        if((*childIt)->getCore()->getType() != Geometry::getClassType())
            continue;
        
        if(isInExcludeList(*childIt) || isInPreserveList(*childIt))
            continue;
        
        Geometry *geo = dynamic_cast<Geometry *>((*childIt)->getCore());
        Material *mat = geo->getMaterial();
        
        MergeList::iterator mlIt  = ml.begin();
        MergeList::iterator mlEnd = ml.end  ();
        
        bool done = false;
        
        for(; mlIt != mlEnd && !done; ++mlIt)
        {
            Geometry *mlGeo =
                    dynamic_cast<Geometry *>(mlIt->front()->getCore());
            Material *mlMat = mlGeo->getMaterial();
            
            if(compareContainerEqual(mlMat, mat) &&
               mergeableGeo         (mlGeo, geo)   )
            {
                mlIt->push_back(*childIt);
                done = true;
            }
        }
        
        if(!done)
        {
            ml       .push_back(MergeGroup());
            ml.back().push_back(*childIt    );
        }
    }
    
    // merge geometry in the same group and replace obsolete children with
    // new geometry
    MergeList::iterator mlIt  = ml.begin();
    MergeList::iterator mlEnd = ml.end  ();
    
    for(; mlIt != mlEnd; ++mlIt)
    {
        // only one geometry in merge group -> nothing to do
        if(mlIt->size() <= 1)
            continue;
        
        FINFO(("GeometryMergeGraphOp::traverseLeave: Merging [%" PRISize "] "
               "Geometries.\n", mlIt->size()));
        
        GeometryUnrecPtr     geo1;
        GeometryUnrecPtr     geo2;
        NodeUnrecPtr         newNode = Node::create();
        MergeGroup::iterator mgIt    = mlIt->begin();
        MergeGroup::iterator mgEnd   = mlIt->end  ();
        
        geo1 = dynamic_cast<Geometry *>((*mgIt)->getCore());

        // remove the first geo as well
        subStore.push_back(*mgIt);

        ++mgIt;
        
        for(UInt32 i = 0; mgIt != mgEnd; ++mgIt, ++i)
        {
            geo2 = dynamic_cast<Geometry *>((*mgIt)->getCore());
            
            if(i > _mergeThreshold && (mgIt + 1) != mgEnd)
            {
                newNode->setCore(geo1);
                addStore.push_back(newNode);
                
                i       = 0;
                newNode = Node::create();
                geo1    = dynamic_cast<Geometry *>((*mgIt)->getCore());
                ++mgIt;
            }
            
            geo1 = mergeGeo(geo1, geo2);
            geo1->setMaterial(geo2->getMaterial());
            
            subStore.push_back(*mgIt);
        }
        
       newNode->setCore(geo1);
       addStore.push_back(newNode);
    }
    
    // add newly created geometries to current node
    NodeStore::const_iterator storeIt  = subStore.begin();
    NodeStore::const_iterator storeEnd = subStore.end  ();
    
    for(; storeIt != storeEnd; ++storeIt)
       node->subChild(*storeIt);
    
    storeIt  = addStore.begin();
    storeEnd = addStore.end  ();
    
    for(; storeIt != storeEnd; ++storeIt)
       node->addChild(*storeIt);
    
    return Action::Continue;
}
コード例 #23
0
ファイル: OSGVCoREOSGSceneItem.cpp プロジェクト: vossg/VCoRE
bool OSGSceneItem::init(UInt32 uiInitPhase, App *pApp)
{
    fprintf(stderr, "OSGSceneItem::init %s (%x)\n",
            getName(this),
            uiInitPhase);

    if(0x0000 != (uiInitPhase & ::OSG::InitPhase::LoadReferences))
    {
        if(_sfMatchedUrl.getValue().empty() == false)
        {
            fprintf(stderr, "Loading %s\n",
                    _sfMatchedUrl.getValue().c_str());
            
            NodeUnrecPtr pRoot = SceneFileHandler::the()->read(
                _sfMatchedUrl.getValue().c_str(),
                NULL,
                NULL,
                false);
            
            fprintf(stderr, "got %p\n", pRoot.get());
            
            if(pRoot != NULL)
            {
                setRoot(pRoot);
            }
            else
            {
                fprintf(stderr, "  failed\n");
            }
        }


        if(_sfMatchedGlobalUrl.getValue().empty() == false)
        {
            fprintf(stderr, "Loading global %s\n",
                    _sfMatchedGlobalUrl.getValue().c_str());
            
            FieldContainerUnrecPtr pRes(NULL);

            _oPathHandler.pushState();

            _oPathHandler.setBaseFile(_sfMatchedGlobalUrl.getValue().c_str());

            ImageFileHandler::the()->setPathHandler(&_oPathHandler);

            fprintf(stderr, "loading osg file %s ...\n",
                    _sfMatchedGlobalUrl.getValue().c_str());

            pRes = OSG::OSGSceneFileType::the().readContainer(
                _sfMatchedGlobalUrl.getValue().c_str(),
                NULL);

            ImageFileHandler::the()->setPathHandler(NULL);

            _oPathHandler.popState();
            
            fprintf(stderr, "got global %p\n", pRes.get());
            
            if(pRes != NULL)
            {
                ContainerCollectionUnrecPtr pColl = 
                    dynamic_pointer_cast<ContainerCollection>(pRes);

                if(pColl != NULL)
                {
                    MFUnrecFieldContainerPtr::const_iterator fIt  = 
                        pColl->getMFContainers()->begin();

                    MFUnrecFieldContainerPtr::const_iterator fEnd = 
                        pColl->getMFContainers()->end();

                    while(fIt != fEnd)
                    {
                        this->pushToGlobals(*fIt);
                        ++fIt;
                    }   
                }
            }
            else
            {
                fprintf(stderr, "  failed\n");
            }

            fprintf(stderr, "got %ld globals\n",
                    _mfGlobals.size());

            if(_sfActiveCamera.getValue().empty() == false)
            {
                FieldContainer *pCnt = findNamedComponent(
                    _sfActiveCamera.getValue().c_str());

                Camera *pCam = dynamic_cast<Camera *>(pCnt);

                fprintf(stderr, "found camera %p\n",
                        pCam);

                setCamera(pCam);
            }
        }
    }

    return true;
}
コード例 #24
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    OSG::preloadSharedObject("OSGFileIO");
    OSG::preloadSharedObject("OSGImageFileIO");
    // OSG init
    osgInit(argc,argv);
    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();

        //Initialize Window
        TutorialWindow->initWindow();

        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));
        TutorialWindow->connectKeyPressed(boost::bind(keyPressed, _1, TutorialWindow.get()));

        //Box Geometry
        GeometryUnrecPtr BoxGeometry = makeBoxGeo(1.0,1.0,1.0,1,1,1);
        ChunkMaterialUnrecPtr TheBoxMaterial = ChunkMaterial::create();
        BoxGeometry->setMaterial(TheBoxMaterial);

        NodeUnrecPtr BoxGeometryNode = Node::create();
        BoxGeometryNode->setCore(BoxGeometry);

        //Make Box Node
        NodeUnrecPtr BoxNode = Node::create();
        TransformUnrecPtr BoxNodeTrans;
        BoxNodeTrans = Transform::create();

        BoxNode->setCore(BoxNodeTrans);
        BoxNode->addChild(BoxGeometryNode);

        //Make Main Scene Node
        NodeUnrecPtr scene = Node::create();
        ComponentTransformUnrecPtr Trans;
        Trans = ComponentTransform::create();
        scene->setCore(Trans);

        // add the torus as a child
        scene->addChild(BoxNode);

        //Setup the Animation
        AnimationUnrecPtr TheAnimation = setupAnimation(TheBoxMaterial);
        TheAnimation->attachUpdateProducer(TutorialWindow);
        TheAnimation->start();

        // tell the manager what to manage
        sceneManager.setRoot  (scene);

        //Create the Documentation
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);

        // show the whole scene
        sceneManager.showAll();

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);

        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "09TextureSelectAnimation");

        //Main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
コード例 #25
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

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

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

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

	//Shader Material
	BlendChunkUnrecPtr ExampleBlendChunk = BlendChunk::create();
    ExampleBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    ExampleBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

	//Material Chunk
	MaterialChunkUnrecPtr ShaderMaterialChunk = MaterialChunk::create();
    ShaderMaterialChunk->setAmbient(Color4f(0.4f,0.4f,0.4f,1.0f));
    ShaderMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
    ShaderMaterialChunk->setSpecular(Color4f(1.0f,1.0f,1.0f,1.0f));

	//Shader Chunk
	SimpleSHLChunkUnrecPtr TheSHLChunk = SimpleSHLChunk::create();
    TheSHLChunk->setVertexProgram(createSHLVertexProg());
    TheSHLChunk->setFragmentProgram(createSHLFragProg());

	//Color Parameter
	ShaderVariableVec4fUnrecPtr Color1Parameter = ShaderVariableVec4f::create();
    Color1Parameter->setName("Color1");
    Color1Parameter->setValue(Vec4f(0.0f,1.0f,0.0f,1.0f));
	
	ShaderVariableVec4fUnrecPtr Color2Parameter = ShaderVariableVec4f::create();
    Color2Parameter->setName("Color2");
    Color2Parameter->setValue(Vec4f(1.0f,1.0f,1.0f,1.0f));


	//Shader Parameter Chunk
	SHLParameterChunkUnrecPtr SHLParameters = SHLParameterChunk::create();
    SHLParameters->getParameters().push_back(Color1Parameter);
    SHLParameters->getParameters().push_back(Color2Parameter);
    SHLParameters->setSHLChunk(TheSHLChunk);

	ChunkMaterialUnrecPtr ShaderMaterial = ChunkMaterial::create();
    ShaderMaterial->addChunk(ShaderMaterialChunk);
    ShaderMaterial->addChunk(TheSHLChunk);
    ShaderMaterial->addChunk(SHLParameters);

	//Torus Node
	GeometryUnrecPtr TorusGeometry = makeTorusGeo(5.0f,20.0f, 32,32);

    TorusGeometry->setMaterial(ShaderMaterial);

	NodeUnrecPtr TorusNode = Node::create();
    TorusNode->setCore(TorusGeometry);


    // Make Main Scene Node
    NodeUnrecPtr scene = Node::create();
    scene->setCore(Group::create());
    scene->addChild(TorusNode);

    mgr->setRoot(scene);

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

	//Create the Animations
	initAnimations(Color1Parameter, "value");

    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "04ShaderAnimation");

    //Main Loop
    TutorialWindow->mainLoop();

    osgExit();

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

    // Set up Window
    TutorialWindow = createNativeWindow();

    //Initialize Window
    TutorialWindow->initWindow();

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

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

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    //Setup the Animation
    setupAnimation();

    //Box Geometry
    GeometryUnrecPtr BoxGeometry = makeBoxGeo(1.0,1.0,1.0,1,1,1);
    BoxGeometry->setMaterial(TheBoxMaterial);
    
    NodeUnrecPtr BoxGeometryNode = Node::create();
    BoxGeometryNode->setCore(BoxGeometry);

    //Make Box Node
    NodeUnrecPtr BoxNode = Node::create();
    TransformUnrecPtr BoxNodeTrans;
    BoxNodeTrans = Transform::create();

    BoxNode->setCore(BoxNodeTrans);
    BoxNode->addChild(BoxGeometryNode);

    //Make Main Scene Node
    NodeUnrecPtr scene = Node::create();
    ComponentTransformUnrecPtr Trans;
    Trans = ComponentTransform::create();
    scene->setCore(Trans);

    // add the torus as a child
    scene->addChild(BoxNode);

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

    // show the whole scene
    mgr->showAll();
    
    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);

    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "05TextureAnimation");

    //Main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
コード例 #27
0
void VTKPolyDataMapper::initGeometries(void)
{
    NodeUnrecPtr pRoot = Node::create();
    
    pRoot->setCore(Group::create());

    setRoot(pRoot);

    for(UInt32 i = 0; i < 4; ++i)
    {
        GeometryUnrecPtr           pGeo      = Geometry::create();
    
        ChunkMaterialUnrecPtr      pMat      = ChunkMaterial::create();
        MaterialChunkUnrecPtr      pMatChunk = MaterialChunk::create();
        
        GeoPnt3fPropertyUnrecPtr   pPoints   = GeoPnt3fProperty  ::create();
        GeoUInt32PropertyUnrecPtr  pLengths  = GeoUInt32Property ::create();
        GeoUInt8PropertyUnrecPtr   pTypes    = GeoUInt8Property  ::create();
        GeoColor4fPropertyUnrecPtr pColors   = GeoColor4fProperty::create();
        GeoVec3fPropertyUnrecPtr   pNormals  = GeoVec3fProperty  ::create();

        if(i < 2)
        {
            pMatChunk->setLit(false);
        }
        
        pMatChunk->setDiffuse  (OSG::Color4f(1.0, 1.0, 1.0, 1.0));
        pMatChunk->setSpecular (OSG::Color4f(0.0, 0.0, 0.0, 1.0));
        pMatChunk->setShininess(10.0f);
        
        pMat->addChunk(pMatChunk);

        TwoSidedLightingChunkUnrecPtr pTSLChunk = 
            TwoSidedLightingChunk::create();
            
        pMat->addChunk(pTSLChunk);

        pGeo->setDlistCache(false   );
        
        pGeo->setMaterial  (pMat    );
        pGeo->setPositions (pPoints );
        pGeo->setLengths   (pLengths);
        pGeo->setTypes     (pTypes  );
        pGeo->setColors    (pColors );

        if(i > 1)
        {
            pGeo->setNormals(pNormals);
        }

        OSG::NodeUnrecPtr pGeoRoot = OSG::Node::create();
        
        pGeoRoot->setCore    (pGeo);
        pGeoRoot->setTravMask(0   );

        pRoot->addChild(pGeoRoot);

        this->pushToGeometries    (pGeo     );
        this->pushToMaterials     (pMat     );
        this->pushToMaterialChunks(pMatChunk);
        this->pushToPositions     (pPoints  );
        this->pushToLength        (pLengths );
        this->pushToTypes         (pTypes   );
        this->pushToColors        (pColors  );
        this->pushToNormals       (pNormals );
        this->pushToGeoRoots      (pGeoRoot );
    }
}
コード例 #28
0
ファイル: dyndrawing1.cpp プロジェクト: jondo2010/OpenSG
//
// setup of the image generation stage
//
static void createAcquisitionStage()
{
    size_t num_ports = win->getMFPort()->size();
    if (num_ports == 0)
        return;

    UInt32 width  = win->getWidth();
    UInt32 height = win->getHeight();

    Real32 a = Real32(width) / Real32(height);
    width = UInt32(a*height);

    Viewport* vp = staticVp;

    Node* internalRoot = rootNode(mgr->getRoot());

    //
    // Setup the FBO
    //
    spSimpleFBO.reset(new SimpleFBO(width, height, true, true, true, false));
    
    //spSimpleFBO->fbo()->setPostProcessOnDeactivate(true);
    //spSimpleFBO->colorBuffer(0)->setReadBack(true);

    //
    // We would like to render the scene but won't detach it from its parent.
    // The VisitSubTree allows just that.
    //
    VisitSubTreeUnrecPtr visitor = VisitSubTree::create();
    visitor->setSubTreeRoot(internalRoot);
    NodeUnrecPtr visit_node = makeNodeFor(visitor);

    //
    // The stage object does provide a render target for the frame buffer attachment.
    // SimpleStage has a camera, a background and the left, right, top, bottom
    // fields to let you restrict rendering to a sub-rectangle of your FBO, i.e.
    // they give you a viewport.
    //
    SimpleStageUnrecPtr stage = SimpleStage::create();
    stage->setRenderTarget(spSimpleFBO->fbo());
    stage->setCamera      (vp->getCamera());
    stage->setBackground  (vp->getBackground());
    //
    // Give the stage core a place to live
    //
    NodeUnrecPtr stage_node = makeNodeFor(stage);
    stage_node->addChild(visit_node);

    //
    //   root
    //    |
    //    +- SimpleStage
    //            |
    //            +- VisitSubTree -> ApplicationScene
    //
    NodeUnrecPtr root = makeCoredNode<Group>();
    root->addChild(stage_node);

    //
    // Give the root node a place to live, i.e. create a passive
    // viewport and add it to the window.
    //
    ViewportUnrecPtr stage_viewport = PassiveViewport::create();
    stage_viewport->setRoot      (stage_node);
    stage_viewport->setBackground(vp->getBackground());
    stage_viewport->setCamera    (vp->getCamera());

    win->addPort(stage_viewport);

    mgr->update();
    win->renderNoFinish(mgr->getRenderAction());
    win->frameExit();
    win->deactivate ();

    //ImageUnrecPtr col_image = Image::create();
    //col_image->set(Image::OSG_RGBA_PF, width, height);
        
    //TextureObjChunk* texObj = spSimpleFBO->colorTexObj(0);
    //texObj->getImage()->subImage(0, 0, 0, width, height, 1, col_image);
    //col_image->write("d:/my_Test_opensg.png");

    win->subPortByObj(stage_viewport);
}
コード例 #29
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

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

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

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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


    //Print key command info
    std::cout << "\n\nKEY COMMANDS:" << std::endl;
    std::cout << "CTRL-Q  Exit\n\n" << std::endl;


    //SkeletonDrawer System Material
    LineChunkUnrecPtr ExampleLineChunk = LineChunk::create();
    ExampleLineChunk->setWidth(2.0f);
    ExampleLineChunk->setSmooth(true);

    BlendChunkUnrecPtr ExampleBlendChunk = BlendChunk::create();
    ExampleBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    ExampleBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkUnrecPtr ExampleMaterialChunk = MaterialChunk::create();
    ExampleMaterialChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
    ExampleMaterialChunk->setDiffuse(Color4f(0.0f,0.0f,0.0f,1.0f));
    ExampleMaterialChunk->setSpecular(Color4f(0.0f,0.0f,0.0f,1.0f));

    ChunkMaterialUnrecPtr ExampleMaterial = ChunkMaterial::create();
    ExampleMaterial->addChunk(ExampleLineChunk);
    ExampleMaterial->addChunk(ExampleMaterialChunk);
    ExampleMaterial->addChunk(ExampleBlendChunk);

    //Joint Node Hierarchy
    NodeRecPtr ExampleJointNode;

    //Create a new skeleton
    SkeletonBlendedGeometryRecPtr ExampleSkeleton;

    //Load skeleton from an XML file
    FCFileType::FCPtrStore NewContainers;
    NewContainers = FCFileHandler::the()->read(BoostPath("./Data/14Skeleton.xml"));

    FCFileType::FCPtrStore::iterator Itor;
    for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor)
    {
        //We only want the skeleton; ignore anything else saved in the XML file
        if( (*Itor)->getType() == (SkeletonBlendedGeometry::getClassType()))
        {
            ExampleSkeleton = (dynamic_pointer_cast<SkeletonBlendedGeometry>(*Itor));
        }

        if( (*Itor)->getType() == (Node::getClassType()) && 
            (dynamic_pointer_cast<Node>(*Itor)->getParent() == NULL))
        {
            ExampleJointNode = (dynamic_pointer_cast<Node>(*Itor));
        }
    }



    //SkeletonDrawer
    SkeletonDrawableUnrecPtr ExampleSkeletonDrawable = SkeletonDrawable::create();
    ExampleSkeletonDrawable->setSkeleton(ExampleSkeleton);
    ExampleSkeletonDrawable->setMaterial(ExampleMaterial);

    //Skeleton Node 
    NodeUnrecPtr SkeletonNode = Node::create();
    SkeletonNode->setCore(ExampleSkeletonDrawable);


    // Make Main Scene Node and add the Torus
    NodeUnrecPtr scene = Node::create();
    scene->setCore(Group::create());
    scene->addChild(SkeletonNode);

    mgr->setRoot(scene);

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


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "14SkeletonLoader");

    //Main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
コード例 #30
0
Node *
ColladaNode::createInstanceJoint(ColladaInstInfo *colInstInfo, domNode *node)
{
    NodeUnrecPtr retVal    = NULL;
    bool         startSkel = false;

    // if there is a ColladaInstanceElement someone tried to use <instance_node>
    // with this joint as target - this is currently not supported
    if(colInstInfo->getColInst() != NULL)
    {
        SWARNING << "ColladaNode::createInstanceJoint: <instance_node> with "
                 << "target <node> of type JOINT not supported." << std::endl;
        return retVal;
    }

    NodeLoaderState *state =
        getGlobal()->getLoaderStateAs<NodeLoaderState>(_loaderStateName);
    OSG_ASSERT(state != NULL);

    state->pushNodePath(node->getId() != NULL ? node->getId() : "");
    state->dumpNodePath();

    InstData instData;
    instData._nodePath = state->getNodePath();
    instData._skel     = state->getSkeleton();

    if(instData._skel == NULL)
    {
        startSkel      = true;
        instData._skel = Skeleton::create();

        state->setSkeleton(instData._skel);
        state->setJointId (0             );

        OSG_COLLADA_LOG(("ColladaNode::createInstanceJoint: id [%s] "
                         "root joint\n", node->getId()));
    }
    else
    {
        state->setJointId(state->getJointId() + 1);

        OSG_COLLADA_LOG(("ColladaNode::createInstanceJoint: id [%s] "
                         "joint [%d]\n", node->getId(), state->getJointId()));
    }

    const daeElementRefArray &contents = node->getContents();

    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]), instData);
            break;

        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]), instData);
            break;

        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]), instData);
            break;

        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]), instData);
            break;
        }
    }

    // assert top and bottom are both set or both unset
    OSG_ASSERT((instData._topN != NULL && instData._bottomN != NULL) ||
               (instData._topN == NULL && instData._bottomN == NULL)   );

    if(instData._topN == NULL && instData._bottomN == NULL)
    {
        // no xforms were created, make a SkeletonJoint for this <node>

        SkeletonJointUnrecPtr joint = SkeletonJoint::create();

        joint->setJointId(state->getJointId());

        instData._topN    = makeNodeFor(joint);
        instData._bottomN = instData._topN;

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(instData._topN, node->getName());
        }
    }
    else if(getGlobal()->getOptions()->getMergeTransforms() == false)
    {
        // when not merging transforms add SkeletonJoint core now

        SkeletonJointUnrecPtr joint  = SkeletonJoint::create();
        NodeUnrecPtr          jointN = makeNodeFor(joint);

        joint->setJointId(state->getJointId());

        instData._bottomN->addChild(jointN);
        instData._bottomN = jointN;
    }

    if(startSkel == true)
    {
        // add a transform for the world matrix up to this node to put
        // the Skeleton in the correct coordinate system

        TransformUnrecPtr xform  = Transform::create();
        NodeUnrecPtr      xformN = makeNodeFor(xform);

        xform->setMatrix(state->getWorldMatrix());

        xformN->addChild(instData._topN);
        instData._topN = xformN;

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true)
            setName(xformN, "SkeletonWorldMatrix");
    }

    // update world matrix before we instantiate child nodes, etc.
    state->pushMatrix(instData._localMatrix);

    // add <node> child elements
    const domNode_Array &nodes = node->getNode_array();

    for(UInt32 i = 0; i < nodes.getCount(); ++i)
        handleNode(nodes[i], instData);

    // add <instance_node> child elements
    const domInstance_node_Array &instNodes =
        node->getInstance_node_array();

    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
        handleInstanceNode(instNodes[i], instData);

    // we don't handle other <instance_*> tags here, it does not
    // make sense to have them inside a skeleton

    editInstStore().push_back(instData._topN);
    _instDataStore .push_back(instData      );
    retVal = instData._topN;

    if(startSkel == true)
    {
        instData._skel->pushToRoots(instData._topN);

        state->setSkeleton(NULL);
        state->setJointId (SkeletonJoint::INVALID_JOINT_ID);
    }

    state->popMatrix  ();
    state->popNodePath();

    return retVal;
}