Geometry绘制自定义图形:
主要就设置顶点、颜色、法线以及 PrimitiveSet 绘制模式。
osg::Geode* geode = new osg::Geode;
osg::Geometry* geo = new osg::Geometry;
osg::Vec3Array* v = new osg::Vec3Array;
osg::Vec4Array* c = new osg::Vec4Array;
osg::Vec3Array* n = new osg::Vec3Array;
v->push_back(osg::Vec3f(0.0, 0.0, 0.0));
v->push_back(osg::Vec3f(1.0, 0.0, 0.0));
v->push_back(osg::Vec3f(0.0, 1.0, 0.0));
v->push_back(osg::Vec3f(-1.0, 0.0, 0.0));
v->push_back(osg::Vec3f(0.0, 0.0, 0.0));
geo->setVertexArray(v);
c->push_back(osg::Vec4f(1.0, 1.0, 1.0, 1.0));
geo->setColorArray(c, osg::Array::BIND_OVERALL);
n->push_back(osg::Vec3f(0.0, 0.0, 1.0));
geo->setNormalArray(n, osg::Array::BIND_OVERALL);
geo->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP, 0, v->size()));
geode->addDrawable(geo);
root->addChild(geode);
运行效果:
更新修改绘制数据:
osg::Vec4Array* color = dynamic_cast<osg::Vec4Array*>(geo->getColorArray());
(*color)[0] = osg::Vec4f(0.0, 1.0, 0.0, 1.0);
osg::Vec3Array* ver = dynamic_cast<osg::Vec3Array*>(geo->getVertexArray());
ver->clear();
ver->push_back(osg::Vec3f(0.0, 0.0, 0.0));
ver->push_back(osg::Vec3f(1.0, 0.0, 0.0));
ver->push_back(osg::Vec3f(1.0, 1.0, 0.0));
ver->push_back(osg::Vec3f(-1.0, 1.0, 0.0));
ver->push_back(osg::Vec3f(-1.0, 0.0, 0.0));
ver->push_back(osg::Vec3f(0.0, 0.0, 0.0));
//如果更新的顶点数与原始顶点数不同,则需要获取当前PrimitiveSet设置绘制的顶点数量
osg::DrawArrays* drawable = dynamic_cast<osg::DrawArrays*>(geo->getPrimitiveSet(0));
drawable->setCount(ver->size());
geo->dirtyDisplayList();
运行效果:
绘制带边线图形(多 PrimitiveSet 绘制):
osg::Geode* geode = new osg::Geode;
osg::Geometry* geo = new osg::Geometry;
osg::Vec3Array* v = new osg::Vec3Array;
osg::Vec4Array* c = new osg::Vec4Array;
osg::Vec3Array* n = new osg::Vec3Array;
v->push_back(osg::Vec3f(0.0, 0.0, 0.0));
v->push_back(osg::Vec3f(1.0, 0.0, 0.0));
v->push_back(osg::Vec3f(0.0, 1.0, 0.0));
v->push_back(osg::Vec3f(-1.0, 0.0, 0.0));
v->push_back(osg::Vec3f(0.0, 0.0, 0.0));
geo->setVertexArray(v);
//设置两种颜色,并以BIND_PER_PRIMITIVE_SET进行绑定
c->push_back(osg::Vec4f(1.0, 1.0, 1.0, 1.0));
c->push_back(osg::Vec4f(1.0, 0.0, 0.0, 1.0));
geo->setColorArray(c, osg::Array::BIND_PER_PRIMITIVE_SET);
n->push_back(osg::Vec3f(0.0, 0.0, 1.0));
geo->setNormalArray(n, osg::Array::BIND_OVERALL);
//设置两个PrimitiveSet,一个以LINE_STRIP绘制,一个以POLYGON绘制
geo->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP, 0, v->size()));
geo->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON, 0, v->size()));
//设置线宽
osg::StateSet* stateSet = geode->getOrCreateStateSet();
stateSet->setAttributeAndModes(new osg::LineWidth(3.0));
geode->addDrawable(geo);
root->addChild(geode);
运行效果: