思路:在osg中创建结点, 比如Geometry对象, 然后给该对象添加DrawCallback, 在这个DrawCallback中使用opengl进行绘制。
(1)继承osg::Drawable::DrawCallback,在
drawImplementation(osg::RenderInfo& renderInfo,const osg::Drawable* drawable)函数里添加opengl代码。
(2)Drawable设置绘制回调函数,并注意要把显示列表设置为false:
geometry->setUseDisplayList(false);
geometry->setDrawCallback(new DrawCallback);
步骤:
1.新建CLR控制台程序
2.添加包含目录,库目录和链接器输入。
具体配置参考:windows10 下OSG+VS环境搭建
// osgdemo2.cpp: 主项目文件。
#include "stdafx.h"
#include <windows.h>
#include <osgViewer/Viewer>
#include <osg/Group>
#include <osg/Geometry>
#pragma comment( lib, "osgd.lib") //.在Debug版本下的库名都加d,如"osgd.lib"
#pragma comment( lib, "osgDBd.lib")
#pragma comment( lib, "osgViewerd.lib")
#pragma comment( lib, "osgUtild.lib")
//opengl的头文件和库文件
#include <gl/gl.h>
#include <gl/glu.h>
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glu32.lib")
///两种方法:1. 在osg中创建结点, 比如Geometry对象, 然后给该对象添加DrawCallback, 在这个DrawCallback中使用opengl进行绘制
class DrawCallback : public osg::Drawable::DrawCallback
{
virtual void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* drawable) const
{
static double dColor = 0;//颜色
glColor3f(dColor, 0, 0);
glBegin(GL_TRIANGLES);//在OSG中画一个opengl三角形
glVertex3f(0.0, 0.0, -2.0);
glVertex3f(0.2, 0.0, -2.0);
glVertex3f(0.0, 0.4, -2.0);
glEnd();
dColor += 0.01;//颜色渐变
if (dColor > 1.0)
{
dColor = 0.0;
}
}
};
int main(int argc, char **argv)
{
osgViewer::Viewer viewer;
osg::Geometry* geometry = new osg::Geometry;
//此处一定要把显示列表设置为false,
//否则DrawCallback的drawImplementation()函数只会调用一次,而不是在画一帧时都动态更新opengl图形
geometry->setUseDisplayList(false);
geometry->setDrawCallback(new DrawCallback);//Drawable设置动态更新opengl图形
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
osg::Group* group = new osg::Group;
group->addChild(geode);
viewer.setSceneData(group);
//return viewer.run();
osg::Matrix mt;
mt.makeIdentity();
while (!viewer.done())
{
viewer.getCamera()->setViewMatrix(mt);
viewer.frame();
}
}