示例#1
0
文件: Main.cpp 项目: fohr/Graphtane
	RenderTextureTargetPtr createDepthTarget(const CameraPtr& camera, int width, int height)
	{
		ImageTextureConfig config = ImageTextureConfig::createDefault();
		config.width = width;
		config.height = height;
		config.textureAddressMode = TextureAddressMode_Clamp;
		config.format = PixelFormat_DepthComponent24;

		TexturePtr texture(new Texture(config));

		RenderTextureTargetPtr target;

		{
			RenderTextureTargetConfig config;
			config.texture = texture;
			config.attachment = FrameBufferAttachment_Depth;
			config.techniqueCategory = TechniqueCategory_DepthRtt;
			target.reset(new RenderTextureTarget(config));

			{
				ViewportPtr viewport = target->addDefaultViewport(m_camera);
				viewport->setBackgroundColor(glm::vec4(1,1,1,1));
			}

			m_window->addRenderTarget(target);
		}
		return target;
	}
// redraw the window
void display(void)
{
    mgr->getNavigator()->updateCameraTransformation();

    mgr->getWindow()->activate();
    mgr->getWindow()->frameInit();

    raction->setWindow(getCPtr(mgr->getWindow()));

    ViewportPtr viewport = mgr->getWindow()->getPort(0);

    glClear(GL_ACCUM_BUFFER_BIT);

    for (int i=0; i < JITTERSIZE[activeJitter]; i++) {
        beginEditCP(cameraDecorator);
            cameraDecorator->setOffset(
                (JITTER[activeJitter][i].x() - 0.5) * jitterRadius,
                (JITTER[activeJitter][i].y() - 0.5) * jitterRadius);
        endEditCP(cameraDecorator);

        viewport->render(raction);
    
        glAccum(GL_ACCUM, 1.0f / float(JITTERSIZE[activeJitter]));
        glAccum(GL_RETURN, float(JITTERSIZE[activeJitter]) / float(i + 1));
    }

    glAccum(GL_RETURN, 1.0f);

    mgr->getWindow()->swap();
    mgr->getWindow()->frameExit();
}
	void setCamera(CameraPtr c)
	{
		_camera = c;
		ViewportPtr vp = _win->getPort(0);
		beginEditCP(vp);
			vp->setCamera(_camera);
		endEditCP(vp);

	}
示例#4
0
void StudyPropertiesDlg::Apply()
{
	// set properties based on state of controls in General page
	m_studyLayer->SetName(m_txtLayerName->GetValue().c_str());
	m_studyLayer->SetDescription(m_txtLayerDescription->GetValue().c_str());
	m_studyLayer->SetAuthours(m_txtAuthours->GetValue().c_str());

	// set properties based on state of controls in Projection page
	StudyControllerPtr studyController = m_studyLayer->GetStudyController();
	studyController->SetDatum(m_cboDatum->GetValue().wc_str());
	studyController->SetProjection(m_cboProjection->GetValue().wc_str());

	ViewportPtr viewport = App::Inst().GetViewport();

	// set properties based on state of controls in Symbology page
	viewport->SetBackgroundColour( Colour( m_colourBackground->GetColour() ) );

	if(m_cboTerrainResolution->GetValue() == _T("256"))
		viewport->SetMaxTerrainResolution(256);
	else if(m_cboTerrainResolution->GetValue() == _T("512"))
		viewport->SetMaxTerrainResolution(512);
	else if(m_cboTerrainResolution->GetValue() == _T("1024"))
		viewport->SetMaxTerrainResolution(1024);
	else if(m_cboTerrainResolution->GetValue() == _T("2048"))
		viewport->SetMaxTerrainResolution(2048);
	else if(m_cboTerrainResolution->GetValue() == _T("4096"))
		viewport->SetMaxTerrainResolution(4096);
	else if(m_cboTerrainResolution->GetValue() == _T("8196"))
		viewport->SetMaxTerrainResolution(8196);

	App::Inst().SetSaveStatus( SESSION_NOT_SAVED );
	viewport->Refresh( false );
	App::Inst().GetLayerTreeController()->SetName(m_studyLayer, m_studyLayer->GetName());
}
void SkyBackgroundPluginForm::on_enableCheckBox_toggled( bool checked )
{
	vrOSGWidget *gl = vrOSGWidget::getMGLW(-1);
	ViewportPtr vredViewport = gl->getViewport();
	beginEditCP(vredViewport);
	if (checked && skyBackground != NullFC)
		vredViewport->setBackground(skyBackground);
	else if (oldBackground != NullFC)
		vredViewport->setBackground(oldBackground);
	endEditCP(vredViewport);

	enableCheckBox->setChecked(checked); // for scripting
}
示例#6
0
文件: Canvas.cpp 项目: artcom/y60
ViewportPtr
Canvas::getViewportAt(const unsigned int theX, const unsigned int theY) const {
    int myViewportCount = getNode().childNodesLength(VIEWPORT_NODE_NAME);
    for (int i = myViewportCount-1; i >= 0; --i) {
        dom::NodePtr myViewportNode = getNode().childNode(VIEWPORT_NODE_NAME,i);
        ViewportPtr myViewport = myViewportNode->getFacade<Viewport>();
        int myTop = 0;
        int myLeft = 0;
        unsigned int myWidth = 0;
        unsigned int myHeight = 0;
        if (myViewport->getTop(myTop) && myViewport->getHeight(myHeight) && 
            myViewport->getWidth(myWidth) && myViewport->getLeft(myLeft) && 
            myTop <= static_cast<int>(theY) &&
            myHeight + myTop >= theY &&
            myLeft <= static_cast<int>(theX) &&
            myLeft + myWidth >= theX)
        {
            return myViewport;
        }
    }
    return ViewportPtr(0);
}
示例#7
0
void OpenSGWidget::initializeGL()
{
    pwin->init();

    // create a gradient background.
    GradientBackgroundPtr gback = GradientBackground::create();
    beginEditCP(gback, GradientBackground::LineFieldMask);
        gback->clearLines();
        gback->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gback->addLine(Color3f(0.0, 0.1, 0.3), 1);
    endEditCP(gback, GradientBackground::LineFieldMask);

    beginEditCP(pwin);
        for(int i=0;i<pwin->getPort().size();++i)
        {
            ViewportPtr vp = pwin->getPort()[i];
            beginEditCP(vp);
                vp->setBackground(gback);
            endEditCP(vp);
        }
    endEditCP(pwin);

    _initialized = true;
}
SkyBackgroundPluginForm::SkyBackgroundPluginForm( QWidget* parent /*= 0*/, const char* name /*= 0*/, WFlags fl /*= 0*/ )
	: SkyBackgroundPluginFormBase(parent, name, fl)
{

	settings.setPath("UFZ", "VRED-SkyBackgroundPlugin");

	skyDir = QDir(settings.readEntry("presetDir", "D:/Data/SkyBackgrounds"));
	presetDirLineEdit->setText(skyDir.absPath());

	presetDirs[0] = QDir("NiceDay");
	//presetDirs[1] = QDir("NiceDay/1024");
	//presetDirs[2] = QDir("NiceDay/512");

	skyBackground = NullFC;
	vrOSGWidget *gl = vrOSGWidget::getMGLW(-1);
	ViewportPtr vredViewport = gl->getViewport();
	oldBackground = vredViewport->getBackground();

	for (int i = 0; i < 6; i++)
	{
		images[i] = Image::create();

		textures[i] = TextureChunk::create();
		beginEditCP(textures[i]);
		textures[i]->setMinFilter( GL_LINEAR );
		textures[i]->setMagFilter( GL_LINEAR );
		textures[i]->setWrapS    ( GL_CLAMP_TO_EDGE );	// other clamping causes black seams on the edges
		textures[i]->setWrapT    ( GL_CLAMP_TO_EDGE );	// of the sky cube because of gl_linear filtering
		textures[i]->setWrapR    ( GL_CLAMP_TO_EDGE );
		textures[i]->setEnvMode  ( GL_REPLACE );
		endEditCP(textures[i]);
	}

	LightDistanceExSlider->setRange(1, 10000);
	LightDistanceExSlider->setValue(1000);
}
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);

    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);
    TutorialUpdateListener TheTutorialUpdateListener;
    TutorialWindowEventProducer->addUpdateListener(&TheTutorialUpdateListener);


    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(MainWindow);
	
    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
        scene->addChild(TorusGeometryNode);
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);


    // Create the Graphics
    GraphicsPtr TutorialGraphics = osg::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

    DefaultDialogComponentGeneratorPtr TutorialDialogGenerator = DefaultDialogComponentGenerator::create();

    ButtonFont = osg::UIFont::create();

    beginEditCP(ButtonFont, UIFont::SizeFieldMask);
        ButtonFont->setSize(16);
    endEditCP(ButtonFont, UIFont::SizeFieldMask);

    ButtonPtr Response = osg::Button::create();
    beginEditCP(Response, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask );
            Response->setMinSize(Vec2f(50, 25));
            Response->setMaxSize(Vec2f(200, 100));
            Response->setPreferredSize(Vec2f(100, 50));
            Response->setToolTipText("These buttons are for selecting a response!");

            Response->setFont(ButtonFont);
            Response->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            Response->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
            Response->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
    endEditCP(Response, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask );

    LabelPtr LabelPrototype = Label::create();
    LabelPrototype->setAlignment(Pnt2f(0.5f,0.5f));
    LabelPrototype->setPreferredSize(Pnt2f(250.0,30.0));

    DialogInterfacePtr TutorialDialogInterface = osg::DialogInterface::create();

    beginEditCP(TutorialDialogGenerator, DefaultDialogComponentGenerator::ResponseButtonPrototypeFieldMask | DefaultDialogComponentGenerator::QuestionPrototypeFieldMask);
        TutorialDialogGenerator->setResponseButtonPrototype(Response);
        TutorialDialogGenerator->setQuestionPrototype(LabelPrototype);
    endEditCP(TutorialDialogGenerator, DefaultDialogComponentGenerator::ResponseButtonPrototypeFieldMask | DefaultDialogComponentGenerator::QuestionPrototypeFieldMask);

    TutorialDialog = osg::DialogHierarchy::create();

    beginEditCP(TutorialDialog, DialogHierarchy::DualNodeStyleFieldMask);
        TutorialDialog->setDualNodeStyle(true);
    endEditCP(TutorialDialog, DialogHierarchy::DualNodeStyleFieldMask);

    DialogPtr rootDialog = TutorialDialog->addDialog("Which do you prefer?", 0.0, NullFC, true, NullFC);

    DialogPtr RootDialogChildA = TutorialDialog->addDialog("Foreground", 0.0, NullFC, false, rootDialog);
    DialogPtr RootDialogChildB = TutorialDialog->addDialog("Background", 0.0, NullFC, false, rootDialog);
    
    DialogPtr SelectableDialogChildA = TutorialDialog->addDialog("What color would you like the forground to be?", 0.0, NullFC, true, RootDialogChildA);
    DialogPtr SelectableDialogChildB = TutorialDialog->addDialog("What object do you want to be in the background?", 0.0, NullFC, true, RootDialogChildB);

    ADialogChildA = TutorialDialog->addDialog("Blue", 0.0, NullFC, false, SelectableDialogChildA);
    ADialogChildB = TutorialDialog->addDialog("Red", 0.0, NullFC, false, SelectableDialogChildA);

    BDialogChildA = TutorialDialog->addDialog("Square", 0.0, NullFC, false, SelectableDialogChildB);
    BDialogChildB = TutorialDialog->addDialog("Sphere", 0.0, NullFC, false, SelectableDialogChildB);

    DialogPtr RestartEnd1 = TutorialDialog->addDialog("What would you like to do?", 0.0, NullFC, true, ADialogChildA);
    DialogPtr RestartEnd2 = TutorialDialog->addDialog("What would you like to do?", 0.0, NullFC, true, ADialogChildB);
    DialogPtr RestartEnd3 = TutorialDialog->addDialog("What would you like to do?", 0.0, NullFC, true, BDialogChildA);
    DialogPtr RestartEnd4 = TutorialDialog->addDialog("What would you like to do?", 0.0, NullFC, true, BDialogChildB);

    Restart1 = TutorialDialog->addDialog("Restart", 0.0, NullFC, false, RestartEnd1);
    End1 = TutorialDialog->addDialog("End", 0.0, NullFC, false, RestartEnd1);
    Restart2 = TutorialDialog->addDialog("Restart", 0.0, NullFC, false, RestartEnd2);
    End2 = TutorialDialog->addDialog("End", 0.0, NullFC, false, RestartEnd2);
    Restart3 = TutorialDialog->addDialog("Restart", 0.0, NullFC, false, RestartEnd3);
    End3 = TutorialDialog->addDialog("End", 0.0, NullFC, false, RestartEnd3);
    Restart4 = TutorialDialog->addDialog("Restart", 0.0, NullFC, false, RestartEnd4);
    End4 = TutorialDialog->addDialog("End", 0.0, NullFC, false, RestartEnd4);

    TutorialDialogListener TheTutorialDialogListener;
    rootDialog->addDialogListener(&TheTutorialDialogListener);
    RootDialogChildA->addDialogListener(&TheTutorialDialogListener);
    RootDialogChildB->addDialogListener(&TheTutorialDialogListener);
    ADialogChildA->addDialogListener(&TheTutorialDialogListener);
    ADialogChildB->addDialogListener(&TheTutorialDialogListener);
    BDialogChildA->addDialogListener(&TheTutorialDialogListener);
    BDialogChildB->addDialogListener(&TheTutorialDialogListener);
    Restart1->addDialogListener(&TheTutorialDialogListener);
    End1->addDialogListener(&TheTutorialDialogListener);
    Restart2->addDialogListener(&TheTutorialDialogListener);
    End2->addDialogListener(&TheTutorialDialogListener);
    Restart3->addDialogListener(&TheTutorialDialogListener);
    End3->addDialogListener(&TheTutorialDialogListener);
    Restart4->addDialogListener(&TheTutorialDialogListener);
    End4->addDialogListener(&TheTutorialDialogListener);

    SelectableDialogChildA->addDialogListener(&TheTutorialDialogListener);
    SelectableDialogChildB->addDialogListener(&TheTutorialDialogListener);
    RestartEnd1->addDialogListener(&TheTutorialDialogListener);
    RestartEnd2->addDialogListener(&TheTutorialDialogListener);
    RestartEnd3->addDialogListener(&TheTutorialDialogListener);
    RestartEnd4->addDialogListener(&TheTutorialDialogListener);
    
    LayoutPtr MainInternalWindowLayout = osg::FlowLayout::create();
    
    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    MainInternalWindowBackground = osg::ColorLayer::create();
    MainInternalWindow = osg::InternalWindow::create();
    beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
	beginEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);
    endEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);

    beginEditCP(TutorialDialogInterface, DialogInterface::ComponentGeneratorFieldMask | DialogInterface::ParentContainerFieldMask | DialogInterface::SourceDialogHierarchyFieldMask);
        TutorialDialogInterface->setComponentGenerator(TutorialDialogGenerator);
        TutorialDialogInterface->setParentContainer(MainInternalWindow);
        TutorialDialogInterface->setSourceDialogHierarchy(TutorialDialog);
    endEditCP(TutorialDialogInterface, DialogInterface::ComponentGeneratorFieldMask | DialogInterface::ParentContainerFieldMask | DialogInterface::SourceDialogHierarchyFieldMask);

    // Create the Drawing Surface
    UIDrawingSurfacePtr TutorialDrawingSurface = UIDrawingSurface::create();
    beginEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindowEventProducer);
    endEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);
	
	// Create the UI Foreground Object
    UIForegroundPtr TutorialUIForeground = osg::UIForeground::create();

    beginEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);
        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
    endEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);

    mgr->setRoot(scene);

    // Add the UI Foreground Object to the Scene
    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialUIForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

    // Show the whole Scene
    mgr->showAll();
    SoundManager::the()->setCamera(mgr->getCamera());

    TutorialDialog->start();

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

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

    osgExit();

    return 0;
}
示例#10
0
int main(int argc, char **argv)
{
    for(int i = 0; i < argc; i++)
    {
        std::cout << "Param " << i << ":" << argv[i] << std::endl;
    }

    OSG::osgInit(argc, argv);

    const char    *inFileName = "tie.bin";

    if(argc > 1)
        inFileName = argv[1];

    std::ifstream in(inFileName, std::ios::binary);
    if(!in)
    {
        std::cerr <<
            "ERROR: Cannot open file " <<
            inFileName <<
            "" <<
            std::endl;
        return -1;
    }

    OSG::BINLoader loader(in);
    loader.read();
    in.close();
    std::cout <<
        "MAIN: " <<
        getContainerId(loader.getRootNode()) <<
        " is root" <<
        std::endl;

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);
    glDisable(GL_LIGHTING);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glClearColor(0.5, 0.5, 0.5, 1.);

    // OSG
    //    OSGSceneFileHandler::the().print();
    //    FhsFile::touch();
    // create the graph
    // beacon for camera and light
    NodePtr     b1n = Node::create();
    GroupPtr    b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore(b1);
    endEditCP(b1n);

    // transformation
    NodePtr         t1n = Node::create();
    TransformPtr    t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore(t1);
    t1n->addChild(b1n);
    endEditCP(t1n);

    cam_trans = t1;

    // light
    NodePtr dlight = Node::create();
    headlight = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore(headlight);
    endEditCP(dlight);

    beginEditCP(headlight);
    headlight->setAmbient(.3, .3, .3, 1);
    headlight->setDiffuse(1, 1, 1, 1);
    headlight->setSpecular(1, 1, 1, 1);
    headlight->setDirection(0, 0, 1);
    headlight->setBeacon(b1n);
    endEditCP(headlight);

    // root
    root = Node::create();

    GroupPtr    gr1 = Group::create();
    beginEditCP(root);
    root->setCore(gr1);
    root->addChild(t1n);
    root->addChild(dlight);
    endEditCP(root);

    // Load the file
    NodePtr     fileRoot = Node::create();

    //  OSGActivateColMatPtr colMat = OSGActivateColMat::create();
    GroupPtr    gr = Group::create();

    beginEditCP(fileRoot);

    //  fileRoot->setCore(colMat);
    fileRoot->setCore(gr);
    endEditCP(fileRoot);

    beginEditCP(dlight);
    dlight->addChild(fileRoot);
    endEditCP(dlight);

    //   for(UInt32 numFiles = 1; numFiles < argc; numFiles++)
    //    {
    //       file = SceneFileHandler::the().read(argv[1]);
    file = loader.getRootNode();
    beginEditCP(fileRoot);
    fileRoot->addChild(file);
    fileRoot->invalidateVolume();
    endEditCP(fileRoot);

    //    }
    dlight->updateVolume();

    Vec3f   min, max;
    dlight->getVolume().getBounds(min, max);

    std::cout << "Volume: from " << min << " to " << max << std::endl;

    //std::cerr << "Tree: " << std::endl;
    //root->dump();
    // Camera
    PerspectiveCameraPtr    cam = PerspectiveCamera::create();

    cam->setBeacon(b1n);
    cam->setFov(deg2rad(60));
    cam->setNear(1.);
    cam->setFar(100000.);

    // Background
    GradientBackgroundPtr   bkgnd = GradientBackground::create();

    bkgnd->addLine(Color3f(0, 0, 0), 0);
    bkgnd->addLine(Color3f(.5, .5, 0), 0.5);
    bkgnd->addLine(Color3f(.7, .7, 1), 0.5);
    bkgnd->addLine(Color3f(0, 0, 1), 1);

    // Viewport
    ViewportPtr vp = Viewport::create();
    vp->setCamera(cam);
    vp->setBackground(bkgnd);
    vp->setRoot(root);
    vp->setSize(0, 0, 1, 1);

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr   gwin;

    GLint           glvp[4];
    glGetIntegerv(GL_VIEWPORT, glvp);

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize(glvp[2], glvp[3]);

    win = gwin;

    win->addPort(vp);

    // Actions
    dact = DrawAction::create();
    ract = RenderAction::create();

    // tball
    /*
	Vec3f pos(min[0] + 0.5 * (max[0] - min[0]),
              min[1] + 0.5 * (max[1] - min[1]),
              max[2] + 1.5 * (max[2] - min[2]));
*/
    Vec3f   pos(0, 0, max[2] + 1.5 * (max[2] - min[2]));

    tball.setMode(Trackball::OSGObject);
    tball.setStartPosition(pos, true);
    tball.setSum(true);
    tball.setTranslationMode(Trackball::OSGFree);
    tball.setTranslationScale(10000.);

    // run...
    glutMainLoop();

    return 0;
}
void SkyBackgroundPluginForm::setupSkyBackground( const QDir dir, const bool zUp )
{	
	try
	{
		skyBackground = NullFC;
		
		bool imageLoaded[6] = {false, false, false, false, false, false};

		const QFileInfoList* fileList = dir.entryInfoList();
		QFileInfoListIterator it(*fileList);
		QFileInfo* fileInfo;

		while ((fileInfo = it.current()) != 0)
		{
			QString qstr = fileInfo->absFilePath();
			const char *filename = qstr.latin1();

			if (((qstr.find("north") >= 0) || (qstr.find("front") >= 0)) && !imageLoaded[0])
			{
				beginEditCP(images[5]);
				if (images[5]->read(filename))
				{
					beginEditCP(textures[5]);
					textures[5]->setImage(images[5]);
					endEditCP(textures[5]);
					vrLog::info("Sky Background: Front/North image loaded.");
					imageLoaded[0] = true;
				}
				endEditCP(images[5]);
			}
			if (((qstr.find("south") >= 0) || (qstr.find("back") >= 0)) && !imageLoaded[1])
			{
				beginEditCP(images[4]);
				if (images[4]->read(filename))
				{
					if (zUp)
						vrImage::rotateImage180Degrees(images[4]);
					beginEditCP(textures[4]);
					textures[4]->setImage(images[4]);
					endEditCP(textures[4]);
					vrLog::info("Sky Background: Back/South image loaded.");
					imageLoaded[1] = true;
				}
				endEditCP(images[4]);
			}
			if (((qstr.find("down") >= 0) || (qstr.find("bottom") >= 0)) && !imageLoaded[2])
			{
				beginEditCP(images[3]);
				if (images[3]->read(filename))
				{
					beginEditCP(textures[3]);
					textures[3]->setImage(images[3]);
					endEditCP(textures[3]);
					vrLog::info("Sky Background: Bottom/Down image loaded.");
					imageLoaded[2] = true;
				}
				endEditCP(images[3]);
			}
			if (((qstr.find("up") >= 0) || (qstr.find("top") >= 0)) && !imageLoaded[3])
			{
				beginEditCP(images[2]);
				if (images[2]->read(filename))
				{
					if (zUp)
						vrImage::rotateImage180Degrees(images[2]);
					beginEditCP(textures[2]);
					textures[2]->setImage(images[2]);
					endEditCP(textures[2]);
					vrLog::info("Sky Background: Top/Up image loaded.");
					imageLoaded[3] = true;
				}
				endEditCP(images[2]);
			}
			if (((qstr.find("east") >= 0) || (qstr.find("right") >= 0)) && !imageLoaded[4])
			{
				beginEditCP(images[1]);
				if (images[1]->read(filename))
				{
					if (zUp)
						vrImage::rotate90Left(images[1]);
					beginEditCP(textures[1]);
					textures[1]->setImage(images[1]);
					endEditCP(textures[1]);
					vrLog::info("Sky Background: Right/East image loaded.");
					imageLoaded[4] = true;
				}
				endEditCP(images[1]);
			}
			if (((qstr.find("west") >= 0) || (qstr.find("left") >= 0)) && !imageLoaded[5])
			{
				beginEditCP(images[0]);
				if (images[0]->read(filename))
				{
					if (zUp)
						vrImage::rotate90Right(images[0]);
					beginEditCP(textures[0]);
					textures[0]->setImage(images[0]);
					endEditCP(textures[0]);
					vrLog::info("Sky Background: Left/West image loaded.");
					imageLoaded[5] = true;
				}
				endEditCP(images[0]);
			}

			++it;
		}

		skyBackground = SkyBackground::create();
		beginEditCP(skyBackground);
		if (!zUp)
		{
			skyBackground->setFrontTexture(textures[5]);
			skyBackground->setBackTexture(textures[4]);
			skyBackground->setBottomTexture(textures[3]);
			skyBackground->setTopTexture(textures[2]);
			skyBackground->setRightTexture(textures[1]);
			skyBackground->setLeftTexture(textures[0]);
		}
		else
		{
			skyBackground->setFrontTexture(textures[3]);
			skyBackground->setBackTexture(textures[2]);
			skyBackground->setBottomTexture(textures[4]);
			skyBackground->setTopTexture(textures[5]);
			skyBackground->setRightTexture(textures[1]);
			skyBackground->setLeftTexture(textures[0]);
		}
		endEditCP(skyBackground);

		vrOSGWidget *gl = vrOSGWidget::getMGLW(-1);
		ViewportPtr vredViewport = gl->getViewport();
		//oldBackground = vredViewport->getBackground();
		beginEditCP(vredViewport);
		vredViewport->setBackground(skyBackground);
		endEditCP(vredViewport);

		directoryLineEdit->setText(dir.absPath());

		// read light settings
		if (SetLightingCheckBox->isChecked())
		{
			string lightName = LightNameLineEdit->text().ascii();
			if (!QFile::exists(dir.absPath() + "/LightSettings.xml"))
				vrLog::warning("Light Settings not found.");
			else
			{
				QFile* file = new QFile(dir.absPath() + "/LightSettings.xml");
				if (file->open(IO_ReadOnly))
				{
					LightSettingsHandler handler;
					QXmlSimpleReader reader;
					reader.setContentHandler(&handler);
					reader.setErrorHandler(&handler);
					QXmlInputSource source(file);
					reader.parse(source);
					file->close();
					handler.direction.normalize();

					vector<NodePtr> lights;
					vrLights::getLights(lights);
					bool lightSet = false;
					for (vector<NodePtr>::const_iterator it = lights.begin();
						it != lights.end(); ++it)
					{
						LightPtr light = LightPtr::dcast((*it)->getCore());
						if (light != NullFC)
						{
							NodePtr node = *it;
							string name = getName(node);
							if (name.find(lightName) != string::npos)
							{
								setLightSettings(light, handler);
								lightSet = true;
							}
						}
					}

					if (!lightSet)
					{
						NodePtr rootNode = vrScenegraph::getRoot();

						TransformPtr beaconTransform = Transform::create();
						NodePtr beaconNode = Node::create();
						beginEditCP(beaconNode);
						beaconNode->setCore(beaconTransform);
						endEditCP(beaconNode);

						PointLightPtr light = PointLight::create();
						beginEditCP(light);
						light->setAttenuation(1,0,0);
						light->setBeacon(beaconNode);
						endEditCP(light);
						NodePtr lightNode = Node::create();
						beginEditCP(lightNode);
						lightNode->setCore(light);
						endEditCP(lightNode);
						OSG::setName(lightNode, lightName);

						beginEditCP(rootNode);
						rootNode->addChild(lightNode);
						rootNode->addChild(beaconNode);
						endEditCP(rootNode);

						setLightSettings(light, handler);

						vrScenegraph::update(true);
					}

				}
			}
		}
	}
	catch (std::exception const& e)
	{
		cout << "type: " << typeid(e).name() << endl;
		cout << "message: " << e.what() << endl << endl;
	}
}
示例#12
0
文件: Editor.cpp 项目: sundoom/glow
VOID Editor::Run()
{
	// check the window rect
	RECT wnd_rc; ::GetClientRect(mWnd, &wnd_rc);
	I32 wnd_width = wnd_rc.right-wnd_rc.left;
	I32 wnd_height = wnd_rc.bottom-wnd_rc.top;
	if(wnd_width<=0||wnd_height<=0) return;

	// get the frame time
	static U32 system_time = Timer::instance().time();
	U32 current_time = Timer::instance().time();
	U32 frame_time = current_time - system_time;
	if(frame_time == 0) return;
	system_time = current_time;

	if(mGraphPtr==NULL) return;

	// reset the render context
	mGraphPtr->Reset();

	// get the window rect	
	Vector4 rect = Vector4(wnd_rc.left, wnd_rc.top, wnd_rc.right, wnd_rc.bottom);

	// set the viewport
	mGraphPtr->viewport(rect);
	ViewportPtr viewport = GNEW(Viewport(rect[0],rect[1],rect[2],rect[3])); CHECK(viewport);
	mGraphPtr->draw(static_cast<Operation*>(viewport.Ptr()));

	// set the scissor
	ScissorPtr scissor = GNEW(Scissor(rect[0],rect[1],rect[2],rect[3]));
	mGraphPtr->draw(static_cast<Operation*>(scissor.Ptr()));

	// clear the target and the zbuffer
	ClearPtr clear = GNEW(Clear(Clear::CT_COLOR|Clear::CT_DEPTH,Vector4(0.5,0.5,0.5,1.0),1.0f)); CHECK(clear);
	mGraphPtr->draw(static_cast<Operation*>(clear.Ptr()));

	// make the projection and the view
	F32 left	= -P2U(wnd_width/2)*mScale;
	F32 right	= P2U(wnd_width/2)*mScale;
	F32 bottom	= -P2U(wnd_height/2)*mScale;
	F32 top		= P2U(wnd_height/2)*mScale;
	F32 znear	= -512.0;
	F32 zfar	= 512.0;
	mGraphPtr->projection(Matrix::makeOrtho(left,right,bottom,top,znear,zfar));
	mGraphPtr->view(Matrix::makeTranslate(-mEye));

	// draw the map
	if(mMapPtr)
	{
		// update the map
		Vector3 start(rect[0], rect[1], 0);
		mGraphPtr->unproject(start, start);
		Vector3 end(rect[2], rect[3], 0);
		mGraphPtr->unproject(end, end);
		mMapPtr->Update(Vector4(start[0], start[1], end[0], end[1]));

		// draw the map
		mMapPtr->Draw(mGraphPtr.Ptr());

		// draw the reference line
		if(mDrawGrid)
		{
			mMapPtr->DrawReferenceLine(mGraphPtr.Ptr());
		}		
	}	

	// draw the brush
	if(mBrushPtr) mBrushPtr->Draw(mGraphPtr.Ptr());

	// swap the graph buffer
	mGraphPtr->swap();

	// swap buffers
	eglSwapBuffers(mDisplay, mSurface);
}
示例#13
0
int main(int argc, char** argv)
{
    std::cout << "osgInit()..." << std::endl;
    osgInit( argc, argv );
    
    std::cout << "glutInit()..." <<  std::endl;
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
    int winID = glutCreateWindow("OpenSG");
    
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(resize);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);
            
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
    glClearColor( .3, .3, .8, 1 );
    
    std::cout << "Creating objects..." << std::endl;
    
    //BEACON
    NodePtr beaconNode = Node::create();
    GroupPtr beaconCore = Group::create();
    beginEditCP( beaconNode );
    beaconNode->setCore( beaconCore );
    endEditCP( beaconNode );
    
    /*
    //LIGHT
    NodePtr dlightNode = Node::create();
    DirectionalLightPtr dlightCore = DirectionalLight::create();
    beginEditCP(dlightNode);
    dlightNode->setCore(dlightCore);
    endEditCP(dlightNode);
    
    beginEditCP(dlightCore);
    dlightCore->setAmbient( .3, .3, .3, 1 );
    dlightCore->setDiffuse( .5, .5, .5, 1 );
    dlightCore->setDirection( 0, 0 , 1 );
    dlightCore->setBeacon( beaconNode );
    endEditCP(dlightCore);
    */
        
    //TRANSFORM
    NodePtr transNode = Node::create();
    TransformPtr transCore = Transform::create();
    beginEditCP( transNode );
    transNode->setCore( transCore );
    transNode->addChild( beaconNode );
    endEditCP( transNode );
    cam_trans = transCore;
    
    //LOD
    NodePtr lowDetailNode = makeBox( 1,1,1, 1,1,1 );
    GeometryPtr boxCore = GeometryPtr::dcast(lowDetailNode->getCore());
    SimpleMaterialPtr lowDetailMat = SimpleMaterial::create();
    lowDetailMat->setDiffuse( Color3f( 1,0,0 ) );
    lowDetailMat->setAmbient( Color3f( 1,0,0 ) );
    boxCore->setMaterial( lowDetailMat );
    
    NodePtr     medDetailNode = makeSphere( 1, 1 );
    GeometryPtr medSphereCore = GeometryPtr::dcast(medDetailNode->getCore());
    SimpleMaterialPtr medDetailMat = SimpleMaterial::create();
    medDetailMat->setDiffuse( Color3f( 0,1,0 ) );
    medDetailMat->setAmbient( Color3f( 0,1,0 ) );
    medSphereCore->setMaterial( medDetailMat );
    
    NodePtr highDetailNode = makeSphere( 2, 1 );
    GeometryPtr highSphereCore = GeometryPtr::dcast(highDetailNode->getCore());
    SimpleMaterialPtr highDetailMat = SimpleMaterial::create();
    highDetailMat->setDiffuse( Color3f( 0,0,1 ) );
    highDetailMat->setAmbient( Color3f( 0,0,1 ) );
    highDetailMat->setSpecular( Color3f(1, 1, 1) );
    highDetailMat->setShininess( 10 );
    highSphereCore->setMaterial( highDetailMat );
    
    NodePtr lodNode = Node::create();
    DistanceLODPtr lodNodeCore = DistanceLOD::create();
    beginEditCP(lodNode);
    lodNode->setCore(lodNodeCore);
    lodNode->addChild( highDetailNode );
    lodNode->addChild( medDetailNode );
    lodNode->addChild( lowDetailNode );
    endEditCP(lodNode);
    
    beginEditCP(lodNodeCore);
    lodNodeCore->editSFCenter()->setValue( Pnt3f(0, 0, 2) );
    lodNodeCore->editMFRange()->push_back( 4.0 );
    lodNodeCore->editMFRange()->push_back( 8.0 );
    lodNodeCore->editMFRange()->push_back( 11.0 );
    endEditCP(lodNodeCore);
    
        
    //TRANSFORM LOD
    NodePtr transLODNode = Node::create();
    TransformPtr transLODCore = Transform::create();
    transMat.setTranslate( 1, -1, -1 );
    beginEditCP(transLODCore);
    transLODCore->editSFMatrix()->setValue( transMat );
    endEditCP(transLODCore);
    beginEditCP( transLODNode );
    transLODNode->setCore( transLODCore );
    transLODNode->addChild( lodNode );
    endEditCP( transLODNode );
    
    
        
    //ROOT
    root = Node::create();
    GroupPtr rootCore = Group::create();
    beginEditCP(root);
    root->setCore(rootCore);
    root->addChild(transNode);
    root->addChild(transLODNode);
    endEditCP(root);
    
    
    
    camera = PerspectiveCamera::create();
    beginEditCP(camera);
    camera->setBeacon( beaconNode );
    camera->setFov( deg2rad(90) );
    camera->setNear( 0.1 );
    camera->setFar( 10000 );
    endEditCP(camera);
    
    SolidBackgroundPtr background = SolidBackground::create();
    
    viewp = Viewport::create();
    beginEditCP(viewp);
    viewp->setCamera( camera );
    viewp->setBackground( background );
    viewp->setRoot( root );
    viewp->setSize( 0,0, 1,1 );
    endEditCP(viewp);
    
    GLint glVP[4];
    glGetIntegerv( GL_VIEWPORT, glVP );
    
    GLUTWindowPtr gwin = GLUTWindow::create();
    gwin->setId(winID);
    gwin->setSize(glVP[2], glVP[3]);
    
    window = gwin;
    beginEditCP(window);
    window->addPort( viewp );
    window->init();
    endEditCP(window);
    
    drAct = DrawAction::create();
    
    Vec3f pos( 0, 0, 3 );
    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );

    glutMainLoop();
    return 0;
}
示例#14
0
int main(int argc, char **argv)
{
    osgInit(argc,argv);

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

    GLUTWindowPtr gwin=GLUTWindow::create();
    gwin->setId(id);
    gwin->init();

    // create the scene
//    NodePtr scene = makeTorus(.5, 2, 16, 16);
    NodePtr scene = Node::create();
    beginEditCP(scene);
    scene->setCore(Group::create());
    endEditCP(scene);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);
    
    DisplayFilterForegroundPtr fg = DisplayFilterForeground::create();

    beginEditCP(fg);
    // add filter
    endEditCP(fg);

    // take the viewport
    ViewportPtr vp = gwin->getPort(0);

    beginEditCP(vp);
    vp->editMFForegrounds()->push_back(fg);    
    endEditCP  (vp);

    colorFilterPtr = ColorDisplayFilter::create();
    distortionFilterPtr = DistortionDisplayFilter::create();
    resolutionFilterPtr = ResolutionDisplayFilter::create();

    beginEditCP(colorFilterPtr);
    beginEditCP(resolutionFilterPtr);
    beginEditCP(distortionFilterPtr);
    beginEditCP(fg);
    colorFilterPtr->setMatrix(osg::Matrix(0,0,1,0,
                                          1,0,0,0,
                                          0,1,0,0,
                                          0,0,0,1));
    resolutionFilterPtr->setDownScale(0.25);

    distortionFilterPtr->setColumns(2);
    distortionFilterPtr->setRows(2);
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(0,.5));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(.5,0));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(.5,1));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(1,.5));
    
    fg->editMFFilter()->push_back(colorFilterPtr);
    fg->editMFFilter()->push_back(resolutionFilterPtr);
    fg->editMFFilter()->push_back(distortionFilterPtr);

    endEditCP(distortionFilterPtr);
    endEditCP(colorFilterPtr);
    endEditCP(resolutionFilterPtr);
    endEditCP(fg);

    for(UInt32 a=1 ; a<argc ;a++)
    {
        NodePtr file = SceneFileHandler::the().read(argv[a],0);
        if(file != NullFC)
            scene->addChild(file);
        else
            std::cerr << "Couldn't load file, ignoring " << argv[a] << std::endl;
    }
	if ( scene->getNChildren() == 0 )
	{
        scene->addChild(makeTorus( .5, 2, 16, 16 ));
//        scene->addChild(makeBox(.6,.6,.6,5,5,5));
    }

    // show the whole scene
    mgr->showAll();
    
    // GLUT main loop
    glutMainLoop();

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

    std::string fontfile("testfont.ttf");
    std::string testtext("Test Text");
    UInt32 drawmode;
    
    if(argc > 1)
        testtext = argv[1];
    if(argc > 2)
        fontfile = argv[2];
    if(argc < 4 || sscanf(argv[3], "%d", &drawmode) != 1 )
        drawmode = FTGLFont::Outline;
        
    // GLUT 
    int winid = setupGLUT(&argc, argv);
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();
   
    
    // Create the Cubes node

    NodePtr scene = makeCoredNode<Group>();

    beginEditCP(scene);
    
    scene->addChild( makeBox(200,200,200, 1,1,1) );
//    scene->addChild( SceneFileHandler::the().read("tie.wrl") );
    endEditCP(scene);


    // Create the text
    
    FTGLFontPtr font = FTGLFont::create();
    
    beginEditCP(font);
    font->setName(fontfile);
    font->setDrawType(drawmode);
    font->setSize(40);
    font->setRes(72);
    font->setDepth(20);
    endEditCP(font);

    FTGLTextPtr text;
    NodePtr tnode = makeCoredNode<FTGLText>(&text);
    
    beginEditCP(text);
    text->setFont(font);
    text->setText(testtext);
    text->setPosition(Pnt3f(0,300,0));
    text->setMaterial(getDefaultMaterial());      
    endEditCP(text);
    

    beginEditCP(scene);
    scene->addChild(tnode);
    endEditCP(scene);
    
    
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    // show the whole scene
    mgr->showAll();
        
    // copy to second window 
    int winid2 = setupGLUT(&argc, argv);
    gwin2= GLUTWindow::create();
    gwin2->setId(winid2);
    gwin2->init();
    
    ViewportPtr ovp = gwin->getPort()[0];
    
    ViewportPtr vp = Viewport::create();
    
    beginEditCP(vp);
    vp->setLeft(0);
    vp->setRight(400);
    vp->setBottom(0);
    vp->setTop(400);
    vp->setCamera(ovp->getCamera());
    vp->setRoot(ovp->getRoot());
    vp->setBackground(ovp->getBackground());
    vp->setParent(gwin2);
    endEditCP(vp);
    
    beginEditCP(gwin2);
    gwin2->getPort().push_back(vp);
    endEditCP(gwin2);
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
void MultiDisplayWindow::serverRender(WindowPtr         serverWindow,
                                      UInt32            id,
                                      DrawActionBase *action )
{
    TileCameraDecoratorPtr deco;
    ViewportPtr serverPort;
    ViewportPtr clientPort;
    StereoBufferViewportPtr clientStereoPort;
    UInt32 sv,cv;
    Int32 l,r,t,b;
    Int32 cleft,cright,ctop,cbottom;

    // sync, otherwise viewports will be out of date

    if(!getHServers())
    {
        setHServers(getServers().size());
    }
    if(!getVServers())
    {
        setVServers(1);
    }

    UInt32 row   =id/getHServers();
    UInt32 column=id%getHServers();

    // calculate width and height from local width and height
    UInt32 width  = serverWindow->getWidth() ;
    UInt32 height = serverWindow->getHeight();

    if(getWidth()==0)
    {
        setWidth( width*getHServers() );
    }
    if(getHeight()==0)
    {
        setHeight( height*getVServers() );
    }

    Int32 left   = column * width  - column * getXOverlap();
    Int32 bottom = row    * height - row    * getYOverlap();
    Int32 right  = left   + width  - 1;
    Int32 top    = bottom + height - 1;
    Real64 scaleCWidth  =
        ((width - getXOverlap()) * (getHServers() - 1) + width) /
        (float)getWidth();
    Real64 scaleCHeight =
        ((height - getYOverlap())* (getVServers() - 1) + height)/
        (float)getHeight();

    bool   isVirtualPort = false;

    // duplicate viewports
    for(cv = 0, sv = 0; cv < getPort().size(); ++cv)
    {
        clientPort = getPort()[cv];

#if 0
        isVirtualPort = clientPort->getType().isDerivedFrom(FBOViewport::getClassType());

        if(isVirtualPort)
        {
            // TODO -- seems wrong to render this on all servers, though rendering
            // then transmitting the texture doesn't seem like a good idea either.
            if(serverWindow->getPort().size() <= sv)
            {
                serverPort = ViewportPtr::dcast(clientPort->shallowCopy());
                beginEditCP(serverWindow);
                serverWindow->addPort(serverPort);
                endEditCP(serverWindow);
            }
            else
            {
                serverPort = serverWindow->getPort()[sv];
                if(serverWindow->getPort()[sv]->getType() !=
                        clientPort->getType())
                {
                    // there is a viewport with the wrong type
                    subRefCP(serverWindow->getPort()[sv]);
                    serverPort = ViewportPtr::dcast(clientPort->shallowCopy());
                    beginEditCP(serverWindow);
                    {
                        serverWindow->getPort()[sv] = serverPort;
                    }
                    endEditCP(serverWindow);
                }
            }
            // update changed viewport fields
            updateViewport(serverPort,clientPort);
        }
        else
#endif
        {
            clientStereoPort =
                dynamic_cast<StereoBufferViewportPtr>(clientPort);

            cleft   = (Int32)(clientPort->getPixelLeft()      * scaleCWidth)   ;
            cbottom = (Int32)(clientPort->getPixelBottom()    * scaleCHeight)  ;
            cright  = (Int32)((clientPort->getPixelRight()+1) * scaleCWidth) -1;
            ctop    = (Int32)((clientPort->getPixelTop()+1)   * scaleCHeight)-1;

            if(cright  < left   ||
                    cleft   > right  ||
                    ctop    < bottom ||
                    cbottom > top      )
            {
                // invisible on this server screen
                continue;
            }

            // calculate overlapping viewport
            l = osgMax(cleft  ,left  ) - left;
            b = osgMax(cbottom,bottom) - bottom;
            r = osgMin(cright ,right ) - left;
            t = osgMin(ctop   ,top   ) - bottom;

            if(serverWindow->getPort().size() <= sv)
            {
                serverPort =
                    dynamic_cast<ViewportPtr>(clientPort->shallowCopy());

                deco = TileCameraDecorator::create();

                serverWindow->addPort(serverPort);

                serverPort->setCamera(deco);
            }
            else
            {
                serverPort = serverWindow->getPort()[sv];

                deco = dynamic_cast<TileCameraDecoratorPtr>(
                           serverPort->getCamera());

                if(serverWindow->getPort()[sv]->getType() !=
                        clientPort->getType())
                {
                    // there is a viewport with the wrong type
                    serverPort =
                        dynamic_cast<ViewportPtr>(clientPort->shallowCopy());

                    serverWindow->replacePort(sv,
                                              serverPort);//[sv] = serverPort;
                    serverPort->setCamera(deco);
                }
                else
                {
                    deco = dynamic_cast<TileCameraDecoratorPtr>(
                               serverPort->getCamera());
                }
            }

            // update changed viewport fields
            updateViewport(serverPort,clientPort);

            // set viewport size
            serverPort->setSize(Real32(l),Real32(b),Real32(r),Real32(t));

            // use pixel even if pixel = 1
            if(serverPort->getLeft() == 1.0)
                serverPort->setLeft(1.0001);

            if(serverPort->getRight() == 1.0)
                serverPort->setRight(1.0001);

            if(serverPort->getTop() == 1.0)
                serverPort->setTop(1.0001);

            if(serverPort->getBottom() == 1.0)
                serverPort->setBottom(1.0001);

            // calculate tile parameters
            deco->setFullWidth ( cright-cleft );
            deco->setFullHeight( ctop-cbottom );
            deco->setSize( ( l+left-cleft     ) / (float)( cright-cleft ),
                           ( b+bottom-cbottom ) / (float)( ctop-cbottom ),
                           ( r+left-cleft     ) / (float)( cright-cleft ),
                           ( t+bottom-cbottom ) / (float)( ctop-cbottom ) );
            deco->setDecoratee( clientPort->getCamera() );
        }
        sv++;
    }

    // remove unused ports
    while(serverWindow->getPort().size()>sv)
    {
        serverWindow->subPort(sv);
    }

    Inherited::serverRender(serverWindow,id,action);
}
示例#17
0
int main(int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    
    bool stereobuffer = false;
    bool amberblue = false;
    if(argc >= 2 && !strcmp(argv[1],"-s"))
    {
        stereobuffer = true;
        --argc, ++argv;
    }
    if(argc >= 2 && !strcmp(argv[1],"-a"))
    {
        amberblue = true;
        --argc, ++argv;
    }
    
    
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE |
                        (stereobuffer?GLUT_STEREO:0) );
    
    glutCreateWindow("OpenSG");
    
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    PassiveWindowPtr pwin=PassiveWindow::create();
    pwin->init();

    // create the scene
    NodePtr scene;
    
    if(argc > 1)
    {
        scene = SceneFileHandler::the().read(argv[1]);
    }
    else
    {
        scene = makeBox(2,2,2, 1,1,1);
    }

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // create the window and initial camera/viewport
    mgr->setWindow(pwin );
    // tell the manager what to manage
    mgr->setRoot  (scene);
    
    // now create the second vp for stereo
    ViewportPtr vp = pwin->getPort(0);
    
    PerspectiveCameraPtr cam = PerspectiveCameraPtr::dcast(vp->getCamera());
    beginEditCP(cam);
    cam->setFov(deg2rad(90));
    cam->setAspect(1);
    endEditCP  (cam);

    Navigator *nav = mgr->getNavigator();
    nav->setAt(Pnt3f(0,0,0));
    nav->setDistance(1.5);
    
    mgr->showAll();
    
    // create the decorators and the second viewport
    ViewportPtr vpleft,vpright;
       
    decoleft = ShearedStereoCameraDecorator::create();
    decoright = ShearedStereoCameraDecorator::create();
    
    beginEditCP(decoleft);
    decoleft->setEyeSeparation(ed);
    decoleft->setZeroParallaxDistance(zpp);
    decoleft->setLeftEye(true);  
    decoleft->setDecoratee(cam);  
    endEditCP  (decoleft);
    
    beginEditCP(decoright);
    decoright->setEyeSeparation(ed);
    decoright->setZeroParallaxDistance(zpp);
    decoright->setLeftEye(false);  
    decoright->setDecoratee(cam);  
    endEditCP  (decoright);

    if(amberblue)
    {
        ColorBufferViewportPtr svpleft = ColorBufferViewport::create();
        ColorBufferViewportPtr svpright = ColorBufferViewport::create();
 
        beginEditCP(svpleft);
        svpleft->setLeft(0);
        svpleft->setRight(1);
        svpleft->setBottom(0);
        svpleft->setTop(1);
        svpleft->setCamera(decoleft);
        svpleft->setBackground(vp->getBackground());
        svpleft->setRoot(vp->getRoot());
        svpleft->setRed(GL_TRUE);
        svpleft->setGreen(GL_TRUE);
        svpleft->setBlue(GL_FALSE);
        svpleft->setAlpha(GL_TRUE);
        endEditCP  (svpleft);
 
        beginEditCP(svpright);
        svpright->setLeft(0);
        svpright->setRight(1);
        svpright->setBottom(0);
        svpright->setTop(1);
        svpright->setCamera(decoright);
        svpright->setBackground(vp->getBackground());
        svpright->setRoot(vp->getRoot());
        svpright->setRed(GL_FALSE);
        svpright->setGreen(GL_FALSE);
        svpright->setBlue(GL_TRUE);
        svpright->setAlpha(GL_FALSE);
        endEditCP  (svpright);
        
        vpleft = svpleft;
        vpright = svpright;
    }
    else if(stereobuffer)
    {
        StereoBufferViewportPtr svpleft = StereoBufferViewport::create();
        StereoBufferViewportPtr svpright = StereoBufferViewport::create();
 
        beginEditCP(svpleft);
        svpleft->setLeft(0);
        svpleft->setRight(1);
        svpleft->setBottom(0);
        svpleft->setTop(1);
        svpleft->setCamera(decoleft);
        svpleft->setBackground(vp->getBackground());
        svpleft->setRoot(vp->getRoot());
        svpleft->setLeftBuffer(true);
        svpleft->setRightBuffer(false);
        endEditCP  (svpleft);
 
        beginEditCP(svpright);
        svpright->setLeft(0);
        svpright->setRight(1);
        svpright->setBottom(0);
        svpright->setTop(1);
        svpright->setCamera(decoright);
        svpright->setBackground(vp->getBackground());
        svpright->setRoot(vp->getRoot());
        svpright->setLeftBuffer(false);
        svpright->setRightBuffer(true);
        endEditCP  (svpright);
        
        vpleft = svpleft;
        vpright = svpright;
    }
    else
    {
        vpleft = vp;
        vpright = Viewport::create();

        beginEditCP(vpleft);
        vpleft->setLeft(0);
        vpleft->setRight(1);
        vpleft->setBottom(0);
        vpleft->setTop(0.5);
        endEditCP  (vpleft);

        beginEditCP(vpright);
        vpright->setLeft(0);
        vpright->setRight(1);
        vpright->setBottom(0.5);
        vpright->setTop(1);
        vpright->setBackground(vp->getBackground());
        vpright->setRoot(vp->getRoot());
        endEditCP  (vpright);
    }
    
    beginEditCP(vpleft);
    vpleft->setCamera(decoleft);
    endEditCP  (vpleft);
    
    beginEditCP(vpright);
    vpright->setCamera(decoright);
    endEditCP  (vpright);
 
    beginEditCP(pwin); 
    pwin->subPort(vp);  
    pwin->addPort(vpleft);  
    pwin->addPort(vpright);  
    endEditCP  (pwin); 

    // make it notice the changes
    mgr->setWindow(pwin );
    
    // show the whole scene
    mgr->showAll();
    
    // OpenGL info
    GLint val;
    
