OSG-简单的绘制一个坐标轴

学习了可绘制Drawable的基本知识,打算绘制一个简单的坐标轴。


效果图如下:

OSG-简单的绘制一个坐标轴_第1张图片


代码如下:

osg::Geode* makeCoordinate()
{
    osg::ref_ptr pSphereShape = new osg::Sphere(osg::Vec3(0,0,0), 10.0f);
    osg::ref_ptr pShapeDrawable = new osg::ShapeDrawable(pSphereShape.get());
    pShapeDrawable->setColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));

    //创建保存几何信息的对象
    osg::ref_ptr geom = new osg::Geometry();

    //创建四个顶点
    osg::ref_ptr v = new osg::Vec3Array();
    v->push_back(osg::Vec3(0.0f, 0.0f, 0.0f));
    v->push_back(osg::Vec3(1000.0f, 0.0f, 0.0f));
    v->push_back(osg::Vec3(0.0f, 0.0f, 0.0f));
    v->push_back(osg::Vec3(0.0f, 1000.0f, 0.0f));
    v->push_back(osg::Vec3(0.0f, 0.0f, 0.0f));
    v->push_back(osg::Vec3(0.0f, 0.0f, 1000.0f));
    geom->setVertexArray(v.get());


    //为每个顶点指定一种颜色
    osg::ref_ptr c = new osg::Vec4Array();
    c->push_back(osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f)); //坐标原点为红色
    c->push_back(osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f)); //x red
    c->push_back(osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f)); //坐标原点为绿色
    c->push_back(osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f)); //y green
    c->push_back(osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f)); //坐标原点为蓝色
    c->push_back(osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f)); //z blue
    //如果没指定颜色则会变为黑色
    geom->setColorArray(c.get());
    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX); 


    //三个轴
    geom->addPrimitiveSet( new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 2)); //X
    geom->addPrimitiveSet( new osg::DrawArrays(osg::PrimitiveSet::LINES, 2, 2)); //Y
    geom->addPrimitiveSet( new osg::DrawArrays(osg::PrimitiveSet::LINES, 4, 2)); //Z


    osg::ref_ptr pTextXAuxis = new osgText::Text;
    pTextXAuxis->setText(L"X轴");
    pTextXAuxis->setFont("Fonts/simhei.ttf");
    pTextXAuxis->setAxisAlignment(osgText::Text::SCREEN);
    pTextXAuxis->setCharacterSize(64);
    pTextXAuxis->setPosition(osg::Vec3(1000.0f, 0.0f, 0.0f));

    osg::ref_ptr pTextYAuxis = new osgText::Text;
    pTextYAuxis->setText(L"Y轴");
    pTextYAuxis->setFont("Fonts/simhei.ttf");
    pTextYAuxis->setAxisAlignment(osgText::Text::SCREEN);
    pTextYAuxis->setCharacterSize(64);
    pTextYAuxis->setPosition(osg::Vec3(0.0f, 1000.0f, 0.0f));

    osg::ref_ptr pTextZAuxis = new osgText::Text;
    pTextZAuxis->setText(L"Z轴");
    pTextZAuxis->setFont("Fonts/simhei.ttf");
    pTextZAuxis->setAxisAlignment(osgText::Text::SCREEN);
    pTextZAuxis->setCharacterSize(64);
    pTextZAuxis->setPosition(osg::Vec3(0.0f, 0.0f, 1000.0f));

    osg::ref_ptr geode = new osg::Geode();
    geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    geode->getOrCreateStateSet()->setAttribute(new osg::LineWidth(3.0),  osg::StateAttribute::ON);

    geode->addDrawable(pShapeDrawable.get());
    geode->addDrawable(geom.get());
    geode->addDrawable(pTextXAuxis.get());
    geode->addDrawable(pTextYAuxis.get());
    geode->addDrawable(pTextZAuxis.get());

    return geode.release();
}


你可能感兴趣的:(OSG)