我想在MFC MDI应用程序中嵌入OpenGL应用程序,即openscenegraph库。我已经创建了MFC应用程序作为标签式MDI文档,它从CView类派生MainForm和ChildForm,通常交换控件的窗口句柄和OpenGL渲染上下文(有一些初始化)足以让场景在控件中显示。我希望OpenGL场景位于子窗体内。
上述场景的问题是,首先我不知道从CView类派生MDI是否正确,或者不同的类更适合于此目的。其次,使用下面的代码m_hWnd总是返回零,因此无法初始化上下文。
CChildFrame::CChildFrame()
{
// TODO: add member initialization code here
osgViewer::Viewer viewer;
//osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
RECT rect;
HWND hw;
hw = m_hWnd;
::GetWindowRect(m_hWnd, &rect);
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
// Init the Windata Variable that holds the handle for the Window to display OSG in.
osg::ref_ptr<osg::Referenced> windata = new osgViewer::GraphicsWindowWin32::WindowData(m_hWnd);
// Setup the traits parameters
traits->x = 0;
traits->y = 0;
traits->width = rect.right - rect.left;
traits->height = rect.bottom - rect.top;
traits->windowDecoration = false;
traits->doubleBuffer = true;
traits->sharedContext = 0;
traits->setInheritedWindowPixelFormat = true;
traits->inheritedWindowData = windata;
// Create the Graphics Context
osg::GraphicsContext* gc = osg::GraphicsContext::createGraphicsContext(traits.get());
// Init a new Camera (Master for this View)
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
// Assign Graphics Context to the Camera
camera->setGraphicsContext(gc);
// Set the viewport for the Camera
camera->setViewport(new osg::Viewport(traits->x, traits->y, traits->width, traits->height));
// Set projection matrix and camera attribtues
camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
camera->setClearColor(osg::Vec4f(0.2f, 0.2f, 0.4f, 1.0f));
camera->setProjectionMatrixAsPerspective(
30.0f, static_cast<double>(traits->width) / static_cast<double>(traits->height), 1.0, 1000.0);
// Add the Camera to the Viewer
//mViewer->addSlave(camera.get());
viewer.setCamera(camera.get());
// Add the Camera Manipulator to the Viewer
viewer.setCameraManipulator(new osgGA::OrbitManipulator());
osg::ref_ptr<osg::Group> root = new osg::Group;
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -0.5f), 100.0f, 100.0f, 1.0f)));
root->addChild(geode.get());
viewer.setSceneData(root.get());
viewer.realize();
}