#define cv(v)\
    glGetIntegerv((v),&val);\
    printf("%s: %d\n", #v, val)
    
    cv(GL_RED_BITS);
    cv(GL_GREEN_BITS);
    cv(GL_BLUE_BITS);
    cv(GL_DEPTH_BITS);
    
    glEnable(GL_DEPTH_TEST);
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
void ApplicationBuilder::attachApplication(void)
{
	Inherited::attachApplication();

	beginEditCP(ApplicationBuilderPtr(this) , ApplicationBuilder::EditingProjectFieldMask);
		setEditingProject(MainApplication::the()->getProject());
	endEditCP(ApplicationBuilderPtr(this) , ApplicationBuilder::EditingProjectFieldMask);

	
	//Camera Beacon
	Matrix TransformMatrix;
	TransformPtr CameraBeaconTransform = Transform::create();
	beginEditCP(CameraBeaconTransform, Transform::MatrixFieldMask);
		CameraBeaconTransform->setMatrix(TransformMatrix);
	endEditCP(CameraBeaconTransform, Transform::MatrixFieldMask);

	NodePtr CameraBeaconNode = Node::create();
	beginEditCP(CameraBeaconNode, Node::CoreFieldMask);
		CameraBeaconNode->setCore(CameraBeaconTransform);
	endEditCP(CameraBeaconNode, Node::CoreFieldMask);

    // Make Main Scene Node empty
    NodePtr DefaultRootNode = osg::Node::create();
    beginEditCP(DefaultRootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
        DefaultRootNode->setCore(osg::Group::create());
        DefaultRootNode->addChild(CameraBeaconNode);
    endEditCP(DefaultRootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
	
	//Camera
	PerspectiveCameraPtr DefaultCamera = PerspectiveCamera::create();
	beginEditCP(DefaultCamera);
		DefaultCamera->setBeacon(CameraBeaconNode);
		DefaultCamera->setFov   (deg2rad(60.f));
		DefaultCamera->setNear  (0.1f);
		DefaultCamera->setFar   (10000.f);
	endEditCP(DefaultCamera);

	//Background
	SolidBackgroundPtr DefaultBackground = SolidBackground::create();
	beginEditCP(DefaultBackground, SolidBackground::ColorFieldMask);
		DefaultBackground->setColor(Color3f(0.0f,0.0f,0.0f));
	endEditCP(DefaultBackground, SolidBackground::ColorFieldMask);

	//Icon Manager
	_IconManager = DefaultIconManager::create();
	
	//User Interface
	ForegroundPtr UserInterfaceForeground = createInterface();
    beginEditCP(_TheBuilderInterface->getDrawingSurface(), UIDrawingSurface::EventProducerFieldMask);
        _TheBuilderInterface->getDrawingSurface()->setEventProducer(MainApplication::the()->getMainWindowEventProducer());
    endEditCP(_TheBuilderInterface->getDrawingSurface(), UIDrawingSurface::EventProducerFieldMask);

	//Viewport
	if(MainApplication::the()->getMainWindowEventProducer()->getWindow() != NullFC && MainApplication::the()->getMainWindowEventProducer()->getWindow()->getPort().size() == 0)
	{
		ViewportPtr DefaultViewport = Viewport::create();
		beginEditCP(DefaultViewport);
			DefaultViewport->setCamera                  (DefaultCamera);
			DefaultViewport->setRoot                    (DefaultRootNode);
			DefaultViewport->setSize                    (0.0f,0.0f, 1.0f,1.0f);
			DefaultViewport->setBackground              (DefaultBackground);
			DefaultViewport->getForegrounds().push_back    (UserInterfaceForeground);
		endEditCP(DefaultViewport);

		beginEditCP(MainApplication::the()->getMainWindowEventProducer()->getWindow(), Window::PortFieldMask);
			MainApplication::the()->getMainWindowEventProducer()->getWindow()->addPort(DefaultViewport);
		endEditCP(MainApplication::the()->getMainWindowEventProducer()->getWindow(), Window::PortFieldMask);
	}
}
示例#19
0
/*! update all changed viewport field from the client port
 */
void MultiDisplayWindow::updateViewport(ViewportPtr &serverPort,
                                        ViewportPtr &clientPort)
{
    bool equal, found;

    // Compare the pointers.
    if(serverPort == clientPort)
        return;
    if(serverPort == NullFC || clientPort == NullFC)
        return;
    if(serverPort->getType() != serverPort->getType())
        return;

    const FieldContainerType &type = serverPort->getType();
    UInt32 fcount = osgMin(serverPort->getType().getNumFieldDescs(),
                           clientPort->getType().getNumFieldDescs());

    BitVector ffilter = RemoteAspect::getFieldFilter(type.getId());

    for(UInt32 i = 1; i <= fcount; ++i)
    {
        const FieldDescription* fdesc = type.getFieldDescription(i);
        // ignore attachments
        if(strcmp(fdesc->getCName(), "parent") == 0 ||
           strcmp(fdesc->getCName(), "camera") == 0)
            continue;

        BitVector mask = fdesc->getFieldMask();

        // don't update filtered fields
        if(ffilter & mask)
            continue;

        Field *dst_field = serverPort->getField(i);
        Field *src_field = clientPort->getField(i);

        const FieldType &dst_ftype = dst_field->getType();
        const FieldType &src_ftype = src_field->getType();

        if(dst_ftype != src_ftype)
            continue;

        equal = true;
        found = false;

        if(strstr(dst_ftype.getCName(), "Ptr") == NULL)
        {
            // This is very slow with multi fields!!!!
            std::string av, bv;
            dst_field->getValueByStr(av);
            src_field->getValueByStr(bv);
            if(av != bv)
                equal = false;
        }
        else
        {
            if(dst_field->getCardinality() == FieldType::SINGLE_FIELD)
            {
                if((static_cast<SFFieldContainerPtr *>(dst_field)->getValue() !=
                    static_cast<SFFieldContainerPtr *>(src_field)->getValue()))
                    equal = false;
            }
            else if(dst_field->getCardinality() == FieldType::MULTI_FIELD)
            {
                UInt32 j, cn = static_cast<MFFieldContainerPtr*>(src_field)->size(),
                          sn = static_cast<MFFieldContainerPtr*>(src_field)->size();

                if (strcmp(fdesc->getCName(), "foregrounds") == 0)
                {
                    MFForegroundPtr sFgndBag;
                    MFForegroundPtr::const_iterator sFgndIt, cFgndIt;
                    DisplayFilterForegroundPtr filterFgnd = NullFC;

                    sFgndIt = serverPort->getMFForegrounds()->begin();
                    cFgndIt = clientPort->getMFForegrounds()->begin();

                    while (sFgndIt != serverPort->getMFForegrounds()->end())
                    {
                        filterFgnd = DisplayFilterForegroundPtr::dcast(*sFgndIt);

                        if (filterFgnd != NullFC &&
                           !filterFgnd->getServer().empty())
                            found = true;   // loaded filters found
                        else
                            sFgndBag.push_back(*sFgndIt);

                        ++sFgndIt;
                    }

                    if (sFgndBag.size() !=
                            clientPort->getMFForegrounds()->size())
                    {
                        equal = false;
                    }
                    else
                    {
                        sFgndIt = sFgndBag.begin();

                        while (sFgndIt != sFgndBag.end() &&
                               cFgndIt != clientPort->getMFForegrounds()->end() &&
                              *sFgndIt == *cFgndIt)
                        {
                            ++sFgndIt;
                            ++cFgndIt;
                        }

                        if (sFgndIt != sFgndBag.end() ||
                            cFgndIt != clientPort->getMFForegrounds()->end())
                            equal = false;
                    }
                }
                else
                {
                    if(static_cast<MFFieldContainerPtr*>(dst_field)->size() !=
                       static_cast<MFFieldContainerPtr*>(src_field)->size())
                    {
                        equal = false;
                    }
                    else
                    {
                        for(j=0;j < static_cast<MFFieldContainerPtr*>(dst_field)->size();++j)
                        {
                            if(((*(static_cast<MFFieldContainerPtr *>(dst_field)))[j] !=
                                (*(static_cast<MFFieldContainerPtr *>(src_field)))[j]))
                                equal = false;
                        }
                    }
                }
            }
        }
        if(equal == false)
        {
            beginEditCP(serverPort, mask);
            dst_field->setAbstrValue(*src_field);
            endEditCP(serverPort, mask);

            if (found)
            {
                ClusterWindowPtr ptr(this);

                beginEditCP(ptr, DirtyFieldMask);
                    setDirty(true);
                endEditCP(ptr, DirtyFieldMask);
            }
        }
    }
}
示例#20
0
int main(int argc, char **argv)
{
    osgInit(argc,argv);

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

    GLUTWindowPtr gwin=GLUTWindow::create();
    gwin->setId(id);
    gwin->init();

    // create the scene
//    NodePtr scene = makeTorus(.5, 2, 16, 16);
    NodePtr scene = makeBox(1,1,1, 1,1,1);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);
    
    // Create the textured material
    UChar8 imgdata[] =
      {  255,0,0,128,  0,255,0,128,  0,0,255,255,  255,255,255,255 };
   
    ImagePtr img = Image::create();
    beginEditCP(img);
    if(argc > 1)
        img->read(argv[1]);
    else
        img->set( Image::OSG_RGBA_PF, 2, 2, 1, 1, 1, 0, imgdata );
    endEditCP(img);
    addRefCP(img);
   
    SimpleTexturedMaterialPtr mat = SimpleTexturedMaterial::create();
    beginEditCP(mat);
    mat->setLit(false);
    mat->setDiffuse(Color3f(0,1,0));
    mat->setImage(img);
    mat->setMinFilter(GL_NEAREST);
    mat->setMagFilter(GL_NEAREST);
    mat->setEnvMode(GL_REPLACE);
    endEditCP(mat);
    
    // Add the polygon foregrounds
    
    Pnt2f pos[][4] = { 
        { Vec2f(.4,.4), Vec2f(.6,.4), Vec2f(.6,.6), Vec2f(.4,.6) },
        { Vec2f(0,0), Vec2f(1,0), Vec2f(1,.1), Vec2f(0,.1) },
        { Vec2f(1,-100), Vec2f(-2,-100), Vec2f(-2,-2), Vec2f(1,-2) },
        { Vec2f(-1000,-1000), Vec2f(0,0), Vec2f(0,0), Vec2f(0,0) }
    };
    bool normx[] = { true, true, false };
    bool normy[] = { true, true, false };
    
    for(UInt16 ind = 0; pos[ind][0][0] != -1000; ++ind)
    {   
        PolygonForegroundPtr pg = PolygonForeground::create();

        beginEditCP(pg);
        pg->setMaterial(mat);
        pg->editMFTexCoords()->push_back(Vec3f( 0.,0.,0.));
        pg->editMFPositions()->push_back(pos[ind][0]);
        pg->editMFTexCoords()->push_back(Vec3f( 1.,0.,0.));
        pg->editMFPositions()->push_back(pos[ind][1]);
        pg->editMFTexCoords()->push_back(Vec3f( 1.,1.,0.));
        pg->editMFPositions()->push_back(pos[ind][2]);
        pg->editMFTexCoords()->push_back(Vec3f( 0.,1.,0.));
        pg->editMFPositions()->push_back(pos[ind][3]);
 
        pg->setNormalizedX(normx[ind]);
        pg->setNormalizedY(normy[ind]);
        endEditCP(pg);

        // take the viewport
        ViewportPtr vp = gwin->getPort(0);

        beginEditCP(vp);
        vp->editMFForegrounds()->push_back(pg);    
        endEditCP  (vp);
    }
     
    // Create the edgeblend foreground
    const int blendpixel = 50;
    
    UChar8 ebimgdata[] =
      {  0,0,0,0,  0,0,0,255 };
   
    ImagePtr ebimg = Image::create();
    beginEditCP(ebimg);
    ebimg->set( Image::OSG_RGBA_PF, 2, 1, 1, 1, 1, 0, ebimgdata );
    endEditCP(ebimg);
    addRefCP(ebimg);
   
    TextureChunkPtr tc = TextureChunk::create();
    beginEditCP(tc);
    tc->setImage(ebimg);
    tc->setMinFilter(GL_NEAREST);
    tc->setMagFilter(GL_LINEAR);
    tc->setEnvMode(GL_REPLACE);
    tc->setWrapS(GL_CLAMP);
    endEditCP(tc);
    
    BlendChunkPtr bl = BlendChunk::create();
    beginEditCP(bl);
    bl->setSrcFactor(GL_SRC_ALPHA);
    bl->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);
    endEditCP(bl);
    
    ChunkMaterialPtr ebmat = ChunkMaterial::create();
    beginEditCP(ebmat);
    ebmat->addChunk(tc);
    ebmat->addChunk(bl);
    endEditCP(ebmat);

    PolygonForegroundPtr ebpg = PolygonForeground::create();

    beginEditCP(ebpg);
    ebpg->setMaterial(ebmat);
    ebpg->editMFTexCoords()->push_back(Vec3f( 0.25,0.,0.));
    ebpg->editMFTexCoords()->push_back(Vec3f( 0.75,0.,0.));
    ebpg->editMFTexCoords()->push_back(Vec3f( 0.75,1.,0.));
    ebpg->editMFTexCoords()->push_back(Vec3f( 0.25,1.,0.));

    ebpg->editMFPositions()->push_back(Pnt2f(-blendpixel-1, 0));
    ebpg->editMFPositions()->push_back(Pnt2f(           -1, 0));
    ebpg->editMFPositions()->push_back(Pnt2f(           -1, 1));
    ebpg->editMFPositions()->push_back(Pnt2f(-blendpixel-1, 1));

    ebpg->setNormalizedX(false);
    ebpg->setNormalizedY(true);
    endEditCP(ebpg);

    // take the viewport
    ViewportPtr vp = gwin->getPort(0);

    beginEditCP(vp);
    vp->editMFForegrounds()->push_back(ebpg);    
    endEditCP  (vp);

// show the whole scene
    mgr->showAll();
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#21
0
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );

    // OSG

    SceneFileHandler::the().print();

    // create the graph

    // beacon for camera and light
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore( b1 );
    endEditCP(b1n);

    // transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore( t1 );
    t1n->addChild( b1n );
    endEditCP(t1n);

    cam_trans = t1;

    // light

    NodePtr dlight = Node::create();
    DirectionalLightPtr dl = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore( dl );
    endEditCP(dlight);

    beginEditCP(dl);
    dl->setAmbient( .3, .3, .3, 1 );
    dl->setDiffuse( 1, 1, 1, 1 );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);
    endEditCP(dl);

    // root
    root = Node::create();
    GroupPtr gr1 = Group::create();
    beginEditCP(root);
    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );
    endEditCP(root);

    // Load the file

    NodePtr file = NullFC;

    if ( argc > 1 )
        file = SceneFileHandler::the().read(argv[1]);

    if ( file == NullFC )
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;
        file = makeTorus( .5, 2, 16, 16 );
    }

    file->updateVolume();

    Vec3f min,max;
    file->getVolume().getBounds( min, max );

    std::cout << "Volume: from " << min << " to " << max << std::endl;

    beginEditCP(dlight);
    dlight->addChild( file );
    endEditCP(dlight);

    std::cerr << "Tree: " << std::endl;
//  root->dump();

    // Camera

    cam = PerspectiveCamera::create();
    cam->setBeacon( b1n );
    cam->setFov( deg2rad( 90 ) );
    cam->setNear( 0.1 );
    cam->setFar( 10000 );

    // Background
    SolidBackgroundPtr bkgnd = SolidBackground::create();

    // Foreground
    GrabForegroundPtr fgnd = GrabForeground::create();

    image = Image::create();
    beginEditCP(image);
    image->set(Image::OSG_RGB_PF, 1);
    endEditCP(image);

    fgnd->setImage(image);

    // Viewport

    vp = Viewport::create();
    vp->setCamera( cam );
    vp->setBackground( bkgnd );
    vp->editMFForegrounds()->push_back( fgnd );
    vp->setRoot( root );
    vp->setSize( 0,0, 1,1 );

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr gwin;

    GLint glvp[4];
    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort( vp );

    win->init();

    // Action

    ract = DrawAction::create();

    // tball

    Vec3f pos( 0, 0, max[2] + ( max[2] - min[2] ) * 1.5 );

    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );

    // run...

    glutMainLoop();

    return 0;
}
// Initialize OpenSG and set up the scene
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);

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

    
    // 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 << "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 << "O       Toggle override status of TheSecondAnimation" << std::endl;
    std::cout << "CTRL-Q  Exit\n\n" << std::endl;


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

    //Skeleton materaial
    LineChunkPtr SkelLineChunk = LineChunk::create();
    beginEditCP(SkelLineChunk);
        SkelLineChunk->setWidth(0.0f);
        SkelLineChunk->setSmooth(true);
    endEditCP(SkelLineChunk);

    ChunkMaterialPtr SkelMaterial = ChunkMaterial::create();
    beginEditCP(SkelMaterial, ChunkMaterial::ChunksFieldMask);
        SkelMaterial->addChunk(SkelLineChunk);
    endEditCP(SkelMaterial, ChunkMaterial::ChunksFieldMask);

    //LOAD FIRST ANIMATION
    FCFileType::FCPtrStore NewContainers;
    NewContainers = FCFileHandler::the()->read(BoostPath("./Data/23WalkingAnimation.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 TheWalkingAnimation to the SkeletonAnimation we just read in
            TheWalkingAnimation = (SkeletonAnimation::Ptr::dcast(*Itor));
        }
        if( (*Itor)->getType() == (Geometry::getClassType()))
        {
            //Add the Geometry we just read in to GeometryPtrs
            GeometryPtrs.push_back(Geometry::Ptr::dcast(*Itor));
        }
    }

    //LOAD SECOND ANIMATION
    NewContainers = FCFileHandler::the()->read(BoostPath("./Data/23SamAnimation.xml"));
    for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor)
    {
         //Import only the skeletonAnimation from the second XML file; we've already imported the skeleton and the geometry
        if( (*Itor)->getType().isDerivedFrom(SkeletonAnimation::getClassType()))
        {
            TheSecondAnimation = (SkeletonAnimation::Ptr::dcast(*Itor));
        }
    }

    //Blend the two animations
    TheSkeletonBlendedAnimation = SkeletonBlendedAnimation::create();
    beginEditCP(TheSkeletonBlendedAnimation);
        TheSkeletonBlendedAnimation->addAnimationBlending(TheWalkingAnimation, BlendWalking, false);
        TheSkeletonBlendedAnimation->addAnimationBlending(TheSecondAnimation, BlendTouchScreen, false);
    endEditCP(TheSkeletonBlendedAnimation);


    
    //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);  //By default, we don't show the mesh in its bind pose.
        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(SkelMaterial);
            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);
    }



    //Setup scene
    NodePtr EmptyScene = osg::Node::create();
    beginEditCP(EmptyScene, Node::CoreFieldMask);
        EmptyScene->setCore(Group::create());
    endEditCP  (EmptyScene, Node::CoreFieldMask);

    mgr->setRoot(EmptyScene);



    //User Interface
    // Create the Graphics
    GraphicsPtr TutorialGraphics = osg::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

    // Create the DefaultBoundedRangeModelPtr and 
    // set its values
    DefaultBoundedRangeModelPtr UpperAnimationSliderRangeModel = DefaultBoundedRangeModel::create();
    UpperAnimationSliderRangeModel->setMinimum(0);
    UpperAnimationSliderRangeModel->setMaximum(100);
    UpperAnimationSliderRangeModel->setValue(BlendWalking * 100);
    UpperAnimationSliderRangeModel->setExtent(0);
    
    //Create the upper animation blend amount slider
    LabelPtr TempLabel;
    SliderPtr UpperAnimationSlider = Slider::create();
    beginEditCP(UpperAnimationSlider, Slider::LabelMapFieldMask | Slider::PreferredSizeFieldMask | Slider::MajorTickSpacingFieldMask | Slider::MinorTickSpacingFieldMask | Slider::SnapToTicksFieldMask | Slider::DrawLabelsFieldMask | Slider::RangeModelFieldMask);

     //Label the slider
        TempLabel = Label::Ptr::dcast(UpperAnimationSlider->getLabelPrototype()->shallowCopy());
        beginEditCP(TempLabel, Label::TextFieldMask); TempLabel->setText("0.0"); endEditCP(TempLabel, Label::TextFieldMask);
        UpperAnimationSlider->getLabelMap()[0] = TempLabel;

        TempLabel = Label::Ptr::dcast(UpperAnimationSlider->getLabelPrototype()->shallowCopy());
        beginEditCP(TempLabel, Label::TextFieldMask); TempLabel->setText("1.0"); endEditCP(TempLabel, Label::TextFieldMask);
        UpperAnimationSlider->getLabelMap()[100] = TempLabel;

        //Customize the slider
        UpperAnimationSlider->setPreferredSize(Vec2f(100, 300));
        UpperAnimationSlider->setSnapToTicks(false);
        UpperAnimationSlider->setMajorTickSpacing(10);
        UpperAnimationSlider->setMinorTickSpacing(5);
        UpperAnimationSlider->setOrientation(Slider::VERTICAL_ORIENTATION);
        UpperAnimationSlider->setInverted(true);
        UpperAnimationSlider->setDrawLabels(true);
        UpperAnimationSlider->setRangeModel(UpperAnimationSliderRangeModel);
    endEditCP(UpperAnimationSlider, Slider::LabelMapFieldMask | Slider::PreferredSizeFieldMask | Slider::MajorTickSpacingFieldMask | Slider::MinorTickSpacingFieldMask | Slider::SnapToTicksFieldMask | Slider::DrawLabelsFieldMask | Slider::RangeModelFieldMask);
    
    DefaultBoundedRangeModelPtr LowerAnimationSliderRangeModel = DefaultBoundedRangeModel::create();
    LowerAnimationSliderRangeModel->setMinimum(0);
    LowerAnimationSliderRangeModel->setMaximum(100);
    LowerAnimationSliderRangeModel->setValue(BlendTouchScreen * 100);
    LowerAnimationSliderRangeModel->setExtent(0);
    
    //Create the lower animation blend amount slider
    SliderPtr LowerAnimationSlider = Slider::create();
    beginEditCP(LowerAnimationSlider, Slider::LabelMapFieldMask | Slider::PreferredSizeFieldMask | Slider::MajorTickSpacingFieldMask | Slider::MinorTickSpacingFieldMask | Slider::SnapToTicksFieldMask | Slider::DrawLabelsFieldMask | Slider::RangeModelFieldMask);

     //Label the slider
        TempLabel = Label::Ptr::dcast(LowerAnimationSlider->getLabelPrototype()->shallowCopy());
        beginEditCP(TempLabel, Label::TextFieldMask); TempLabel->setText("0.0"); endEditCP(TempLabel, Label::TextFieldMask);
        LowerAnimationSlider->getLabelMap()[0] = TempLabel;

        TempLabel = Label::Ptr::dcast(LowerAnimationSlider->getLabelPrototype()->shallowCopy());
        beginEditCP(TempLabel, Label::TextFieldMask); TempLabel->setText("1.0"); endEditCP(TempLabel, Label::TextFieldMask);
        LowerAnimationSlider->getLabelMap()[100] = TempLabel;

        //Customize the slider
        LowerAnimationSlider->setPreferredSize(Vec2f(100, 300));
        LowerAnimationSlider->setSnapToTicks(false);
        LowerAnimationSlider->setMajorTickSpacing(10);
        LowerAnimationSlider->setMinorTickSpacing(5);
        LowerAnimationSlider->setOrientation(Slider::VERTICAL_ORIENTATION);
        LowerAnimationSlider->setInverted(true);
        LowerAnimationSlider->setDrawLabels(true);
        LowerAnimationSlider->setRangeModel(LowerAnimationSliderRangeModel);
    endEditCP(LowerAnimationSlider, Slider::LabelMapFieldMask | Slider::PreferredSizeFieldMask | Slider::MajorTickSpacingFieldMask | Slider::MinorTickSpacingFieldMask | Slider::SnapToTicksFieldMask | Slider::DrawLabelsFieldMask | Slider::RangeModelFieldMask);

    // Create Background to be used with the MainFrame
    ColorLayerPtr MainFrameBackground = osg::ColorLayer::create();
    beginEditCP(MainFrameBackground, ColorLayer::ColorFieldMask);
        MainFrameBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainFrameBackground, ColorLayer::ColorFieldMask);

    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerPtr MainInternalWindowBackground = osg::ColorLayer::create();
    beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);

    LayoutPtr MainInternalWindowLayout = osg::FlowLayout::create();

    //GL Viewport
    ComponentPtr TheGLViewport = createGLPanel();
    InternalWindowPtr MainInternalWindow = osg::InternalWindow::create();
    beginEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);
       MainInternalWindow->getChildren().push_back(UpperAnimationSlider);
       MainInternalWindow->getChildren().push_back(LowerAnimationSlider);
       MainInternalWindow->getChildren().push_back(TheGLViewport);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
       MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
       MainInternalWindow->setScalingInDrawingSurface(Vec2f(1.0f,1.0f));
       MainInternalWindow->setDrawTitlebar(false);
       MainInternalWindow->setResizable(false);
    endEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);

    // Create the Drawing Surface
    UIDrawingSurfacePtr TutorialDrawingSurface = UIDrawingSurface::create();
    beginEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindowEventProducer);
    endEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
    
    TutorialDrawingSurface->openWindow(MainInternalWindow);

    // Create the UI Foreground Object
    UIForegroundPtr TutorialUIForeground = osg::UIForeground::create();

    beginEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);
        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
    endEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);

    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialUIForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

    //Attach the Slider Listeners
    BlendAmountSliderChangeListener UpperAnimationSliderListener(TheSkeletonBlendedAnimation, 0, UpperAnimationSlider);
    UpperAnimationSlider->addChangeListener(&UpperAnimationSliderListener);
    
    BlendAmountSliderChangeListener LowerAnimationSliderListener(TheSkeletonBlendedAnimation, 1, LowerAnimationSlider);
    LowerAnimationSlider->addChangeListener(&LowerAnimationSliderListener);

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


    beginEditCP(TheAnimationAdvancer);

        //Create the Documentation
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);
    
    // 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,
                                        "23BlendXMLAnimations");

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

    osgExit();

    return 0;
}
示例#23
0
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);
    
    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);
    TutorialUpdateListener TheTutorialUpdateListener;
    TutorialWindowEventProducer->addUpdateListener(&TheTutorialUpdateListener);

    //Create Start and stop buttons for the caption
    ButtonPtr StartButton = osg::Button::create();
    ButtonPtr StopButton = osg::Button::create();
    ButtonPtr PauseButton = osg::Button::create();

    UIFontPtr ButtonFont = osg::UIFont::create();

    beginEditCP(ButtonFont, UIFont::SizeFieldMask);
        ButtonFont->setSize(16);
    endEditCP(ButtonFont, UIFont::SizeFieldMask);
    
    beginEditCP(StartButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);
            StartButton->setMinSize(Vec2f(50, 25));
            StartButton->setMaxSize(Vec2f(200, 100));
            StartButton->setPreferredSize(Vec2f(100, 50));
            StartButton->setToolTipText("This will start playing the caption!");

            StartButton->setText("START");
            StartButton->setFont(ButtonFont);
            StartButton->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            StartButton->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
            StartButton->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            StartButton->setAlignment(Vec2f(0.25,0.5));
    endEditCP(StartButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);

    beginEditCP(StopButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);
            StopButton->setMinSize(Vec2f(50, 25));
            StopButton->setMaxSize(Vec2f(200, 100));
            StopButton->setPreferredSize(Vec2f(100, 50));
            StopButton->setToolTipText("This will stop the caption and reset it!");

            StopButton->setText("STOP");
            StopButton->setFont(ButtonFont);
            StopButton->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            StopButton->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
            StopButton->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            StopButton->setAlignment(Vec2f(0.75,0.5));
    endEditCP(StopButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);

    beginEditCP(PauseButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);
            PauseButton->setMinSize(Vec2f(50, 25));
            PauseButton->setMaxSize(Vec2f(200, 100));
            PauseButton->setPreferredSize(Vec2f(100, 50));
            PauseButton->setToolTipText("This will Pause the caption!");

            PauseButton->setText("PAUSE");
            PauseButton->setFont(ButtonFont);
            PauseButton->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            PauseButton->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
            PauseButton->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
            PauseButton->setAlignment(Vec2f(0.5,0.5));
    endEditCP(PauseButton, Button::MinSizeFieldMask | Button::MaxSizeFieldMask | Button::PreferredSizeFieldMask | Button::ToolTipTextFieldMask | Button::TextFieldMask |
        Button::FontFieldMask | Button::TextColorFieldMask | Button::RolloverTextColorFieldMask | Button::ActiveTextColorFieldMask | Button::AlignmentFieldMask);


    StartButtonActionListener TheStartButtonActionListener;
    StartButton->addActionListener(&TheStartButtonActionListener);

    StopButtonActionListener TheStopButtonActionListener;
    StopButton->addActionListener(&TheStopButtonActionListener);

    PauseButtonActionListener ThePauseButtonActionListener;
    PauseButton->addActionListener(&ThePauseButtonActionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(MainWindow);
	
    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
        scene->addChild(TorusGeometryNode);
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);


    // Create the Graphics
    GraphicsPtr TutorialGraphics = osg::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

    
    LayoutPtr MainInternalWindowLayout = osg::FlowLayout::create();



    PanelPtr CaptionContainer = osg::Panel::create();

    beginEditCP(CaptionContainer, Panel::PreferredSizeFieldMask | Panel::LayoutFieldMask);
        CaptionContainer->setPreferredSize(Pnt2f(250.0,30.0));
        CaptionContainer->setLayout(MainInternalWindowLayout);
    endEditCP(CaptionContainer, Panel::PreferredSizeFieldMask | Panel::LayoutFieldMask);

    //Initialize the Sound Manager
    SoundManager::the()->attachUpdateProducer(TutorialWindowEventProducer);

    TutorialSound = SoundManager::the()->createSound();
    beginEditCP(TutorialSound, Sound::FileFieldMask | Sound::VolumeFieldMask | Sound::StreamingFieldMask | Sound::LoopingFieldMask);
        TutorialSound->setFile(Path("./Data/captionSoundFile.ogg"));
        TutorialSound->setVolume(1.0);
        TutorialSound->setStreaming(true);
        TutorialSound->setLooping(0);
    endEditCP(TutorialSound, Sound::FileFieldMask | Sound::VolumeFieldMask | Sound::StreamingFieldMask | Sound::LoopingFieldMask);

    // Create the Caption
    TutorialCaption = osg::Caption::create();

    //Add the segments of text to be displayed
    TutorialCaption->captionSegment("Listeners can be used for a variety",1.7,3.4);
    TutorialCaption->captionSegment("of different applications.",3.4,4.7);
    TutorialCaption->captionSegment("In this tutorial we will",5.0,6.35);
    TutorialCaption->captionSegment("simply be changing the background though.",6.35,8.0);
    TutorialCaption->captionSegment("First we will change the",8.8,10.2);
    TutorialCaption->captionSegment("torus on screen to a sphere.",10.2,11.75);
    TutorialCaption->captionSegment("By timing things correctly we can make",12.7,14.6);
    TutorialCaption->captionSegment("the changes right as the word is spoken.",14.6,16.75);
    TutorialCaption->captionSegment("Such as changing the sphere to a cube",17.3,20.0);
    TutorialCaption->captionSegment("but personally I would prefer",20.33,21.65);
    TutorialCaption->captionSegment("the background to be blank.",21.65,22.8);
    TutorialCaption->captionSegment("Much better!",23.8,25.0);


    //Add the tutorial Caption Listener to the Caption that was set up for the tutorial
    TutorialCaptionListener TheCaptionListener;
    TutorialCaption->addCaptionListener(&TheCaptionListener);

    //Create the Caption component Generator
    TutorialCapGen = DefaultCaptionComponentGenerator::create();

    TutorialCaption->attachWindowEventProducer(TutorialWindowEventProducer);
    beginEditCP(TutorialCaption, Caption::ParentContainerFieldMask | Caption::ComponentGeneratorFieldMask | Caption::CaptionDialogSoundFieldMask);
        TutorialCaption->setParentContainer(CaptionContainer);
        TutorialCaption->setComponentGenerator(TutorialCapGen);
        TutorialCaption->setCaptionDialogSound(TutorialSound);
    endEditCP(TutorialCaption, Caption::ParentContainerFieldMask | Caption::ComponentGeneratorFieldMask | Caption::CaptionDialogSoundFieldMask);


    //Create and modify the Label prototype that will be used for the caption
    LabelPtr LabelPrototype = Label::create();
    LabelPrototype->setAlignment(Pnt2f(0.5f,0.5f));
    LabelPrototype->setPreferredSize(Pnt2f(250.0,30.0));

    //Add the prototype to the Generator for use
    beginEditCP(TutorialCapGen, DefaultCaptionComponentGenerator::CaptionSegmentPrototypeFieldMask);
        TutorialCapGen->setCaptionSegmentPrototype(LabelPrototype);
    endEditCP(TutorialCapGen, DefaultCaptionComponentGenerator::CaptionSegmentPrototypeFieldMask);
    
    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerPtr MainInternalWindowBackground = osg::ColorLayer::create();
    MainInternalWindow = osg::InternalWindow::create();
    beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
	beginEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);
	   MainInternalWindow->getChildren().push_back(CaptionContainer);
	   MainInternalWindow->getChildren().push_back(StartButton);
	   MainInternalWindow->getChildren().push_back(StopButton);
       MainInternalWindow->getChildren().push_back(PauseButton);
    endEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);

    // Create the Drawing Surface
    UIDrawingSurfacePtr TutorialDrawingSurface = UIDrawingSurface::create();
    beginEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindowEventProducer);
    endEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);
	
	// Create the UI Foreground Object
    UIForegroundPtr TutorialUIForeground = osg::UIForeground::create();

    beginEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);
        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
    endEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);

    mgr->setRoot(scene);

    // Add the UI Foreground Object to the Scene
    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialUIForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

    // Show the whole Scene
    mgr->showAll();
    SoundManager::the()->setCamera(mgr->getCamera());


    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
            WinSize,
            "05Caption");

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


    osgExit();

    return 0;
}
示例#24
0
int main (int argc, char **argv)
{
	osgInit(argc,argv);

	// GLUT init

	glutInit(&argc, argv);
	glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	int winid = glutCreateWindow("OpenSG");
	glutKeyboardFunc(key);
	glutVisibilityFunc(vis);
	glutReshapeFunc(reshape);
	glutDisplayFunc(display);       
	glutMouseFunc(mouse);   
	glutMotionFunc(motion); 
	
	glutIdleFunc(display);	


    glEnable( GL_NORMALIZE );
    glEnable( GL_DEPTH_TEST );

	// OSG

	// create the graph

	// beacon for camera and light	
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
	beginEditCP(b1n);
	b1n->setCore( b1 );
	endEditCP(b1n);

	// transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
	beginEditCP(t1n);
	t1n->setCore( t1 );
	t1n->addChild( b1n );
	endEditCP(t1n);

	cam_trans = t1;

	// light
	
	NodePtr dlight = Node::create();
	headlight = DirectionalLight::create();

	beginEditCP(dlight);
	dlight->setCore( headlight );
	endEditCP(dlight);
	
	beginEditCP(headlight);
	headlight->setAmbient( .3, .3, .3, 1 );
	headlight->setDiffuse( 1, 1, 1, 1 );
	headlight->setSpecular( 1, 1, 1, 1 );
	headlight->setDirection(0,0,1);
	headlight->setBeacon( b1n);
	endEditCP(headlight);

	// root
    root = Node::create();
    GroupPtr gr1 = Group::create();
	beginEditCP(root);
	root->setCore( gr1 );
	root->addChild( t1n );
	root->addChild( dlight );
	endEditCP(root);

	// Create the scene

    NodePtr sroot = Node::create();

 	beginEditCP(dlight);
    dlight->addChild(sroot);
   	endEditCP(dlight);

    GroupPtr gr = Group::create();

    beginEditCP(sroot);
    sroot->setCore(gr);
    endEditCP(sroot);

    // a transform to move it around
 
    NodePtr tnode = Node::create();
    tr = Transform::create();
    beginEditCP(tnode);
    tnode->setCore( tr );
    endEditCP(tnode);

    beginEditCP(sroot);
    sroot->addChild(tnode);
    endEditCP(sroot);

    // the billboard
 
    NodePtr bnode = Node::create();
    bill = Billboard::create();
    beginEditCP(bnode);
    bnode->setCore( bill );
    endEditCP(bnode);

    beginEditCP(tnode);
    tnode->addChild(bnode);
    endEditCP(tnode);
  
    // a geometry to billboard
    NodePtr geo = makeTorus( .2, 1, 16, 3);

    beginEditCP(bnode);
    bnode->addChild( geo );
    endEditCP(bnode);
 
    // a geometry to lead the render action somewhere else
    geo = makePlane( 2, 2, 2, 2 );

    beginEditCP(sroot);
    sroot->addChild( geo );
    endEditCP(sroot);

    dlight->updateVolume();
        
    Vec3f min,max;
    dlight->getVolume().getBounds( min, max );
	
    std::cout << "Volume: from " << min << " to " << max << std::endl;

    //std::cerr << "Tree: " << std::endl;
    //root->dump();

	// Camera
	PerspectiveCameraPtr cam = PerspectiveCamera::create();

	cam->setBeacon( b1n );
	cam->setFov( deg2rad( 60 ) );
	cam->setNear( .1 );
	cam->setFar( 20. );

	// Background
	GradientBackgroundPtr bkgnd = GradientBackground::create();
	
	bkgnd->addLine( Color3f( 0,0,0 ), 0 );
	bkgnd->addLine( Color3f( .5,.5,0 ), 0.5 );
	bkgnd->addLine( Color3f( .7,.7,1 ), 0.5 );
	bkgnd->addLine( Color3f( 0,0,1 ), 1 );

	// Viewport

	ViewportPtr vp = Viewport::create();
	vp->setCamera( cam );
	vp->setBackground( bkgnd );
	vp->setRoot( root );
	vp->setSize( 0,0, 1,1 );

	// Window
	std::cout << "GLUT winid: " << winid << std::endl;

	GLUTWindowPtr gwin;

	GLint glvp[4];
	glGetIntegerv( GL_VIEWPORT, glvp );

	gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->setSize( glvp[2], glvp[3] );

	win = gwin;

	win->addPort( vp );

	// Actions
	
	dact = DrawAction::create();
	ract = RenderAction::create();

	// tball

	Vec3f pos(0,
              0,
              max[2] + 1.5 * (max[2] - min[2]));

	tball.setMode( Trackball::OSGObject );
	tball.setStartPosition( pos, true );
	tball.setSum( true );
	tball.setTranslationMode( Trackball::OSGFree );
    tball.setTranslationScale(10.);
	// run...
	
	glutMainLoop();
	
    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

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

    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);

    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    NodePtr scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
        scene->addChild(TorusGeometryNode);
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // Create the Graphics
    GraphicsPtr TutorialGraphics = osg::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

	//Create InventoryItems
	ExampleInventory = Inventory::create();
	GenericInventoryItemPtr ExampleItem1 = GenericInventoryItem::create();
	GenericInventoryItemPtr ExampleItem2 = GenericInventoryItem::create(); 
	GenericInventoryItemPtr ExampleItem3 = GenericInventoryItem::create(); 
	GenericInventoryItemPtr ExampleItem4 = GenericInventoryItem::create();
	GenericInventoryItemPtr ExampleItem5 = GenericInventoryItem::create();
	GenericInventoryItemPtr ExampleItem6 = GenericInventoryItem::create();
	GenericInventoryItemPtr ExampleItem7 = GenericInventoryItem::create();

	beginEditCP(ExampleItem1, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem1->setName(std::string("David K"));
		ExampleItem1->setDetails(std::string("Major: Human Computer Interaction \nDegree: PhD \nDepartment: Computer Science \nCollege: LAS"));
	endEditCP(ExampleItem1, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem2, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem2->setName(std::string("Eve W"));
		ExampleItem2->setDetails(std::string("Department: Genetics Development and Cell Biology\n\nCollege: Agriculture"));
	endEditCP(ExampleItem2, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem3, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem3->setName(std::string("Will S"));
		ExampleItem3->setDetails(std::string("Major: Art And Design\nDegree: BFA\nDepartment: Art and Design\nCollege: Design"));
	endEditCP(ExampleItem3, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem4, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem4->setName(std::string("Eric L"));
		ExampleItem4->setDetails(std::string("Major: Software Engineering\nDegree: BS\nDepartment: Software Engineering\nCollege: Engineering"));
	endEditCP(ExampleItem4, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem5, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem5->setName(std::string("Jeffery F"));
		ExampleItem5->setDetails(std::string("Major: Integrated Studio Arts\nDegree: BFA\nDepartment: Art and Design\nCollege: Design"));
	endEditCP(ExampleItem5, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem6, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem6->setName(std::string("Tao L"));
		ExampleItem6->setDetails(std::string("Major: Computer Engineering\nDegree: PhD\nDepartment: Computer Engineering\nCollege: Engineering"));
	endEditCP(ExampleItem6, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	beginEditCP(ExampleItem7, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);
		ExampleItem7->setName(std::string("Daniel G"));
		ExampleItem7->setDetails(std::string("Major: Computer Engineering\nDegree: BS\nDepartment: Computer Engineering\nCollege: Engineering"));
	endEditCP(ExampleItem7, InventoryItem::NameFieldMask | GenericInventoryItem::DetailsFieldMask);

	ExampleInventory->addItem(ExampleItem1);
	ExampleInventory->addItem(ExampleItem2);
	ExampleInventory->addItem(ExampleItem3);
	ExampleInventory->addItem(ExampleItem4);
	ExampleInventory->addItem(ExampleItem5);
	ExampleInventory->addItem(ExampleItem6);
	ExampleInventory->addItem(ExampleItem7);



    /******************************************************

            Create a List.  A List has several 
			parts to it:
			-ListModel: Contains the data which is to be
			    displayed in the List.  Data is added
				as shown below
			-ListCellRenderer: Creates the Components to
				be used within the List (the default
				setting is to create Labels using 
				the desired text).
			-ListSelectionModel: Determines how
				the List may be selected.

			To add values to the list:
            
            First, create SFStrings and use the 
            .setValue("Value") function to set their
            values.  Then, use the .pushBack(&SFStringName)
            to add them to the List.

            Next, create the CellRenderer and ListSelectionModel
            defaults.

            Finally, actually create the List.  Set
            its Model, CellRenderer, and SelectionModel
            as shown below.  Finally, choose the
            type of display for the List (choices outlined
            below).

    ******************************************************/

    // Add data to it
	ExampleListModel = InventoryListModel::create();
    beginEditCP(ExampleListModel, InventoryListModel::CurrentInventoryFieldMask);
	    ExampleListModel->setCurrentInventory(ExampleInventory);
    endEditCP(ExampleListModel, InventoryListModel::CurrentInventoryFieldMask);
    

    /******************************************************

            Create ListCellRenderer and 
			ListSelectionModel.  Most 
			often the defauls will be used.
			
			Note: the ListSelectionModel was
			created above and is referenced
			by the ActionListeners.

    ******************************************************/    


    /******************************************************

            Create List itself and assign its 
			Model, CellRenderer, and SelectionModel
			to it.
			-setOrientation(ENUM): Determine the
				Layout of the cells (Horizontal
				or Vertical).  Takes List::VERTICAL_ORIENTATION
				and List::HORIZONTAL_ORIENTATION arguments.

    ******************************************************/    
    ExampleList = List::create();
	beginEditCP(ExampleList, List::PreferredSizeFieldMask | List::OrientationFieldMask | List::ModelFieldMask);
        ExampleList->setPreferredSize(Vec2f(200, 300));
        ExampleList->setOrientation(List::VERTICAL_ORIENTATION);
        //ExampleList->setOrientation(List::HORIZONTAL_ORIENTATION);
		ExampleList->setModel(ExampleListModel);
    endEditCP(ExampleList, List::PreferredSizeFieldMask | List::OrientationFieldMask | List::ModelFieldMask);

    ExampleList->setSelectionModel(ExampleListSelectionModel);
	InventoryListListener TheInventoryListListener;
    ExampleList->getSelectionModel()->addListSelectionListener(&TheInventoryListListener);


	// Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerPtr MainInternalWindowBackground = osg::ColorLayer::create();
    beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
    endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask);

    /******************************************************

            Determine the SelectionModel
            -SINGLE_SELECTION lets you select ONE item
                via a single mouse click
            -SINGLE_INTERVAL_SELECTION lets you select
                one interval via mouse and SHIFT key
            -MULTIPLE_INTERVAL_SELECTION lets you select
                via mouse, and SHIFT and CONTRL keys

            Note: this tutorial is currently set up
            to allow for this to be changed via 
			TogggleButtons with ActionListeners attached 
            to them so this code is commented out.

    ******************************************************/

    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_INTERVAL_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::MULTIPLE_INTERVAL_SELECTION);

    // Create a ScrollPanel for easier viewing of the List (see 27ScrollPanel)
    ScrollPanelPtr ExampleScrollPanel = ScrollPanel::create();
	beginEditCP(ExampleScrollPanel, ScrollPanel::PreferredSizeFieldMask | ScrollPanel::HorizontalResizePolicyFieldMask | ScrollPanel::BackgroundFieldMask);
        ExampleScrollPanel->setPreferredSize(Vec2f(200,100));
		ExampleScrollPanel->setBackgrounds(MainInternalWindowBackground);
        ExampleScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
        //ExampleScrollPanel->setVerticalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
    endEditCP(ExampleScrollPanel, ScrollPanel::PreferredSizeFieldMask | ScrollPanel::HorizontalResizePolicyFieldMask | ScrollPanel::BackgroundFieldMask);
    ExampleScrollPanel->setViewComponent(ExampleList);

    // Create MainFramelayout
    FlowLayoutPtr MainInternalWindowLayout = osg::FlowLayout::create();
    beginEditCP(MainInternalWindowLayout, FlowLayout::OrientationFieldMask | FlowLayout::MajorAxisAlignmentFieldMask | FlowLayout::MinorAxisAlignmentFieldMask);
	MainInternalWindowLayout->setOrientation(FlowLayout::HORIZONTAL_ORIENTATION);
        MainInternalWindowLayout->setMajorAxisAlignment(0.5f);
        MainInternalWindowLayout->setMinorAxisAlignment(0.5f);
    endEditCP(MainInternalWindowLayout, FlowLayout::OrientationFieldMask | FlowLayout::MajorAxisAlignmentFieldMask | FlowLayout::MinorAxisAlignmentFieldMask);
    
    

	DetailsWindow = osg::TextArea::create();
	beginEditCP(DetailsWindow, TextArea::PreferredSizeFieldMask);
		DetailsWindow->setPreferredSize(Pnt2f(200,100));
		DetailsWindow->setMinSize(Vec2f(200,100));
    endEditCP(DetailsWindow, TextArea::PreferredSizeFieldMask);

    InternalWindowPtr MainInternalWindow = osg::InternalWindow::create();
	beginEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);
       MainInternalWindow->getChildren().push_back(ExampleScrollPanel);
       MainInternalWindow->getChildren().push_back(DetailsWindow);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.7f,0.5f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);
    endEditCP(MainInternalWindow, InternalWindow::ChildrenFieldMask | InternalWindow::LayoutFieldMask | InternalWindow::BackgroundsFieldMask | InternalWindow::AlignmentInDrawingSurfaceFieldMask | InternalWindow::ScalingInDrawingSurfaceFieldMask | InternalWindow::DrawTitlebarFieldMask | InternalWindow::ResizableFieldMask);

    // Create the Drawing Surface
    UIDrawingSurfacePtr TutorialDrawingSurface = UIDrawingSurface::create();
    beginEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindowEventProducer);
    endEditCP(TutorialDrawingSurface, UIDrawingSurface::GraphicsFieldMask | UIDrawingSurface::EventProducerFieldMask);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);

    // Create the UI Foreground Object
    UIForegroundPtr TutorialUIForeground = osg::UIForeground::create();

    beginEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);
        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
    endEditCP(TutorialUIForeground, UIForeground::DrawingSurfaceFieldMask);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

    // Add the UI Foreground Object to the Scene
    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialUIForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

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

    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
            WinSize,
            "09Inventory");

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


    osgExit();

    return 0;
}
ComponentPtr createGLPanel(void)
{
    //Create the nessicary parts for a viewport

    //Camera Beacon
    Matrix TransformMatrix;
    TransformMatrix.setTranslate(0.0f,0.0f, 0.0f);
    TransformPtr CameraBeaconTransform = Transform::create();
    beginEditCP(CameraBeaconTransform, Transform::MatrixFieldMask);
        CameraBeaconTransform->setMatrix(TransformMatrix);
    endEditCP(CameraBeaconTransform, Transform::MatrixFieldMask);

    NodePtr CameraBeaconNode = Node::create();
    beginEditCP(CameraBeaconNode, Node::CoreFieldMask);
        CameraBeaconNode->setCore(CameraBeaconTransform);
    endEditCP(CameraBeaconNode, Node::CoreFieldMask);

    //Light Beacon
    Matrix LightTransformMatrix;
    LightTransformMatrix.setTranslate(0.0f,0.0f, 0.0f);
    TransformPtr LightBeaconTransform = Transform::create();
    beginEditCP(LightBeaconTransform, Transform::MatrixFieldMask);
        LightBeaconTransform->setMatrix(TransformMatrix);
    endEditCP(LightBeaconTransform, Transform::MatrixFieldMask);

    NodePtr LightBeaconNode = Node::create();
    beginEditCP(LightBeaconNode, Node::CoreFieldMask);
        LightBeaconNode->setCore(CameraBeaconTransform);
    endEditCP(LightBeaconNode, Node::CoreFieldMask);
    
    //Light Node
    DirectionalLightPtr TheDirectionLight = DirectionalLight::create();
    beginEditCP(TheDirectionLight, DirectionalLight::DirectionFieldMask);
        TheDirectionLight->setDirection(0.0f,1.0f,0.0f);
    endEditCP(TheDirectionLight, DirectionalLight::DirectionFieldMask);

    NodePtr LightNode = Node::create();
    beginEditCP(LightNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
        LightNode->setCore(TheDirectionLight);
        LightNode->addChild(createScene());
    endEditCP(LightNode, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // Make Torus Node (creates Torus in background of scene)
    NodePtr GeometryNode = makeTorus(.5, 2, 32, 32);

    // Make Main Scene Node and add the Torus
    NodePtr DefaultRootNode = osg::Node::create();
    beginEditCP(DefaultRootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
        DefaultRootNode->setCore(osg::Group::create());
        DefaultRootNode->addChild(CameraBeaconNode);
        DefaultRootNode->addChild(LightBeaconNode);
        DefaultRootNode->addChild(LightNode);
    endEditCP(DefaultRootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);

    //Camera
    PerspectiveCameraPtr DefaultCamera = PerspectiveCamera::create();
     beginEditCP(DefaultCamera);
         DefaultCamera->setBeacon(CameraBeaconNode);
         DefaultCamera->setFov   (deg2rad(60.f));
         DefaultCamera->setNear  (0.1f);
         DefaultCamera->setFar   (100.f);
     endEditCP(DefaultCamera);

    //Background
    GradientBackgroundPtr DefaultBackground = GradientBackground::create();
    beginEditCP(DefaultBackground, GradientBackground::ColorFieldMask | GradientBackground::PositionFieldMask);
        DefaultBackground->addLine(Color3f(0.0f,0.0f,0.0f), 0.0f);
        DefaultBackground->addLine(Color3f(0.0f,0.0f,1.0f), 1.0f);
    endEditCP(DefaultBackground, GradientBackground::ColorFieldMask | GradientBackground::PositionFieldMask);
    
    //Viewport
    ViewportPtr DefaultViewport = Viewport::create();
    beginEditCP(DefaultViewport);
        DefaultViewport->setCamera                  (DefaultCamera);
        DefaultViewport->setRoot                    (DefaultRootNode);
        DefaultViewport->setSize                    (0.0f,0.0f, 1.0f,1.0f);
        DefaultViewport->setBackground              (DefaultBackground);
    endEditCP(DefaultViewport);

    //GL Viewport Component

    GLViewportPtr TheGLViewport = GLViewport::create();
    beginEditCP(TheGLViewport, GLViewport::PortFieldMask | GLViewport::PreferredSizeFieldMask | GLViewport::BordersFieldMask);
        TheGLViewport->setPort(DefaultViewport);
        TheGLViewport->setPreferredSize(Vec2f(1024.0f,768.0f));
    endEditCP(TheGLViewport, GLViewport::PortFieldMask | GLViewport::PreferredSizeFieldMask | GLViewport::BordersFieldMask);
    
    TheGLViewport->showAll();

    return TheGLViewport;
}
示例#27
0
void BinarySwapComposer::composeViewport(ViewportPtr port)
{
    // setup viewport
    GLint 
        pl=port->getPixelLeft(), 
        pr=port->getPixelRight(),
        pb=port->getPixelBottom(), 
        pt=port->getPixelTop();
    GLint pw=pr-pl+1,ph=pt-pb+1;
    bool full = port->isFullWindow();
    glViewport(pl, pb, pw, ph);
    glScissor(pl, pb, pw, ph);
    if(! full)
        glEnable(GL_SCISSOR_TEST);

    GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
    GLboolean blend = glIsEnabled(GL_BLEND);

    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, port->getPixelWidth(),
            0, port->getPixelHeight(),-1,1);

//    printf("max %x,%x\n",_intDepthMax,_shortDepthMax);

    if(getAlpha())
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }
    _tilesX = port->getPixelWidth()  / getTileSize() + 1;
    _tilesY = port->getPixelHeight() / getTileSize() + 1;

    _tileBufferSize = getTileSize()*getTileSize()*8+sizeof(TileBuffer);
    _readTile.resize(_tileBufferSize);

    _statistics.bytesIn  = 0;
    _statistics.bytesOut = 0;

    if(isClient())
    {
        if(getShort())
        {
            UInt16 colorDummy;
            UInt32 depthDummy;
            recvFromServers(depthDummy,colorDummy,
                            GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5,
                            port);
        }
        else
        {
            if(getAlpha())
            {
                UInt32 colorDummy;
                UInt32 depthDummy;
                recvFromServers(depthDummy,colorDummy,
                                GL_RGBA,
                                GL_UNSIGNED_BYTE,
                                port);
            }
            else
            {
                RGBValue colorDummy;
                UInt32   depthDummy;
                recvFromServers(depthDummy,colorDummy,
                                GL_RGB,
                                GL_UNSIGNED_BYTE,
                                port);
            }
        }
        if(getStatistics())
        {
            UInt32      maxIn   = _statistics.bytesIn;
            UInt32      maxOut  = _statistics.bytesOut;
            UInt32      maxIO   = maxIn + maxOut;
            UInt32      sumOut  = _statistics.bytesOut;
            UInt32      missing = _usableServers;
            double      composeTime = 1e32;
            
            Connection *server;
            Statistics  statistics;
            for(UInt32 i=0 ; i<_usableServers ;++i)
            {
                server = clusterWindow()->getNetwork()->getConnection(i);
                server->selectChannel();
                server->get(&statistics,sizeof(Statistics));
                sumOut += statistics.bytesOut;
                if(statistics.composeTime < composeTime)
                    composeTime = statistics.composeTime;
                if(statistics.bytesOut > maxOut)
                    maxOut = statistics.bytesOut;
                if(statistics.bytesIn > maxIn)
                    maxIn = statistics.bytesIn;
                if(statistics.bytesIn + statistics.bytesOut > maxIO)
                    maxIO = statistics.bytesIn + statistics.bytesOut;
                missing--;
            }
            printf("compose Time     : %1.5lf\n",composeTime);
            printf("Transfered bytes : %10d\n",sumOut);
            printf("Max out          : %10d\n",maxOut);
            printf("Max in           : %10d\n",maxIn);
            printf("Max io           : %10d\n",maxIO);
        }
    }
    else
    {
        if(clusterId() < _usableServers)
        {
            _statistics.composeTime = -getSystemTime();
            _tile.resize(_tileBufferSize * _tilesX * _tilesY);
            if(getShort())
            {
                UInt16 colorDummy;
                UInt32 depthDummy=_shortDepthMax;
//                UInt32 depthDummy=_intDepthMax;
                startReader(depthDummy,colorDummy,
//                            GL_UNSIGNED_SHORT,
                            GL_UNSIGNED_INT,
                            GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5,
                            port);
            }
            else
            {
                if(getAlpha())
                {
                    UInt32 colorDummy;
                    UInt32 depthDummy=_intDepthMax;
                    startReader(depthDummy,colorDummy,
                                GL_UNSIGNED_INT,
                                GL_RGBA,
                                GL_UNSIGNED_BYTE,
                                port);
                }
                else
                {
                    RGBValue colorDummy;
                    UInt32   depthDummy=_intDepthMax;
                    startReader(depthDummy,colorDummy,
                                GL_UNSIGNED_INT,
                                GL_RGB,
                                GL_UNSIGNED_BYTE,
                                port);
                }
            }
            _statistics.composeTime += getSystemTime();
            if(getStatistics())
            {
                Connection *client = clusterWindow()->getNetwork()->getConnection(serverCount());
                client->put(&_statistics,sizeof(Statistics));
                client->flush();
            }
        }
/*
        // max depth value !! find a better way
        glClear(GL_DEPTH_BUFFER_BIT);
        glReadPixels(0, 0, 1, 1, 
                     GL_DEPTH_COMPONENT, GL_UNSIGNED_INT,
                     &_intDepthMax);
        glReadPixels(0, 0, 1, 1, 
                     GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT,
                     &_shortDepthMax);
*/
    }

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glEnable(GL_DEPTH_TEST);

    // reset state
    if(depth && !glIsEnabled(GL_DEPTH_TEST))
        glEnable(GL_DEPTH_TEST);
    if(!blend && glIsEnabled(GL_BLEND))
        glDisable(GL_BLEND);
}
	virtual void  initialize(void)
	{
		// Check necessary stuff
		if(_win == NullFC)
		{
			FWARNING(("SceneManager::initialize: window not set, "
					  "ignoring!\n"));
			return;
		}
	    
		// the rendering action
		_ownAction = RenderAction::create();
		_action = _ownAction;

		// the camera and light beacon
		NodePtr cartN = Node::create();
		_cart = Transform::create();

		beginEditCP(cartN);
			cartN->setCore(_cart);
		endEditCP(cartN);

		// the headlight
		_internalRoot = Node::create();
		_headlight    = DirectionalLight::create();

		addRefCP(_internalRoot);
		beginEditCP(_internalRoot);
			_internalRoot->setCore(_headlight);
			_internalRoot->addChild(cartN);
		endEditCP(_internalRoot);

		beginEditCP(_headlight);
			_headlight->setAmbient  (.3, .3, .3, 1);
			_headlight->setDiffuse  ( 1,  1,  1, 1);
			_headlight->setSpecular ( 1,  1,  1, 1);
			_headlight->setDirection( 0,  0,  1);
			_headlight->setBeacon   (cartN);
		endEditCP(_headlight);

		// the camera
		_camera = PerspectiveCamera::create();
		addRefCP(_camera);
		beginEditCP(PerspectiveCameraPtr::dcast(_camera));
			PerspectiveCameraPtr::dcast(_camera)->setBeacon(cartN);
			PerspectiveCameraPtr::dcast(_camera)->setFov   (deg2rad(60.f));
			PerspectiveCameraPtr::dcast(_camera)->setNear  (0.1f);
			PerspectiveCameraPtr::dcast(_camera)->setFar   (10000.f);
		endEditCP(PerspectiveCameraPtr::dcast(_camera));

		// need a viewport?
		if(_win->getPort().size() == 0)
		{
			SolidBackgroundPtr bg = SolidBackground::create();
			beginEditCP(bg);
				bg->setColor(Color3f(0, 0, 0));
			endEditCP(bg);

			ViewportPtr vp = Viewport::create();
			beginEditCP(vp);
				vp->setCamera                  (_camera);
				vp->setRoot                    (_internalRoot);
				vp->setSize                    (0,0, 1,1);
				vp->setBackground              (bg);
			endEditCP(vp);

			beginEditCP(_win);
				_win->addPort(vp);
			endEditCP(_win);
		}

	}
示例#29
0
文件: Main.cpp 项目: fohr/Graphtane
	void setupScene()
	{
		m_window->getViewports().front()->setRenderQueueIdMask(~RenderQueueId_OffscreenTransparentObjects);

		LightPtr light(new Light);
		light->setDirection(glm::normalize(glm::vec3(1.5, -1, -0.5)));
		light->setPosition(glm::vec3(0, 0.5, 0) + light->getDirection() * -10.0f);
		m_visSystem->addLight(light);

		// Volume
		std::vector<std::string> gridNames;
		gridNames.push_back(m_config.densityGridName);

		if (!m_config.temperatureGridName.empty())
		{
			gridNames.push_back(m_config.temperatureGridName);
		}

		std::vector<openvdb::GridBase::Ptr> baseGrids = loadGridsFromFile(m_config.vdbVilename, gridNames);

		openvdb::FloatGrid::Ptr densityGrid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrids[0]);

		openvdb::FloatGrid::Ptr temperatureGrid;
		if (!m_config.temperatureGridName.empty())
		{
			temperatureGrid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrids[1]);

			// Rescale temperature field to between 0 and 1
			{
				float minValue = 99999999999999;
				float maxValue = -99999999999999;
				for (openvdb::FloatGrid::ValueOnCIter iter = temperatureGrid->cbeginValueOn(); iter.test(); ++iter) {
					float value = *iter;
					minValue = std::min(minValue, value);
					maxValue = std::max(maxValue, value);
				}

				float scale = 1.0 / (maxValue - minValue);

				for (openvdb::FloatGrid::ValueOnIter iter = temperatureGrid->beginValueOn(); iter.test(); ++iter) {
					float value = *iter;
					value = (value - minValue) * scale;
					iter.setValue(value);
				}
			}

			// Ensure both grids have the same hierarchy
			{
				openvdb::FloatGrid::Ptr resultGrid = openvdb::FloatGrid::create();
				resultGrid->tree().combine2(densityGrid->tree(), temperatureGrid->tree(), CopyBIntoA());
				temperatureGrid->tree().combine(densityGrid->tree(), CopyBIntoA());

				densityGrid = resultGrid; 
			}
		}

		std::vector<GridPtr> grids;
		GridTextureRolesMap gridTextureRoles;

		grids.push_back(GridPtr(new VdbGrid<openvdb::FloatGrid>(densityGrid, 1)));
		gridTextureRoles[GridTextureRole_Diffuse] = grids.back();

		if (m_config.generateNormals)
		{
			Vec3UByteGrid::Ptr normalGrid = createNormalGrid(*densityGrid);
			grids.push_back(GridPtr(new VdbGrid<Vec3UByteGrid>(normalGrid, 3)));
			gridTextureRoles[GridTextureRole_Normal] = grids.back();
		}

		if (temperatureGrid)
		{
			grids.push_back(GridPtr(new VdbGrid<openvdb::FloatGrid>(temperatureGrid, 1)));
			gridTextureRoles[GridTextureRole_Temperature] = grids.back();
		}

		openvdb::CoordBBox bbox;
		densityGrid->constTree().evalLeafBoundingBox(bbox);

		float scale = 1.0f / (float)bbox.extents().asVec3s().length();

		glm::vec3 center = toVec3(bbox.getCenter() * scale);
		std::ostringstream ss;
		ss << "Grid extents: " << bbox.extents().x() << ", " << bbox.extents().y() << ", " << bbox.extents().z();
		defaultLogger()->logLine(ss.str());

		int renderQueueId;
		if (m_config.renderToLowResTarget)
		{
			renderQueueId = RenderQueueId_OffscreenTransparentObjects;
		}
		else
		{
			renderQueueId = getDefaultRenderQueueId();
		}

		RenderableVolumeConfig config;
		config.grids = grids;
		config.materialFactory.reset(new SparseVolumeMaterialFactoryI(gridTextureRoles, m_config.transparent, m_config.opacityMultiplier));
		config.scale = scale;
		config.batchBoxes = !m_config.transparent; // don't batch if we have transparency so we can sort

		RenderableVolumePtr volume = RenderableVolumeFactory::createRenderableVolume(config);
		BOOST_FOREACH(const GVis::RenderableNodePtr& node, volume->nodes)
		{
			node->translate(-center);
			m_visSystem->addRenderableNode(node, renderQueueId);
		}

		if (m_config.transparent)
		{
			RenderQueuePtr renderQueue = m_visSystem->getRenderQueue(renderQueueId);
			if (renderQueue)
				renderQueue->setSortingMode(RenderSortingMode_BackToFront);
		}

		if (m_config.renderToLowResTarget)
		{
			int volumeTargetWidth = m_window->getWidth() / 2;
			int volumeTargetHeight = m_window->getHeight() / 2;

			TexturePtr offscreenTransparentObjectsTexture;
			// Create offscreen transparent objects target
			{
				ImageTextureConfig config = ImageTextureConfig::createDefault();
				config.width = volumeTargetWidth;
				config.height = volumeTargetHeight;
				config.textureAddressMode = TextureAddressMode_Clamp;
				offscreenTransparentObjectsTexture.reset(new Texture(config));

				{
					RenderTextureTargetConfig config;
					config.texture = offscreenTransparentObjectsTexture;
					config.attachment = FrameBufferAttachment_Color;
					RenderTextureTargetPtr target(new RenderTextureTarget(config));

					{
						ViewportPtr viewport = target->addDefaultViewport(m_camera);
						viewport->setRenderQueueIdMask(RenderQueueId_OffscreenTransparentObjects);
						viewport->setBackgroundColor(glm::vec4(0,0,0,0));
					}

					m_window->addRenderTarget(target);
				}
			}

			// Composite offscreen particles
			{
				TextureUnit textureUnit(offscreenTransparentObjectsTexture, "albedoSampler");

				ShaderProgramPtr shader = ShaderProgram::createShaderProgram(ShaderProgramConfig("Shaders/Common/ScreenQuad.vert", "Shaders/Common/SimpleTextured.frag"));
				TechniquePtr technique(new Technique(shader));
				technique->addTextureUnit(textureUnit);
				technique->setAlphaBlendingMode(AlphaBlendingMode_PreMultiplied);
				MaterialPtr material(new Material);
				material->setTechnique(technique);

				{
					RectangleConfig config = RectangleConfig::defaultWithSize(glm::vec2(2, 2));
					MeshPtr mesh = RectangleMeshFactory::createMesh(config);
					GeoPtr geo(new Geo(mesh, material));
					
					RenderableNodePtr renderableNode = RenderableNode::createWithSingleGeo(geo);
					m_visSystem->addRenderableNode(renderableNode, RenderQueueId_CompositeOffscreenTransparentObjects);
				}
			}
		}

		if (m_config.orbitCam)
		{
			centerNode.reset(new SceneNode);
			centerNode->addChild(m_camera);
			m_cameraInputEnabled = false;
		}
		m_camera->setPosition_parentSpace(glm::vec3(0,0,1.4));
	}
示例#30
0
void ParallelComposer::composeViewport(ViewportPtr port)
{
#ifdef OSG_WITH_PARALLEL
    // setup viewport
    GLint 
        pl=port->getPixelLeft(), 
        pr=port->getPixelRight(),
        pb=port->getPixelBottom(), 
        pt=port->getPixelTop();
    if(_wWidth != pr-pl+1 || _wHeight != pt-pb+1)
    {
        _wWidth = pr-pl+1;
        _wHeight= pt-pb+1;
        _createContext = true;
    }
    bool full = port->isFullWindow();
    glViewport(pl, pb, _wWidth, _wHeight);
    glScissor(pl, pb, _wWidth, _wHeight);
    if(! full)
        glEnable(GL_SCISSOR_TEST);

    GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
    GLboolean blend = glIsEnabled(GL_BLEND);

    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, port->getPixelWidth(),
            0, port->getPixelHeight(),-1,1);

    if(_createContext)
    {
        createCtx(port);
        _createContext = false;
    }

    if(getAlpha())
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    if(isClient())
    {
        UInt32 id = beginFrame();
        renderRead();
        endFrame(id);
        drawFrame();
    }
    else
    {
        if(clusterId() < _usableServers)
        {
            UInt32 id = beginFrame();
            renderRead();
            endFrame(id);
            //drawFrame();
        }
    }
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glEnable(GL_DEPTH_TEST);

    // reset state
    if(depth && !glIsEnabled(GL_DEPTH_TEST))
        glEnable(GL_DEPTH_TEST);
    if(!blend && glIsEnabled(GL_BLEND))
        glDisable(GL_BLEND);
#endif
}